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
376 changed files with 8134 additions and 11431 deletions

No files matched your search

@@ -15,7 +15,6 @@ namespace mbts.spark {
using mbts.ui.utility;
using mbts.utils;
using Spark.Core;
using Spark.Core.Collections;
using Spark.ViewModel.Commands;
@@ -34,13 +33,13 @@ namespace mbts.spark {
class AnalyticsExpirationParametersVM : DisposableViewModelBase, IHandleRowSelection {
readonly IBus _bus;
readonly ObservableCollection<AnalyticsExpirationParameters> _parameters = new();
readonly DeferrableAction _sync_visible_rows;
readonly DeferrableActionWrapper _sync_visible_rows;
readonly Property<AnalyticsExpirationParametersRowVM?> _copy_row_source;
readonly Property<bool> _auto_copy_rolls_is_checked;
readonly Property<bool> _auto_copy_rates_is_checked;
readonly DelegateProperty<bool> _is_dirty;
readonly ObservableHashSet<AnalyticsExpirationParametersRowVM> _selected_rows = new();
readonly DeferrableAction _raise_selected_rows_changed;
readonly DeferrableActionWrapper _raise_selected_rows_changed;
readonly IRaiseCanExecuteChangedCommand _set_driver_to_nearest_exp_cmd;
AnalyticsExpirationParametersMap? _parameter_map;
@@ -82,24 +81,24 @@ namespace mbts.spark {
selected_rows_changed += _ => _set_driver_to_nearest_exp_cmd.RaiseCanExecuteChanged();
_dispose = Disposable.Create(
_selected_rows.Subscribe((s, e) => _raise_selected_rows_changed.Invoke()),
_selected_rows.Subscribe((s, e) => _raise_selected_rows_changed.execute()),
ObservableAutoWrapper.connect(_parameters, rows, p => new(this, p), r => r.Dispose()),
ObservableAutoWrapper.connect(
non_options,
explicit_drivers,
sec => new ExpirationDriverImmutable(new() { Security = sec.to_api_sec_exp() })),
rows.Subscribe((s, e) => _sync_visible_rows.Invoke()),
rows.Subscribe((s, e) => _sync_visible_rows.execute()),
_bus.subscribe(SparkTags.ExpirationParametersInputTag).OnDispatcher().Subscribe(
CompositeObserver.create(
Observer.Create<AnalyticsExpirationParametersMap>(_on_parameter_map),
can_commit_observer.wrap<bool, AnalyticsExpirationParametersMap>(m => m is not null))),
ObservableAutoWrapper.connect_item_hooks(selected_symbols, sym => {
if (selected_symbol_ref_count.increment_adds_key(sym)) {
_sync_visible_rows.Invoke();
_sync_visible_rows.execute();
}
return Disposable.Create(() => {
if (selected_symbol_ref_count.decrement_removes_key(sym)) {
_sync_visible_rows.Invoke();
_sync_visible_rows.execute();
}
});
}),
@@ -197,11 +196,9 @@ namespace mbts.spark {
void _set_driver_to_nearest_exp(IEnumerable<AnalyticsExpirationParametersRowVM> rows) {
foreach (var r in rows) {
if (drivers
.Where(d => d.HasSecurity && d.Security.Symbol == r.security.symbol)
.TryGetMinElement(
d => (r.security.expiration - d.Security.Expiration.date_time()).Ticks.abs(),
out var nearest_exp)) {
if (drivers.Where(d => d.HasSecurity).TryGetMinElement(
d => (r.security.expiration - d.Security.Expiration.date_time()).Ticks.abs(),
out var nearest_exp)) {
r.driver = nearest_exp;
}
}
@@ -288,7 +285,7 @@ namespace mbts.spark {
}
symbols.sync_with(_parameters.Select(p => p.security.symbol).Distinct().Ordered());
using var _ = _sync_visible_rows.defer();
using var _ = _sync_visible_rows.defer_execution();
if (is_first_update) {
// select all symbols on first update
selected_symbols.sync_with(symbols);
@@ -32,7 +32,7 @@ namespace mbts.spark {
public SingleVolSurfaceRequestCalculator(int vs_id, IEnumerable<string> symbols,
ThreadedBlackboard threaded_bb) {
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator cons vs_id: {vs_id}");
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator cons vs_id:{vs_id}");
_vs_id = vs_id;
_symbols = new HashSet<string>(symbols);
_bb = threaded_bb;
@@ -89,8 +89,8 @@ namespace mbts.spark {
effective_req.cascade_up,
effective_req.cascade_down);
_timer.stop();
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator._recompute_and_publish time: " +
$"{_timer.lastIntervalTime}");
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator._recompute_and_publish time:" +
$"{_timer.lastIntervalTime} vs_output:{_last_output.log_string()}");
_bb.post(SparkTags.VolSurfaceCalculationResponseTag(_vs_id),
new VolSurfaceCalculationResponse(_last_output, effective_req.request_id));
}
@@ -11,22 +11,18 @@ namespace mbts.analytics {
// tags, into IReadOnlyDictionary of symbol vs data publsihed under one tag
public class SymbolAggregationPublisher<TData> : IDisposable {
private readonly ThreadedBlackboard _bb;
private readonly SecurityType _sec_type;
Func<string, ITag<TData>> _get_tag;
// the tag on which the output will be published
ITag<IReadOnlyDictionary<string, TData>> _out_tag;
private readonly ITag<SystemContractData> _sc_data_tag;
Func<string, ITag<TData>> _get_tag;
ITag<IReadOnlyDictionary<string, TData>> _out_tag;
private Dictionary<string, ITag<TData>> _tag_map =
new Dictionary<string, ITag<TData>>();
private HashSet<object> _obj_tags = new HashSet<object>();
private bool _dirty = true;
public SymbolAggregationPublisher(
ThreadedBlackboard bb,
SecurityType sec_type,
Func<string, ITag<TData>> get_tag,
ITag<IReadOnlyDictionary<string, TData>> out_tag) {
_bb = bb;
_sec_type = sec_type;
_get_tag = get_tag;
_out_tag = out_tag;
_sc_data_tag = SparkTags.SystemContractsTag;
@@ -52,20 +48,15 @@ namespace mbts.analytics {
return;
}
foreach (var st in sc_data.sectup_map) {
if (st.security_type != _sec_type) {
continue;
}
// this is not correct since it is assuming symbol/name is
// unique across securty_tuples
string symbol = st.security_name;
if (!_tag_map.ContainsKey(symbol)) {
var tag = _get_tag(symbol);
if (tag != null) {
_tag_map.Add(symbol, tag);
_obj_tags.Add(tag);
_bb.subscribe(tag);
_dirty = true;
}
var symbol_tag = _get_tag(symbol);
_tag_map.Add(symbol, symbol_tag);
_obj_tags.Add(symbol_tag);
_bb.subscribe(symbol_tag);
_dirty = true;
}
}
}
@@ -16,7 +16,6 @@ using System.Collections;
using mbts.spark;
using System.DirectoryServices.ActiveDirectory;
using Spark.Core.Protobuf;
using mbts.ui;
// using mbts.bb;
namespace mbts.spark {
@@ -102,14 +101,11 @@ namespace mbts.spark {
_subs.Add(new AnalyticsParametersManager(bus, _analytics_service));
_subs.Add(new ResourceAllocator(bus, _bb));
_subs.Add(new SymbolAggregationPublisher<OptionDriverPriceMap>(
_bb, SecurityType.Option, sym => SparkTags.OptionDriverBBOTag(sym),
_bb, (sym) => SparkTags.OptionDriverBBOTag(sym),
SparkTags.AllOptionDriverBBOTag));
_subs.Add(new SymbolAggregationPublisher<OptionTheoInterpolationData>(
_bb, SecurityType.Option, sym => SparkTags.SymbolInterpGreeksTag(sym),
_bb, (sym) => SparkTags.SymbolInterpGreeksTag(sym),
SparkTags.AllInterpGreeks));
_subs.Add(new SymbolAggregationPublisher<ExpStrikeKeyedData<TheoPoint>>(
_bb, SecurityType.Option, sym => SparkTags.TC2Tags.LiveTheosTag(sym),
SparkTags.TC2Tags.AllLiveTheosTag));
_subs.Add(new LiveTheoPublisher(_bb));
_subs.Add(new VolSurfaceInterpGreeksMultiplexer(_bb));
// usage
@@ -142,7 +138,6 @@ namespace mbts.spark {
var list_imm = new VolSurfaceUsageListImmutable(ulist);
Log.Ui.info(list_imm.log_string());
_bb.post(SparkTags.VolSurfaceUsageTag, list_imm);
_spin_vss(list_imm);
});
_disps.Add(list_sub);
}
@@ -151,13 +146,6 @@ namespace mbts.spark {
return _bb;
}
void _spin_vss(VolSurfaceUsageListImmutable ulist) {
foreach (var u in ulist.UsageList) {
var vs_id = u.VsId;
_bb.post(SparkTags.VolSurfaceActiveUITag(vs_id), true);
}
}
void _on_vs_usage_update(Update<VolSurfaceUsageListImmutable, int> update) {
// TODO
return;
@@ -6,7 +6,6 @@
using mbts.user.settings;
using System;
using System.Collections.Generic;
public class VolSurfaceDisplayGridColumn : IEquatable<VolSurfaceDisplayGridColumn> {
public readonly Func<object, string> format;
@@ -19,19 +18,16 @@
VolSurfaceColumnSettings settings,
Func<object, string> format = null,
Func<string, object> parse = null,
Func<object, bool, object> tick_move = null,
IEqualityComparer<object> comparer = null) {
Func<object, bool, object> tick_move = null) {
this.settings = settings;
this.format = format ?? (v => v?.ToString() ?? string.Empty);
this.parse = parse ?? (v => v);
this.tick_move = tick_move ?? ((v, is_up) => v);
this.comparer = comparer ?? EqualityComparer<object>.Default;
}
public string unique_col_name => settings.id;
public string display_name => settings.display_name;
public string group => settings.group;
public IEqualityComparer<object> comparer { get; }
internal VolSurfaceColumnType type => settings.type;
@@ -7,7 +7,6 @@
using mbts.user.settings;
using System;
using System.Collections.Generic;
class VolSurfaceDisplayUtilities {
public static TickDisplaySettings default_tick_display =>
@@ -19,10 +18,6 @@
default_tick_display.with(display_multiplier: 100);
public static double parse_double(object obj) {
if (obj is null) {
Log.Gen.warn("parse_double received null input (will return nan and continue)");
return double.NaN;
}
Log.assert(obj is double);
obj = obj ?? Double.NaN;
double rv = obj is Double ? (double)obj : (Double.TryParse(obj.ToString(), out rv) ? rv : Double.NaN);
@@ -54,31 +49,9 @@
}
public static Func<object, bool, object> get_double_tickmove(TickFactors tick_factors, int tick_move) =>
(data, is_up) => {
if (data is not double dbl) {
return data;
}
if (dbl.is_nan()) {
return 0D;
}
return tick_factors.tick(dbl, is_up ? tick_move : -tick_move);
};
public static IEqualityComparer<double> get_double_comparer(
TickFactors tick_factors = null, double display_mult = double.NaN) {
if (tick_factors is null) {
return new TickFactors(10^7, 1).tick_equality_comparer();
}
// This equality comparer is used to compare actual values (not multiplied by
// 'display_mult'), while the TickFactors are used to format the display value (multiplied
// by 'display_mult'). Multiply the tick base by 'display_mult' so the equality comparison
// is done with the correct number of decimal places.
if (display_mult > 0 && Math.Log10(display_mult).is_int()) {
tick_factors = tick_factors.with(
tick_base: tick_factors.tick_base * display_mult);
}
return tick_factors.tick_equality_comparer();
}
(data, is_up) => data is double d_data ?
tick_factors.tick(d_data, is_up ? tick_move : -tick_move) :
data;
public static VolSurfaceDisplayGridColumn get_double_output_col(
string group,
@@ -140,10 +113,7 @@
col_config,
format: get_double_tostring(col_config.tick_factors, col_config.tick_display),
parse: get_parse_double(col_config.tick_factors, col_config.tick_display),
tick_move: get_double_tickmove(col_config.tick_factors, col_config.tick_move),
comparer: get_double_comparer(
col_config.tick_factors, col_config.tick_display.display_multiplier)
.cast<double, object>());
tick_move: get_double_tickmove(col_config.tick_factors, col_config.tick_move));
}
}
}
@@ -63,27 +63,6 @@ namespace mbts.spark {
return rv;
}
public static string log_string(this VolSurfaceCalculationRequest vs_req) {
if (vs_req == null) {
return "Null";
}
string action_str = String.Empty;
foreach (var kv in vs_req.action_map) {
action_str += $"exp: {kv.Key.ToString()} action: {kv.Value.ToString()}, ";
}
action_str = action_str.TrimEnd(',', ' ');
return $"vs_inp: {vs_req.volsurface_input.log_string()}\nreq_id: {vs_req.request_id}\n" +
$"action_map: {action_str}\nup: {vs_req.cascade_up} down: {vs_req.cascade_down}";
}
public static string log_string(this VolSurfaceCalculationResponse resp) {
if (resp == null) {
return "Null";
}
return $"req_id: {resp.request_id} vs_output: " +
$"{resp.volsurface_calculation_output.volsurface_input.log_string()}";
}
private static string _trim_leading_char(string s, char c) {
if (!s.is_null_or_empty() && s.EndsWith(c)) {
return s.Remove(s.Length - 1, 1);
@@ -92,12 +71,11 @@ namespace mbts.spark {
}
internal static string log_string(this VolSurfaceDisplayModel.DisplayModelData dm_data) {
var vs_output = dm_data.vs_output;
var exp_grid = dm_data.exp_grid;
var vs_output_str = vs_output == null ? "NULL" : vs_output.volsurface_input.log_string();
var exp_grid_str = exp_grid == null ? "NULL" : exp_grid.log_string();
var rv = $"DisplayModelData\nvs_output:\n{vs_output_str}\n" +
$"exp_grid\n{exp_grid_str}\n";
string rv = String.Empty;
string global_grid_str = dm_data.global_grid == null ? "Null" : dm_data.global_grid.log_string();
rv += $"global_grid: {global_grid_str} \n";
string exp_grid_str = dm_data.exp_grid == null ? "Null" : dm_data.exp_grid.log_string();
rv += $"exp_grid: {exp_grid_str} \n";
return rv;
}
@@ -113,19 +91,19 @@ namespace mbts.spark {
}
internal static string log_string(this VolSurfaceDisplayGrid dgrid) {
Func<IDictionary<string, object>, string> log_exp = (col_val_map) => {
Func<IDictionary<string, object>, string> log_exp = (map) => {
string rv = String.Empty;
foreach (var kv in col_val_map) {
foreach (var kv in map) {
string val_string = kv.Value == null ? "Null" : kv.Value.ToString();
rv += $"{kv.Key}: {val_string}, ";
rv += $"{kv.Key}:{val_string},";
}
return _trim_leading_char(rv, ',');
};
string rv = String.Empty;
foreach (var kv in dgrid.data_map) {
rv += $"Exp: {kv.Key.expiration.ToShortDateString()} Data: {log_exp(kv.Value)}\n";
rv += $"Exp:{kv.Key.expiration.ToShortDateString()} Data:{log_exp(kv.Value)},";
}
return rv;
return _trim_leading_char(rv, ',');
}
internal static string log_string(this OptionDriverPriceMap map) {
@@ -260,15 +238,6 @@ namespace mbts.spark {
return rv;
}
internal static string log_string(this IPNLUnit p) {
string rv = "IPNLUnit:";
rv += $" account: {p.account} sec: {p.security.security_desc()} driver: {p.driver} theo: {p.theo} settle: {p.settle_price}" +
$" start_pos: {p.start_long_pos - p.start_short_pos} day_pos: {p.day_long_pos - p.day_short_pos}" +
$" start_pnl: {p.start_pnl} start_delta: {p.start_delta} start_vega: {p.start_vega}" +
$" day_pnl: {p.day_pnl} day_delta: {p.day_delta} day_vega: {p.day_vega}";
return rv;
}
internal static int tid() {
return System.Threading.Thread.CurrentThread.ManagedThreadId;
}
@@ -47,7 +47,6 @@ namespace mbts.spark {
var x_axis = BTSOxyGraphAxisDouble.Default;
x_axis.name = "Strike";
x_axis.major_grid_line_color = BTSColors.Graph.grid_line;
x_axis.tick_line_color = BTSColors.Graph.tick_line;
x_axis.position = AxisPosition.BottomLeftToRight;
x_axis.minimum = 0;
x_axis.maximum = 2000;
@@ -60,7 +59,6 @@ namespace mbts.spark {
var y_axis = BTSOxyGraphAxisDouble.Default;
y_axis.name = "Volatility";
y_axis.major_grid_line_color = BTSColors.Graph.grid_line;
y_axis.tick_line_color = BTSColors.Graph.tick_line;
y_axis.position = AxisPosition.LeftBottomToTop;
y_axis.minimum = 0;
y_axis.maximum = 1;
@@ -0,0 +1,84 @@
namespace mbts.spark {
using mbts.ui;
using mbts.ui.shell;
using System;
using System.Reactive.Linq;
using System.Windows.Input;
class VolGridCellVM : DisposableViewModelBase {
readonly Property<object> _candidate_value;
readonly Property<object> _committed_value;
readonly Property<bool> _is_dirty;
public VolGridCellVM(string column_id) {
this.column_id = column_id ?? throw new ArgumentNullException(nameof(column_id));
_committed_value = backing<object>(nameof(committed_value));
_candidate_value = backing<object>(nameof(candidate_value));
_is_dirty = backing(nameof(is_dirty),
_committed_value.observe_current(true)
.CombineLatest(_candidate_value.observe_current(true))
.Select(tup => !Equals(tup.First, tup.Second))
.OnDispatcher());
}
public string column_id { get; }
public object committed_value {
get => _committed_value.Value;
set => _committed_value.set(value);
}
public object candidate_value {
get => _candidate_value.Value;
set => _candidate_value.set(value);
}
public bool is_dirty => _is_dirty.Value;
public IObservable<object> observe_candidate(bool start_immediately = false) =>
_candidate_value.observe_current(start_immediately);
public void revert() =>
candidate_value = committed_value;
public override string ToString() =>
$"column_id: {column_id}, committed: {committed_value}, candidate: {candidate_value}";
}
class VolGridCellVM<T> : VolGridCellVM {
public VolGridCellVM(string column_id) : base(column_id) { }
public VolGridCellVM(string column_id, T committed_value, T candidate_value) : base(column_id) {
this.committed_value = committed_value;
this.candidate_value = candidate_value;
}
public new T committed_value {
get => base.committed_value is T v ? v : default;
set => base.committed_value = value;
}
public new T candidate_value {
get => base.candidate_value is T v ? v : default;
set => base.candidate_value = value;
}
}
class VolGridTickCellVM : VolGridCellVM {
ICommand _tick_up_cmd;
ICommand _tick_down_cmd;
public VolGridTickCellVM(string column_id) : base(column_id) { }
public event Action<bool> request_tick;
public ICommand tick_up_cmd =>
_tick_up_cmd ??= new DelegateCommand(() =>
request_tick?.Invoke(true));
public ICommand tick_down_cmd =>
_tick_down_cmd ??= new DelegateCommand(() =>
request_tick?.Invoke(false));
}
}
@@ -1,11 +0,0 @@
#nullable enable
namespace mbts.spark.VolSurface {
using System.Windows.Media;
readonly struct VolSurfaceCellState {
public bool is_dirty => committed_text is not null;
public FormattedText? text { get; init; }
public FormattedText? committed_text { get; init; }
}
}
@@ -1,79 +0,0 @@
#nullable enable
namespace mbts.spark {
using bts;
using mbts.ui.controls;
using mbts.ui.shell;
using Spark.Core;
using System;
class VolSurfaceCellVM : DisposableViewModelBase {
readonly Property<object?> _candidate_value;
readonly Property<object?> _committed_value;
readonly DelegateProperty<bool> _is_dirty;
readonly DeferrableAction _refresh;
public VolSurfaceCellVM(
VolSurfaceDisplayGridExpiration expiration, VolSurfaceDisplayGridColumn column) {
this.column = column ?? throw new ArgumentNullException(nameof(column));
this.expiration = expiration ?? throw new ArgumentNullException(nameof(expiration));
_committed_value = backing<object?>(nameof(committed_value), column.comparer);
_candidate_value = backing<object?>(nameof(candidate_value), column.comparer);
_is_dirty = backing(
nameof(is_dirty), () => !column.comparer.Equals(candidate_value, committed_value));
_refresh = new(_is_dirty.refresh);
_committed_value.Changed += on_committed_changed;
_candidate_value.Changed += on_candidate_changed;
_is_dirty.Changed += (o, n) => {
Log.assert(o != n);
Log.Ui.info(
$"VolSurface '{expiration}.{column}' is_dirty changed to {n}. " +
$"commited: {committed_value}; candidate: {candidate_value}");
};
void on_committed_changed(object? oldval, object? newval) =>
_is_dirty.refresh();
void on_candidate_changed(object? oldval, object? newval) =>
_is_dirty.refresh();
}
public event PropertyChange<object?>? candidate_value_changed {
add => _candidate_value.Changed += value;
remove => _candidate_value.Changed -= value;
}
public VolSurfaceDisplayGridColumn column { get; }
public string column_id => column.unique_col_name;
public VolSurfaceDisplayGridExpiration expiration { get; }
public object? committed_value {
get => _committed_value.Value;
set => _committed_value.set(value);
}
public object? candidate_value {
get => _candidate_value.Value;
set => _candidate_value.set(value);
}
public bool is_dirty => _is_dirty.Value;
public IObservable<object?> observe_candidate(bool start_immediately = false) =>
_candidate_value.observe_current(start_immediately);
public void reset(object? committed_value, object? candidate_value) {
using var _ = _refresh.defer();
this.committed_value = committed_value;
this.candidate_value = candidate_value;
}
public void revert() =>
candidate_value = committed_value;
public override string ToString() =>
$"column: {column}, committed: {committed_value}, candidate: {candidate_value}";
}
}
@@ -78,7 +78,7 @@ namespace mbts.spark.VolSurface {
view.SetBinding(FrameworkElement.DataContextProperty, new Binding() {
Converter = _data_context_converter
});
view.SetBinding(TextBlock.TextProperty, new Binding(nameof(VolSurfaceCellVM.candidate_value)) {
view.SetBinding(TextBlock.TextProperty, new Binding(nameof(VolGridCellVM.candidate_value)) {
Converter = ValueConverter.create(obj => model.format(obj))
});
return view;
@@ -101,16 +101,16 @@ namespace mbts.spark.VolSurface {
view.SetBinding(FrameworkElement.DataContextProperty, new Binding() {
Converter = _data_context_converter
});
view.SetBinding(VolSurfaceCellView.CommittedValueProperty, new Binding(nameof(VolSurfaceCellVM.committed_value)) {
view.SetBinding(VolSurfaceCellView.CommittedValueProperty, new Binding(nameof(VolGridCellVM.committed_value)) {
Mode = BindingMode.OneWay,
Converter = ValueConverter.create(obj => model.format(obj))
});
view.SetBinding(VolSurfaceCellView.CandidateValueProperty, new Binding(nameof(VolSurfaceCellVM.candidate_value)) {
view.SetBinding(VolSurfaceCellView.CandidateValueProperty, new Binding(nameof(VolGridCellVM.candidate_value)) {
Mode = BindingMode.TwoWay,
Converter = ValueConverter.create<object, string>(obj => model.format(obj), obj => model.parse(obj))
});
view.SetBinding(VolSurfaceCellView.TickDownCommandProperty, new Binding(nameof(VolSurfaceTickCellVM.tick_down_cmd)));
view.SetBinding(VolSurfaceCellView.TickUpCommandProperty, new Binding(nameof(VolSurfaceTickCellVM.tick_up_cmd)));
view.SetBinding(VolSurfaceCellView.TickDownCommandProperty, new Binding(nameof(VolGridTickCellVM.tick_down_cmd)));
view.SetBinding(VolSurfaceCellView.TickUpCommandProperty, new Binding(nameof(VolGridTickCellVM.tick_up_cmd)));
var bd = new Border {
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch,
@@ -1,4 +1,3 @@
#nullable enable
namespace mbts.spark.VolSurface {
using bts;
using bts.collections;
@@ -12,8 +11,6 @@ namespace mbts.spark.VolSurface {
using mbts.ui.shell;
using mbts.ui.utility;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -28,20 +25,17 @@ namespace mbts.spark.VolSurface {
class VolSurfaceGridVM : DisposableViewModelBase {
readonly VolSurfaceVM _parent;
readonly ObservableCollection<VolSurfaceDisplayGridExpiration> _expirations = new();
readonly DeferrableAction _invalidate_rows;
readonly DeferrableActionWrapper _invalidate_rows;
readonly ColumnsModel _columns_model;
ISet<string> _hidden_columns;
ISet<VolSurfaceExpiration>? _hidden_expirations;
IDisposable? _shift_editor;
ISet<VolSurfaceExpiration> _hidden_expirations;
IDisposable _shift_editor;
public VolSurfaceGridVM(
VolSurfaceVM vm,
VolSurfaceDisplayModel model,
ISet<string> hidden_columns,
ISet<VolSurfaceExpiration> hidden_expirations) {
Log.notnull(hidden_columns);
Log.notnull(hidden_expirations);
public VolSurfaceGridVM(VolSurfaceVM vm, VolSurfaceDisplayModel model,
ISet<string> hidden_columns, ISet<VolSurfaceExpiration> hidden_expirations) {
Log.assert(hidden_columns != null);
Log.assert(hidden_expirations != null);
_parent = vm;
this.model = model;
_columns_model = new(create_exp_column_view());
@@ -69,8 +63,7 @@ namespace mbts.spark.VolSurface {
};
_dispose = Disposable.Create(
ObservableAutoWrapper.connect(_expirations, rows, row_factory),
ObservableAutoWrapper.connect_item_hooks(rows, connect_row),
ObservableAutoWrapper.connect(_expirations, rows, exp => new VolSurfaceRowVM(this, exp), row => row.Dispose()),
sorted_visible_rows.bind(visible_rows),
Disposable.Create(() => {
this.model.on_candidate_grid_change -= _on_grid_updated;
@@ -80,20 +73,6 @@ namespace mbts.spark.VolSurface {
}),
_columns_model);
VolSurfaceRowVM row_factory(VolSurfaceDisplayGridExpiration exp) =>
new(this, exp);
IDisposable connect_row(VolSurfaceRowVM row) {
row.request_calculate += request_recalc;
return Disposable.Create(() => {
row.request_calculate -= request_recalc;
row.Dispose();
});
void request_recalc() =>
model.set_candidate_grid(current_grid);
}
VolSurfaceColumn create_exp_column_view() {
var filter = new ComboCheckBox();
filter.SetResourceReference(FrameworkElement.StyleProperty, "ExpirationFilterDropDown");
@@ -113,7 +92,7 @@ namespace mbts.spark.VolSurface {
}
}
public event Action<IEnumerable<VolSurfaceDisplayGridExpiration>>? on_selection_changed;
public event Action<IEnumerable<VolSurfaceDisplayGridExpiration>> on_selection_changed;
public VolSurfaceDisplayGrid current_grid { get; private set; }
public VolSurfaceDisplayGrid committed_grid { get; private set; }
@@ -139,7 +118,6 @@ namespace mbts.spark.VolSurface {
.Select(group => new DIYGridSuperHeaderVM(group.Key, group.Count(), collapsed_content: _short_header(group.Key)))
.ToList();
public ICommand populate_empty_exps_cmd => _parent.populate_empty_exps_cmd;
public ICommand main_settings_cmd => _parent.main_settings_cmd;
public ICommand advanced_settings_cmd => _parent.advanced_settings_cmd;
public ICommand graph_settings_cmd => _parent.vol_curve_vm.settings_command;
@@ -163,14 +141,13 @@ namespace mbts.spark.VolSurface {
rows.select_exp().Except(visible_rows.select_exp());
public void invalidate_rows() =>
_invalidate_rows.Invoke();
_invalidate_rows.execute();
public IDisposable defer_invalidate_rows() =>
_invalidate_rows.defer();
_invalidate_rows.defer_execution();
public VolSurfaceColumn get_column(string id) =>
columns.FirstOrDefault(c => c.id == id) as VolSurfaceColumn ??
throw new InvalidOperationException($"Failed to find column '{id}'");
columns.FirstOrDefault(c => c.id == id) as VolSurfaceColumn;
internal void signal_selection_changed() {
var e = on_selection_changed;
@@ -241,7 +218,7 @@ namespace mbts.spark.VolSurface {
!_hidden_columns.Contains(column.unique_col_name);
void _on_grid_updated() {
using var _ = _invalidate_rows.defer();
using var _ = _invalidate_rows.defer_execution();
var grid_new = model.get_active_grid();
// add/remove columns
var cols_new = grid_new.get_ordered_columns()
@@ -266,7 +243,7 @@ namespace mbts.spark.VolSurface {
}
current_grid = grid_new;
committed_grid = is_dirty ? model.get_committed_grid() : current_grid;
_invalidate_rows.Invoke();
_invalidate_rows.execute();
}
void _launch_shift_editor(VolSurfaceDisplayGridColumn column, Action<double> commit_shift) {
@@ -79,7 +79,6 @@ namespace mbts.spark {
public bool is_input_cell => column?.type == VolSurfaceColumnType.ReadWriteTick;
public ICommand populate_empty_exps_cmd => _parent.populate_empty_exps_cmd;
public ICommand main_settings_cmd => _parent.main_settings_cmd;
public ICommand advanced_settings_cmd => _parent.advanced_settings_cmd;
public ICommand grid_settings_cmd => _parent.grid_settings_cmd;
@@ -4,18 +4,22 @@ namespace mbts.spark.VolSurface {
using mbts.ui.controls;
using mbts.ui.shell;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Media;
public struct VolSurfaceCellState {
public bool is_dirty => committed_text is not null;
public FormattedText? text;
public FormattedText? committed_text;
}
class VolSurfaceRowVM : DisposableViewModelBase, ISelectable, IFormatCellsToClipboard, DIYGrid.IRowVM {
readonly VolSurfaceGridVM _parent;
readonly VolSurfaceDisplayGridExpiration _exp;
readonly Dictionary<string, CellData> _cells = new();
readonly DeferrableAction _request_calculate;
VolSurfaceRowContextMenuVM? _context_menu;
bool _is_selected;
@@ -23,7 +27,6 @@ namespace mbts.spark.VolSurface {
public VolSurfaceRowVM(VolSurfaceGridVM parent, VolSurfaceDisplayGridExpiration exp) {
_parent = parent;
_exp = exp;
_request_calculate = new(() => request_calculate?.Invoke());
_dispose = Disposable.Create(() => {
_cells.Values.DisposeAll();
_cells.Clear();
@@ -33,7 +36,6 @@ namespace mbts.spark.VolSurface {
public event Action<bool>? is_selected_changed;
public event Action? invalidated;
public event Action? request_calculate;
public VolSurfaceDisplayGridExpiration expiration => _exp;
@@ -50,14 +52,12 @@ namespace mbts.spark.VolSurface {
public VolSurfaceRowContextMenuVM context_menu =>
_context_menu ??= new(_parent, this);
public VolSurfaceCellVM get_cell(VolSurfaceDisplayGridColumn column) =>
public VolGridCellVM get_cell(VolSurfaceDisplayGridColumn column) =>
_cells.GetOrAdd(column.unique_col_name, _ => _create_cell(column)).vm;
public void invalidate() {
using (_request_calculate.supress()) {
foreach (var cell in _cells.Values) {
_sync_cell(cell.vm);
}
foreach (var cell in _cells.Values) {
_sync_cell(cell.vm);
}
invalidated?.Invoke();
}
@@ -79,15 +79,29 @@ namespace mbts.spark.VolSurface {
CellData _create_cell(VolSurfaceDisplayGridColumn column) {
var cell = column.type switch {
VolSurfaceColumnType.ReadWriteTick => create_tick_cell(),
_ => new VolSurfaceCellVM(_exp, column)
_ => new VolGridCellVM(column.unique_col_name),
};
_sync_cell(cell);
return new(cell, _connect_cell(cell));
var dispose = cell.observe_candidate().DistinctUntilChanged().OnDispatcher()
.Subscribe(value => {
var curr = _parent.current_grid.read(expiration, column);
if (Equals(value, curr)) {
return;
}
var grid = _parent.current_grid;
grid.write(expiration, column, value);
_parent.model.set_candidate_grid(grid);
});
return new(cell, dispose);
VolSurfaceCellVM create_tick_cell() {
var cell = new VolSurfaceTickCellVM(_exp, column);
VolGridTickCellVM create_tick_cell() {
var cell = new VolGridTickCellVM(column.unique_col_name);
cell.request_tick += is_up => {
var col = _parent.get_column(column.unique_col_name);
if (col is null) {
throw new InvalidOperationException(
$"Failed to find column with id {column.unique_col_name}");
}
if (col.model?.tick_move is var tm) {
cell.candidate_value = tm?.Invoke(cell.candidate_value, is_up);
return;
@@ -98,48 +112,23 @@ namespace mbts.spark.VolSurface {
}
}
void _sync_cell(VolSurfaceCellVM cell) {
void _sync_cell(VolGridCellVM cell) {
if (cell is null) {
return;
}
using var _ = _request_calculate.supress();
cell.reset(
committed_value: _parent.committed_grid.read(_exp, cell.column_id),
candidate_value: _parent.current_grid.read(_exp, cell.column_id));
}
IDisposable? _connect_cell(VolSurfaceCellVM cell) {
return cell.column.type switch {
VolSurfaceColumnType.ReadWriteTick => connect_input(),
_ => null
};
IDisposable connect_input() {
cell.candidate_value_changed += on_candidate_value_changed;
return Disposable.Create(() =>
cell.candidate_value_changed -= on_candidate_value_changed);
void on_candidate_value_changed(object? oldval, object? newval) {
var curr = _parent.current_grid.read(expiration, cell.column);
if (cell.column.comparer.Equals(newval, curr)) {
return;
}
var grid = _parent.current_grid;
grid.write(expiration, cell.column, newval);
_request_calculate.Invoke();
}
}
cell.committed_value = _parent.committed_grid.read(_exp, cell.column_id);
cell.candidate_value = _parent.current_grid.read(_exp, cell.column_id);
}
class CellData : IDisposable {
IDisposable? _dispose;
IDisposable _dispose;
public CellData(VolSurfaceCellVM vm, IDisposable? dispose) {
public CellData(VolGridCellVM vm, IDisposable dispose) {
this.vm = vm;
_dispose = Disposable.Create(vm, dispose);
}
public VolSurfaceCellVM vm { get; }
public VolGridCellVM vm { get; }
public void Dispose() =>
Disposable.dispose(ref _dispose);
@@ -1,27 +0,0 @@
#nullable enable
namespace mbts.spark {
using mbts.ui;
using mbts.ui.controls;
using System;
using System.Windows.Input;
class VolSurfaceTickCellVM : VolSurfaceCellVM {
ICommand? _tick_up_cmd;
ICommand? _tick_down_cmd;
public VolSurfaceTickCellVM(
VolSurfaceDisplayGridExpiration expiration, VolSurfaceDisplayGridColumn column)
: base(expiration, column) { }
public event Action<bool>? request_tick;
public ICommand tick_up_cmd =>
_tick_up_cmd ??= new DelegateCommand(() =>
request_tick?.Invoke(true));
public ICommand tick_down_cmd =>
_tick_down_cmd ??= new DelegateCommand(() =>
request_tick?.Invoke(false));
}
}
@@ -77,8 +77,8 @@
public IRaiseCanExecuteChangedCommand vol_shift { get; }
IEnumerable<IRaiseCanExecuteChangedCommand> _commands =>
ReflectionHelper.property_getters<VolSurfaceMacroActionsVM, IRaiseCanExecuteChangedCommand>()
.Select(pg => pg.get(this));
ReflectionHelper.property_delegates_of_type<VolSurfaceMacroActionsVM, IRaiseCanExecuteChangedCommand>()
.Select(g => g(this));
public void selection_changed(IEnumerable<VolSurfaceDisplayGridExpiration> selected) {
_selected_exps = selected.ToList();
@@ -60,7 +60,6 @@ namespace mbts.spark {
vol_terms_vm = new VolTermsGraphVM(_model, demux);
// command
populate_empty_exps_cmd = new Command(() => { _model.populate_empty_expirations(); });
_revert_cmd = new Command(o => _model.revert(), o => _model.is_dirty);
_commit_cmd = new Command(o => _model.commit(), o => _model.is_dirty);
load_previous_cmd = new Command(
@@ -186,7 +185,6 @@ namespace mbts.spark {
public ICommand revert_cmd => _revert_cmd;
public ICommand commit_cmd => _commit_cmd;
public ICommand populate_empty_exps_cmd { get; }
public ICommand main_settings_cmd => _main_settings_cmd;
public ICommand advanced_settings_cmd => _advanced_settings_cmd;
public ICommand grid_settings_cmd => _grid_settings_cmd;
+6 -18
View File
@@ -126,20 +126,6 @@
_log_bad_transition(_state, "set candidate grid");
}
public void populate_empty_expirations() {
bts.Log.Ui.info(String.Format("VolSurfaceDisplayModel.populate_expirations called with state: {0}",
_state.ToString()));
if (_state == DisplayModelState.Idle || _state == DisplayModelState.ResponseReady) {
DisplayModelData curr_data = _get_current_data();
VolSurfaceInput vs_inp =
VolSurfaceDataFunctions.populate_empty_expirations(curr_data.vs_output.volsurface_input);
_change_state(DisplayModelState.WaitingForCalcResponse);
_bus.post(SparkTags.VolSurfaceCalculationRequestTag(_vs_id),
new VolSurfaceCalculationRequest(vs_inp, _request_version_no++));
} else
_log_bad_transition(_state, "populate_expirations");
}
#endregion
#region Globals
@@ -159,7 +145,6 @@
return (_committed_data != null && _committed_data.vs_output != null) ? _committed_data.vs_output.volsurface_input.surface_parameters.vol_time : DateTime.MinValue;
}
public void set_candidate_vol_time(DateTime vol_time) {
bts.Log.Ui.info($"VolSurfaceDisplayModel.set_candidate_vol_time vs_id: {_vs_id} state: {_state.ToString()} vol_time: {vol_time}");
if (_state == DisplayModelState.Idle || _state == DisplayModelState.ResponseReady) {
DisplayModelData curr_data = _get_current_data();
if (curr_data != null) {
@@ -583,7 +568,9 @@
private void _change_state(DisplayModelState new_state) {
bool dirty_before = _translate_to_dirty(_state),
dirty_after = _translate_to_dirty(new_state);
bts.Log.Ui.info($"VolSurfaceDisplayModel._change_state vs_id: {_vs_id} {_state.ToString()}->{new_state.ToString()}");
// mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui,
// String.Format("State change {0}->{1}", _state.ToString(), new_state.ToString()));
bts.Log.Ui.info(String.Format("State change {0}->{1}", _state.ToString(), new_state.ToString()));
_state = new_state;
if (dirty_before != dirty_after && on_dirty_change != null) {
_bus.post(SparkTags.VolSurfaceDirtyStateTag(_vs_id), dirty_after);
@@ -626,8 +613,9 @@
}
}
private void _log_bad_transition(DisplayModelState state, string action) {
bts.Log.Ui.error($"VoLSurfaceDisplayModel bad_transaction vs_id: {_vs_id} {state}:{action}");
private static void _log_bad_transition(DisplayModelState state, string action) {
//mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, String.Format("{0}:{1}", state, action));
bts.Log.Ui.error(String.Format("{0}:{1}", state, action));
}
private static bool _translate_to_dirty(DisplayModelState state) {
+5 -7
View File
@@ -50,13 +50,11 @@ namespace mbts.spark {
.Table(UserTuple.key_fn)
.Cache() :
Observable.Return(TableUpdate<UserTuple, uint>.mk_empty(UserTuple.key_fn).with_added(new[] { user }));
_dispose = Disposable.Create(
all_user_tuples.Subscribe(t => bus.post(SparkTags.Users, t.state)),
on_accounts.Subscribe(map => {
_account_map = map;
var account_tuple_map = MappedDictionary.create(map, (id, name) => new AccountTuple(id, name));
bus.post(SparkTags.AccountsTag, account_tuple_map);
}));
_dispose = on_accounts.Subscribe(map => {
_account_map = map;
var account_tuple_map = MappedDictionary.create(map, (id, name) => new AccountTuple(id, name));
bus.post(SparkTags.AccountsTag, account_tuple_map);
});
}
public IObservable<IReadOnlyDictionary<uint, string>> on_users { get; }
@@ -189,6 +189,6 @@ namespace mbts {
exchange ?? sec_exp.exchange, security_type ?? sec_exp.security_type,
symbol ?? sec_exp.symbol,
expiration ?? sec_exp.expiration,
id.has_value ? id : sec_exp.id);
id.has_value ? id.value : sec_exp.id);
}
}
@@ -65,7 +65,7 @@ namespace mbts.analytics {
}
public override string ToString() {
return String.Format("{0} {1} {2}",
return String.Format("{0} {1} {2}",
security_type.ToString().ToUpper().First(), symbol, expiration.ToShortDateString());
}
@@ -74,11 +74,6 @@ namespace mbts.analytics {
int rv = expiration.CompareTo(other.expiration);
return rv != 0 ? rv : symbol.CompareTo(other.symbol);
}
public double diff_days(VolSurfaceExpiration exp_other) {
TimeSpan ts = expiration - exp_other.expiration;
return ts.TotalDays;
}
}
public static class VolSurfaceExpirationExtensions {
@@ -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,
@@ -680,60 +681,5 @@ namespace mbts.analytics
}
#endregion
#region Data copying
public static bool exp_has_input(VolSurfaceSettings vs_settings, VolCurveParameters exp_params) {
if (exp_params == null || vs_settings == null)
return false;
double atm_vol = get_atm_vol(vs_settings, exp_params);
double ref_fwd = exp_params.core_parameters.ref_forward;
return !Double.IsNaN(atm_vol) && !Double.IsNaN(ref_fwd);
}
public static VolSurfaceExpiration find_nearest_populated_exp(
VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp) {
VolCurveParameters exp_params = get_curve_parameters(vs_input, vs_exp);
if (exp_has_input(vs_input.surface_settings, exp_params))
return vs_exp;
VolSurfaceExpiration rv = null;
double rv_diff_days = Double.MaxValue;
foreach (var kv in vs_input.surface_parameters.curve_parameters_map) {
var this_exp = kv.Item1;
var this_exp_params = kv.Item2;
if (exp_has_input(vs_input.surface_settings, this_exp_params)) {
double this_exp_diff_days = Math.Abs(vs_exp.diff_days(this_exp));
if (this_exp_diff_days < rv_diff_days) {
rv = this_exp;
rv_diff_days = this_exp_diff_days;
}
}
}
return rv;
}
// Copies the empty exps from closest neighbor
public static VolSurfaceInput populate_empty_expirations(VolSurfaceInput vs_input) {
VolSurfaceInput rv = Spark.Core.Protobuf.ProtobufSerializationHelper.clone(vs_input);
rv.surface_parameters.curve_parameters_map.Clear();
foreach (var kv in vs_input.surface_parameters.curve_parameters_map) {
var vs_exp = kv.Item1;
var exp_params = kv.Item2;
if (!exp_has_input(vs_input.surface_settings, exp_params)) {
VolSurfaceExpiration np_exp = find_nearest_populated_exp(vs_input, vs_exp);
if (np_exp != null) {
var np_exp_params = get_curve_parameters(vs_input, np_exp);
if (np_exp_params != null) {
exp_params = Spark.Core.Protobuf.ProtobufSerializationHelper.clone(np_exp_params);
}
}
}
rv.surface_parameters.curve_parameters_map.Add(
new Tuple<VolSurfaceExpiration, VolCurveParameters>(vs_exp, exp_params));
}
return rv;
}
#endregion
}
}
@@ -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,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@@ -68,7 +68,6 @@ namespace bts.daemons {
double price,
int size = 1,
string account = "ACC A",
uint account_id = 1,
double? strike = null,
PutOrCall? cp = null,
double? theo = null
@@ -82,11 +81,9 @@ namespace bts.daemons {
price,
theo ?? price + 10 * new Random().NextDouble(),
account,
account_id,
true,
DateTime.Now,
"FakeTrader",
1);
"FakeTrader");
return t1;
}
}
+10 -13
View File
@@ -65,21 +65,18 @@ namespace bts {
_merge_and_post();
}
private static bool _is_active(SecurityMD sec_md) {
if (sec_md.security.Exchange == Venue.Sim)
return true;
if (sec_md.security.HasFuture || sec_md.security.HasOption) {
var exp = sec_md.security.security_expiration();
if (exp.HasValue) {
return exp.Value.Date >= DateTime.Now.Date.AddDays(-1);
private void _merge_and_post() {
Func<SecurityMD, bool> is_active = (sec_md) => {
if (sec_md.security.HasFuture || sec_md.security.HasOption) {
var exp = sec_md.security.security_expiration();
if (exp.HasValue) {
return exp.Value.Date >= DateTime.Now.Date.AddDays(-1);
}
return true;
}
return true;
}
return true;
}
private void _merge_and_post() {
var to_pub = _server_sec_map.Where(kv => _is_active(kv.Value)).ToDictionary(kv => kv.Key, kv => kv.Value);
};
var to_pub = _server_sec_map.Where(kv => is_active(kv.Value)).ToDictionary(kv => kv.Key, kv => kv.Value);
foreach (var kv in _fake_sec_map) {
to_pub[kv.Key] = kv.Value;
}
+3 -6
View File
@@ -29,7 +29,6 @@ namespace bts.daemons {
readonly OrderService _order_service;
readonly ErrorReporter _error_reporter;
readonly IBus _bus;
readonly mbts.analytics.PNLReportCalculator _pnl_calc;
IReadOnlyDictionary<int, ReportImmutable> _report_parameters_map =
new Dictionary<int, ReportImmutable>();
@@ -49,7 +48,6 @@ namespace bts.daemons {
_error_reporter = error_reporter;
_order_service = order_service;
_report_calculators = new(mk_report_calculator);
_pnl_calc = new PNLReportCalculator(bus);
_dispose = Disposable.Create(
bus.subscribe(SparkTags.ReportBlackboardTags.Create).Subscribe(rp => _create_report(rp).ignore()),
@@ -61,8 +59,7 @@ namespace bts.daemons {
_bus.subscribe(SparkTags.SystemContractsTag).CombineLatest(
_order_service.subscribe_fills(), _position_service.subscribe_manual_fills())
.Subscribe(tup => _on_all_trade_data(tup.First, tup.Second, tup.Third)),
_report_calculators,
_pnl_calc);
_report_calculators);
IDisposable mk_report_calculator(int id) {
if (!_report_parameters_map.TryGetValue(id, out var r)) {
@@ -159,8 +156,8 @@ namespace bts.daemons {
var fills_tl = fills_filtered.Select(
f => new TradeLogRow(f, sc_data.sec_md_map[f.SecurityKey].security));
var m_fills_tl = man_fills_filtered.Select(m => new TradeLogRow(
m, sc_data.sec_md_map[m.SecurityKey].security, Fill.Types.FillKind.Standard));
var m_fills_tl = man_fills_filtered.Select(
m => new TradeLogRow(m, sc_data.sec_md_map[m.SecurityKey].security));
var merged_fills = fills_tl.Concat(m_fills_tl).ToList();
Log.Ui.info($"ReportDaemon posting {merged_fills.Count} trades");
_bus.post(SparkTags.TradeLogTag, merged_fills);
-2
View File
@@ -203,7 +203,6 @@ namespace mbts.ui {
public static ImageSource CopyBoxes => create_icon(CopyBoxesGeometryKey, null, _copy_boxes_pen);
public static ImageSource CurrencyExchange => create_icon(CurrencyExchangeGeometryKey);
public static ImageSource DataEdit => create_icon(DataEditGeometryKey);
public static ImageSource DayFills => PNL;
public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } }
public static ImageSource DetachAlgos => create_icon_and_rotate(DetachAlgosKey, Brushes.Red);
public static ImageSource Disk => create_icon(DiskGeometryKey);
@@ -236,7 +235,6 @@ namespace mbts.ui {
public static ImageSource Payment => create_icon(PaymentGeometryKey);
public static ImageSource Pencil => create_icon(PencilGeometryKey);
public static ImageSource Play => create_icon(PlayGeometryKey);
public static ImageSource PNL => Accounting;
public static ImageSource Prohibited => create_icon(ProhibitedGeometryKey);
public static ImageSource RecurringSchedule => create_icon(RecurringScheduleGeometryKey);
public static ImageSource RecurringScheduleGray => create_icon(RecurringScheduleGeometryKey, Brushes.Gray);
@@ -13,7 +13,7 @@ using System.Threading.Tasks;
namespace mbts.ui.settings {
public interface ISavedWindowFactory {
Task<IShellWindow> restore(WindowSettings window);
Task<IShellWindow> restore(WindowState window);
}
[Export(typeof(ISavedWindowFactory))]
@@ -28,7 +28,7 @@ namespace mbts.ui.settings {
[Import]
public ObservableCollection<IShellModule> modules { get; set; }
public Task<IShellWindow> restore(WindowSettings window) {
public Task<IShellWindow> restore(WindowState window) {
Log.Ui.info("Loading window '{0}'".fmt(window.title));
bool changed;
int count = 0;
@@ -49,7 +49,7 @@ namespace mbts.ui.settings {
/// 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 WindowSettings window) {
private bool apply_compatability_migrations(ref WindowState window) {
foreach (var test in _compat) {
try {
if (test.apply(ref window)) {
@@ -14,9 +14,9 @@ using System.Windows.Threading;
namespace mbts.ui.settings {
public interface ISettingsCollector {
// Get the save state for every open window
Task<List<WindowSettings>> get_window_state();
Task<WindowSettings> get_window_state(IShellWindow window);
IEnumerable<ModuleSettings> get_module_state();
Task<List<WindowState>> get_window_state();
Task<WindowState> get_window_state(IShellWindow window);
IEnumerable<ModuleState> get_module_state();
WindowPosition get_launcher_state();
}
@@ -39,9 +39,9 @@ namespace mbts.ui.settings {
IWindowsInterop _interop => _wm;
public async Task<List<WindowSettings>> get_window_state() {
public async Task<List<WindowState>> get_window_state() {
var windows = _wm.list_windows();
var rv = new List<WindowSettings>(windows.Count);
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)) {
@@ -54,12 +54,12 @@ namespace mbts.ui.settings {
return rv;
}
public IEnumerable<ModuleSettings> get_module_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 ModuleSettings() {
yield return new ModuleState() {
name = module.key(),
app_data = out_stream.ToArray(),
};
@@ -70,7 +70,7 @@ namespace mbts.ui.settings {
return _launcher.get_position();
}
public async Task<WindowSettings> get_window_state(IShellWindow window) {
public async Task<WindowState> get_window_state(IShellWindow window) {
try {
if (window == null || window.Owner == null) return null;
Dispatcher dispatcher = null;
@@ -89,10 +89,10 @@ namespace mbts.ui.settings {
}
var pos = _interop.GetPosition(window);
var state = new WindowSettings() {
var state = new WindowState() {
owner = window.Owner.key(),
app_data = dispatcher is null ?
serialize() : (await dispatcher.InvokeAsync(serialize)),
(await dispatcher.InvokeAsync(serialize)) : serialize(),
position = pos,
title = string.IsNullOrEmpty(pos.custom_title) ? window.Title : pos.custom_title
};
@@ -1,4 +1,4 @@
using bts.shell.pnl;
using bts.shell.pnl;
using bts.utils;
using mbts.ui.settings;
@@ -21,7 +21,6 @@ namespace bts.settings {
interface IPNLSettingsMigrationRule : ISettingsMigrationRule<PNLSettings> { }
interface ISyntheticManagementMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IReconcileReportMigrationRule : ISettingsMigrationRule<GridSettings> { }
interface IDayFillsGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
static class SettingsMigrationHelper {
public static bool apply<T>(T settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules, out T new_settings) {
@@ -34,6 +34,7 @@ namespace mbts.persist {
_instance_settings = instance_settings;
_get = get;
_set = set;
hub.request_clear_instance_settings += () => instance_settings = null;
}
public T instance_settings {
@@ -1,31 +0,0 @@
#nullable enable
namespace mbts.ui.shell {
using ProtoBuf;
using Spark.Core.Protobuf;
using System.Collections.Generic;
[ProtoContract]
public class ModuleSettings : IProtobuf<ModuleSettings> {
[ProtoMember(1)]
public string? name { get; set; }
[ProtoMember(2)]
public byte[]? app_data { get; set; }
public bool Equals(ModuleSettings? other) =>
other is not null &&
name == other.name &&
app_data.safe_sequence_equals(other.app_data);
public override bool Equals(object? obj) =>
Equals(obj as ModuleSettings);
public override int GetHashCode() =>
GetType().GetHashCode();
public ModuleSettings Clone() =>
ProtobufSerializationHelper.clone(this);
}
}
+242 -239
View File
@@ -1,239 +1,242 @@
#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 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(15)]
GridSettings? _day_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;
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 day_fills_grid =>
_day_fills_grid ??= DayFillsSettings.default_grid();
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 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? day_fills = null,
GridSettings? synthetic_management = null,
GridSettings? reconcile_report = null,
PNLSettings? pnl = null,
OrderBookGridSettings? order_book_grid = null,
GlobalAlertSettings? alerts = null) {
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,
_day_fills_grid = day_fills ?? _day_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
};
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;
}
}
#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;
}
}
+226 -188
View File
@@ -1,188 +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(fills: gs)),
_day_fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.day_fills_grid, (us, gs) => us.with(day_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);
readonly IEnumerable<IFillsGridSettingsMigrationRule> _fills_migration_rules;
readonly IEnumerable<IDayFillsGridSettingsMigrationRule> _day_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<IDayFillsGridSettingsMigrationRule> day_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>();
_day_fills_migration_rules = day_fills_migration_rules ?? Enumerable.Empty<IDayFillsGridSettingsMigrationRule>();
_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 IWindowSettingsManager<GridSettings> create_day_fills_settings_manager(
GridSettings instance_settings) =>
_create_settings_manager(
instance_settings,
_day_fills_migration_rules,
_day_fills_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,71 +0,0 @@
#nullable enable
namespace mbts.ui.shell {
using ProtoBuf;
using Spark.Core.Protobuf;
using System;
using System.ComponentModel;
[ProtoContract]
public class WindowPosition : IProtobuf<WindowPosition> {
[ProtoMember(3)]
public int width { get; set; }
[ProtoMember(4)]
public int height { get; set; }
[ProtoMember(5)]
public int left { get; set; }
[ProtoMember(6)]
public int top { get; set; }
[ProtoMember(7)]
public bool is_maximized { get; set; }
[ProtoMember(8)]
public string? host_id { get; set; }
[ProtoMember(9)]
public int tab_index { get; set; }
[ProtoMember(100)]
public bool horizontal { get; set; }
[ProtoMember(101), DefaultValue(true)]
public bool show_text { get; set; } = true;
[ProtoMember(102), DefaultValue(true)]
public bool always_on_top { get; set; } = true;
[ProtoMember(104)]
public string? custom_title { get; set; }
public bool Equals(WindowPosition? other) =>
other is not null &&
width == other.width &&
height == other.height &&
left == other.left &&
top == other.top &&
is_maximized == other.is_maximized &&
host_id == other.host_id &&
tab_index == other.tab_index &&
horizontal == other.horizontal &&
show_text == other.show_text &&
always_on_top == other.always_on_top &&
custom_title == other.custom_title;
public override bool Equals(object? obj) =>
Equals(obj as WindowPosition);
public override int GetHashCode() =>
GetType().GetHashCode();
public WindowPosition Clone() =>
ProtobufSerializationHelper.clone(this);
object ICloneable.Clone() =>
Clone();
}
}
@@ -1,45 +0,0 @@
#nullable enable
namespace mbts.ui.shell {
using bts.utils;
using ProtoBuf;
using Spark.Core.Protobuf;
using System;
using System.Collections.Generic;
[ProtoContract]
public class WindowSettings : IProtobuf<WindowSettings> {
[ProtoMember(1)]
public string? owner { get; set; }
[ProtoMember(2)]
public byte[]? app_data { get; set; }
[ProtoMember(8)]
public WindowPosition? position { get; set; }
[ProtoMember(9)]
public string? title { get; set; }
public bool Equals(WindowSettings? other) =>
other is not null &&
owner == other.owner &&
app_data.safe_sequence_equals(other.app_data) &&
position.safe_equals(other.position) &&
title == other.title;
public override bool Equals(object? obj) =>
Equals(obj as WindowSettings);
public override int GetHashCode() =>
GetType().GetHashCode();
public WindowSettings Clone() =>
ProtobufSerializationHelper.clone(this);
object ICloneable.Clone() =>
Clone();
}
}
@@ -0,0 +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;
}
}
@@ -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,12 +1,13 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api;
namespace bts.api.position {
using bts.api.core;
using bts.api.orderman;
using bts.api.position;
using bts.shell.pnl;
using mbts.ui;
using Spark.Trading;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
@@ -16,10 +17,10 @@ namespace Spark.Trading {
IObservable<TableUpdate<(SecurityImmutable?, PositionUnitImmutable), int>> on_positions { get; }
IObservable<TableUpdate<(SecurityImmutable? sec, RetrievedExchangePositionImmutable exch_pos), AccountSecurityKey>> on_exchange_positions { get; }
IObservable<TableUpdate<ReconcileReportRowData, AccountSecurityKey>> merged_positions { get; }
IObservable<TableUpdate<DayFillsRowData, DayFillsRowKey>> day_fills { get; }
// pnl
IObservable<TableUpdate<PNLRowData, AccountSecurityKey>> pnl { get; }
IObservable<TableUpdate<(SecurityImmutable?, PNLUnitImmutable, QuantityConversionData<double>), int>> on_pnl { get; }
IObservable<TableUpdate<PNLRowData, AccountSecurityKey>> security_account_pnl { get; }
IObservable<TableUpdate<(SecurityImmutable?, PositionUnitImmutable), int>> on_security_positions(
uint security_key);
@@ -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,245 +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 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);
}
}
}
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,36 +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 readonly Pen _bid_pen = new(BTSColors.MarketData.bid.to_brush(true), 4);
static readonly Pen _ask_pen = new(BTSColors.MarketData.ask.to_brush(true), 4);
static readonly ConcurrentDictionary<uint, Brush> _algo_palette = new ConcurrentDictionary<uint, Brush>();
static OrderIconFactory() {
_bid_pen.Freeze();
_ask_pen.Freeze();
}
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,488 +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 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 ??= Security.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 ??= Security.Defaults.price_display_settingsi;
quantity_display ??= Security.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 ??= Security.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 ??= Security.Defaults.price_display_settingsi;
quantity_display ??= Security.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,
Func<double, string> fmt_qty = null) =>
order_collection_summary(
best_price,
best_price_volume,
total_volume,
Security.Defaults.ContractSpecificationImmutable,
fmt_qty);
public static string order_collection_summary(
double best_price,
double best_price_volume,
double total_volume,
ContractSpecificationImmutable spec,
Func<double, string> fmt_qty = null) {
if (total_volume == 0)
return string.Empty;
fmt_qty ??= v => v.ToString();
return total_volume == best_price_volume ?
$"{fmt_qty(best_price_volume)} @ {spec.format(best_price)}" :
$"{fmt_qty(best_price_volume)} ({fmt_qty(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
+24 -11
View File
@@ -1,22 +1,19 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api;
namespace bts.api.position {
using bts.api.core;
using bts.api.orderman;
using bts.api.position;
using bts.collections;
using bts.shell.pnl;
using bts.spark;
using mbts;
using mbts.analytics;
using mbts.spark;
using mbts.ui;
using Spark.Core;
using Spark.Core.Reactive;
using Spark.Model.Trading;
using Spark.Trading;
using System;
using System.Collections.Generic;
@@ -67,11 +64,27 @@ namespace Spark.Trading {
.Table()
.Cache();
day_fills = DayFillsDataSource.create(bus, security_store);
on_pnl = admin_model
.permission_filter(
_position_service.subscribei_pnl_data().Naggle(interval, scheduler),
p => p.Pos.AccountId)
.join(security_store, p => p.Pos.SecurityId)
.Select(
tup => (tup.sec, tup.val, new QuantityConversionData<double>(
security_auxiliary_model.get_display_quantity_divisor(tup.sec),
QuantityConversionOpType.DivideActual)),
tup => tup.val.RecordId)
.TableCheckedAutoCorrect(
EqualityComparer<(SecurityImmutable?, PNLUnitImmutable, QuantityConversionData<double>)>.Default)
.Where(t => t.has_changes())
.Cache();
pnl = bus.subscribe(SparkTags.ReportBlackboardTags.PNL.PNLData)
.Select(d => d.position_data.ToDictionary(u => u.id(), PNLRowData.from_pnl_unit))
.Table(PNLRowData.key_fn)
// security account pnl
security_account_pnl = on_pnl
#if DEBUG
.AssertIncremental(p => new AccountSecurityKey(p.Item2.Pos.AccountId, p.Item2.Pos.SecurityId))
#endif
.SelectKeyValue(PNLRowDataFactory.create, PNLRowData.key_fn)
.FullJoin(
order_data.working_account_security_orders,
PNLRowData.key_fn,
@@ -107,9 +120,9 @@ namespace Spark.Trading {
public IObservable<TableUpdate<(SecurityImmutable? sec, RetrievedExchangePositionImmutable exch_pos), AccountSecurityKey>> on_exchange_positions { get; }
public IObservable<TableUpdate<(SecurityImmutable?, PositionUnitImmutable), int>> on_positions { get; }
public IObservable<TableUpdate<PNLRowData, AccountSecurityKey>> pnl { get; }
public IObservable<TableUpdate<(SecurityImmutable?, PNLUnitImmutable, QuantityConversionData<double>), int>> on_pnl { get; }
public IObservable<TableUpdate<ReconcileReportRowData, AccountSecurityKey>> merged_positions { get; }
public IObservable<TableUpdate<DayFillsRowData, DayFillsRowKey>> day_fills { get; }
public IObservable<TableUpdate<PNLRowData, AccountSecurityKey>> security_account_pnl { get; }
public IObservable<TableUpdate<(SecurityImmutable?, PositionUnitImmutable), int>> on_security_positions(uint security) =>
_security_positions_demuxer.subscribe(security);
@@ -1,5 +1,5 @@
#nullable enable
namespace Spark.Trading {
namespace bts.api.position {
using bts.api.core;
using Spark.Api.Position;
@@ -1,11 +1,9 @@
namespace mbts.spark {
using bts;
using bts.api;
using bts.api.analytics;
using bts.api.core;
using bts.collections;
using bts.shell;
using bts.shell.pnl;
using bts.spark;
using mbts.analytics;
@@ -14,9 +12,7 @@ namespace mbts.spark {
using mbts.ui.shell;
using mbts.ui.utility;
using Spark.Core.Data;
using Spark.Core.Reactive;
using Spark.Trading;
using Spark.ViewModel;
using System;
@@ -39,13 +35,7 @@ namespace mbts.spark {
[ImportingConstructor]
public AnalyticsShellModule(
IBus bus,
WindowManager wm,
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
Lazy<UserTuple> user) {
IBus bus, WindowManager wm, UserSettingsHub settings_hub, OrdersModel orders_model) {
_wm = wm;
_bus = bus;
var reports_demuxer = new TableUpdateDemuxer<ReportImmutable?, int>(default, false);
@@ -59,10 +49,6 @@ namespace mbts.spark {
new AnalyticsExpirationParametersWindowFactory(this, bus),
new SlideReportWindowFactory(this, bus, reports_demuxer.subscribe),
new ComboReportWindowFactory(this, bus, reports_demuxer.subscribe),
new PNLWindowFactory(
this, bus, settings_hub, orders_model, position_model, sec_meta_store),
new DayFillsWindowFactory(
this, bus, settings_hub, position_model, sec_meta_store, user.Value)
};
var vol_surfaces_src = _bus.subscribe(SparkTags.VolSurfaceListTag).OnDispatcher();
var reports_src = _bus.subscribe(SparkTags.ReportBlackboardTags.ListTag).OnDispatcher();
@@ -72,8 +58,6 @@ namespace mbts.spark {
nullable_reports_src.Subscribe(reports_demuxer),
reports_demuxer,
vm.launch_exp_params_view_cmd.subscribe_executed(_launch_exp_params_view),
vm.launch_pnl_cmd.subscribe_executed(_launch_pnl),
vm.launch_day_fills_cmd.subscribe_executed(_launch_day_fills),
// vol surface
vm.vol_surface_launcher_vm.launch_cmd.subscribe_executed(_launch_vol_surface),
vm.vol_surface_launcher_vm.create_cmd.subscribe_executed(_create_vol_surface),
@@ -130,12 +114,6 @@ namespace mbts.spark {
_bus.post(SparkTags.show_analytics_exp_params, settings);
}
void _launch_pnl() =>
_bus.post(SparkTags.ShowPNLTag, null);
void _launch_day_fills() =>
_bus.post(SparkTags.show_day_fills, DayFillsSettings.Default());
void _launch_vol_surface(int id) {
var windows = _wm.list_windows();
if (windows.OfType<VolSurfaceWindow>().TryGetFirst(w => w.vs_id == id, out var win)) {
@@ -202,8 +180,7 @@ namespace mbts.spark {
_bus.post(SparkTags.ShowSlideReportTag, SlideReportSettings.Default(id));
void _create_combo_report(string _) {
var vm = new ComboReportSettingsVM(
_bus.subscribe(SparkTags.AccountsTag), _bus.subscribe(SparkTags.SecuritiesTag));
var vm = new ComboReportSettingsVM(_bus.subscribe(SparkTags.AccountsTag));
vm.load_from(new(new Report { ReportType = Report.Types.ReportType.Slide }));
var win = new ComboReportCreationDialog() {
DataContext = vm
@@ -13,10 +13,6 @@ namespace mbts.spark {
public KeyValueLauncherVM<int, string> slide_report_launcher_vm { get; } = new() { type_name = "Slide Report" };
public KeyValueLauncherVM<int, string> combo_report_launcher_vm { get; } = new() { type_name = "Combo Report" };
// pnl
public EventCommand launch_pnl_cmd { get; } = new();
public EventCommand launch_day_fills_cmd { get; } = new();
public string? selected_window_type {
get => _selected_window_type;
set => Set(ref _selected_window_type, value);
@@ -3,11 +3,9 @@
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:bshell="clr-namespace:bts.shell"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:shell="clr-namespace:mbts.ui.shell"
xmlns:trading="clr-namespace:Spark.Trading"
x:Name="me"
Background="Transparent"
MinWidth="250"
@@ -19,25 +17,23 @@
<Setter Property="BorderThickness" Value="0" />
</Style>
<Style x:Key="LaunchButton" TargetType="Button" BasedOn="{StaticResource LargeMenuButton}">
<Setter Property="Height" Value="32" />
<Setter Property="MinWidth" Value="190" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
<Setter Property="Padding" Value="16,6,6,6" />
</Style>
<DataTemplate x:Key="LaunchItemTemplate">
<Button
Height="32"
MinWidth="190"
HorizontalAlignment="Stretch"
HorizontalContentAlignment="Stretch"
Padding="12,6,6,6"
Command="{Binding DataContext.launch_cmd, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding key}"
Style="{StaticResource LaunchButton}">
Style="{StaticResource LargeMenuButton}"
>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding value}" VerticalAlignment="Center" Margin="0,0,7,0" />
<TextBlock Text="{Binding value}" VerticalAlignment="Center" Margin="4,0,7,0" />
<Button
Grid.Column="1"
HorizontalAlignment="Right"
@@ -97,8 +93,6 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button
@@ -180,32 +174,5 @@
/>
</ContentControl>
<ToggleButton
Grid.Row="8"
c:RadioButtonGroupManager.Value="pnl"
c:RadioButtonGroupManager.Manager="{StaticResource WindowTypeRadioButtonGroupManager}"
Margin="0,6,0,0"
Content="P&amp;L Reports"
IsChecked="{Binding Path='(u:ExpandCollapseAnimator.IsExpanded)', ElementName=PNLContent, Mode=TwoWay}"
Style="{StaticResource LargeMenuToggleButton}" />
<ContentControl Grid.Row="9" Height="0">
<Grid x:Name="PNLContent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button
Content="{x:Static bshell:PNLWindow.WINDOW_TITLE}"
Command="{Binding launch_pnl_cmd}"
Style="{StaticResource LaunchButton}" />
<Button
Grid.Row="1"
Content="{x:Static trading:DayFillsWindow.WINDOW_TITLE}"
Command="{Binding launch_day_fills_cmd}"
Style="{StaticResource LaunchButton}" />
</Grid>
</ContentControl>
</Grid>
</UserControl>
@@ -65,9 +65,12 @@
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Grid Grid.Row="2" Background="{u:BTSBrush dialog_skirt}">
<Grid
Grid.Row="2"
Background="{x:Static u:BTSColors.dialog_skirt_brush}">
<Grid.ColumnDefinitions>
<!--PAD LEFT-->
<ColumnDefinition Width="12" />
<!--ADD ITEM BUTTON-->
<ColumnDefinition Width="Auto" />
<!--SPACING-->
@@ -257,9 +257,6 @@
ContextMenuOpening="_on_context_menu_opening">
<c:DIYGrid.ContextMenu>
<ContextMenu>
<MenuItem
Header="Populate Empty Expirations"
Command="{Binding populate_empty_exps_cmd}" />
<MenuItem Header="Settings">
<MenuItem.Icon>
<Image
@@ -46,7 +46,7 @@
var dummy_view = new Border {
Background = BTSColors.UI.default_background.to_brush().frozen(),
Padding = new(8),
Child = new TextBlock { Text = "Loading ..." }
Child = new TextBlock { Text = "Dummy Window" }
};
_dummy_view = dummy_view;
@@ -8,16 +8,16 @@ namespace mbts.ui.shell {
public interface IBookmarks {
Task save_bookmark(IShellWindow window);
void save_bookmark(WindowSettings window);
void remove(WindowSettings window);
void save_bookmark(WindowState window);
void remove(WindowState window);
void clear();
IEnumerable<WindowSettings> bookmarks { get; }
IEnumerable<WindowState> bookmarks { get; }
}
[Export(typeof(IBookmarks))]
public class BookmarksModel : IBookmarks {
readonly ISettingsCollector _settings_collector;
readonly Dictionary<string, WindowSettings> _bookmarks = new();
readonly Dictionary<string, WindowState> _bookmarks = new Dictionary<string, WindowState>();
[ImportingConstructor]
public BookmarksModel(ISettingsCollector settings) {
@@ -31,17 +31,17 @@ namespace mbts.ui.shell {
}
}
public void save_bookmark(WindowSettings window) =>
public void save_bookmark(WindowState window) =>
_bookmarks[window.title] = window;
public void clear() {
_bookmarks.Clear();
}
public void remove(WindowSettings window) {
public void remove(WindowState window) {
_bookmarks.Remove(window.title);
}
public IEnumerable<WindowSettings> bookmarks => _bookmarks.Values;
public IEnumerable<WindowState> bookmarks => _bookmarks.Values;
}
}
@@ -1,5 +1,6 @@
namespace bts.shell {
using bts.api;
using bts.api.position;
using bts.spark;
using mbts.co2;
@@ -8,7 +9,6 @@
using mbts.ui;
using Spark.Core.Data;
using Spark.Trading;
using System.Collections.Generic;
using System.Composition;
@@ -111,10 +111,10 @@ namespace mbts.spark {
new CellAnimation(Columns.Position, CellAnimation.Type.DownArrow, Brushes.Red),
new CellAnimation(Columns.DayChange, CellAnimation.Type.UpArrow, Brushes.Green),
new CellAnimation(Columns.DayChange, CellAnimation.Type.DownArrow, Brushes.Red),
new CellAnimation(Columns.WorkingBids, CellAnimation.Type.Border, BTSColors.warning.to_brush()),
new CellAnimation(Columns.WorkingBids, CellAnimation.Type.Border, BTSColors.warning_brush),
new CellAnimation(Columns.WorkingBids, CellAnimation.Type.Border, new SolidColorBrush(BTSColors.MarketData.bid)),
new CellAnimation(Columns.WorkingBids, CellAnimation.Type.Border, Brushes.Green),
new CellAnimation(Columns.WorkingAsks, CellAnimation.Type.Border, BTSColors.warning.to_brush()),
new CellAnimation(Columns.WorkingAsks, CellAnimation.Type.Border, BTSColors.warning_brush),
new CellAnimation(Columns.WorkingAsks, CellAnimation.Type.Border, new SolidColorBrush(BTSColors.MarketData.ask)),
new CellAnimation(Columns.WorkingAsks, CellAnimation.Type.Border, Brushes.Red));
private static readonly TimeSpan flash_duration = TimeSpan.FromSeconds(2);
@@ -15,8 +15,6 @@
using mbts.utils;
using Spark.Api.Position;
using Spark.Core;
using Spark.Trading;
using System;
using System.Collections.Generic;
@@ -34,7 +32,7 @@
readonly OrdersModel _orders_model;
readonly AnimationManager _animation = new();
readonly MyOrderSummarizer _order_summarizer;
readonly DeferrableAction _raise_invalidated;
readonly DeferrableActionWrapper _raise_invalidated;
readonly Property<double> _bid_price;
readonly Property<double> _ask_price;
@@ -319,7 +317,7 @@
IMDConsumerHandle _md => security_md.md;
public void raise_invalidated() =>
_raise_invalidated.Invoke();
_raise_invalidated.execute();
public void refresh() {
bool dirty = false;
@@ -36,7 +36,27 @@ namespace bts.shell.market_view {
}
public static GridSettings DefaultGridSettings =>
GridSettings.Default.with(DefaultColumns.all, DefaultColumns.default_sorting_criteria);
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 {
@@ -86,7 +106,7 @@ namespace bts.shell.market_view {
}
}
// and enable background color upgrade
return s.with(columns);
return s.with(columns, enable_background_color: true);
}
static class DefaultColumns {
@@ -102,21 +122,8 @@ namespace bts.shell.market_view {
public static GridColumnSettings bid_implied_size => _mk(Columns.BidImpliedQty, ColHeader.ImpliedQty, ColWidth.MergedQty, fg: BTSColors.MarketData.bid);
public static GridColumnSettings bid_direct_size => _mk(Columns.BidDirectQty, ColHeader.DirectQty, ColWidth.MergedQty, fg: BTSColors.MarketData.bid);
public static GridColumnSettings bid_merged_size => _mk(Columns.BidMergedQty, ColHeader.MergedQty, ColWidth.MergedQty, fg: BTSColors.MarketData.bid);
public static GridColumnSettings bid => _mk(
Columns.Bid,
ColHeader.Bid,
ColWidth.MViewPrice,
fg: BTSColors.header_text,
bg: BTSColors.MarketData.bid);
public static GridColumnSettings ask => _mk(
Columns.Ask,
ColHeader.Ask,
ColWidth.MViewPrice,
fg: BTSColors.header_text,
bg: BTSColors.MarketData.ask);
public static GridColumnSettings bid => _mk(Columns.Bid, ColHeader.Bid, ColWidth.MViewPrice, fg: BTSColors.header_text, bg: BTSColors.MarketData.bid);
public static GridColumnSettings ask => _mk(Columns.Ask, ColHeader.Ask, ColWidth.MViewPrice, fg: BTSColors.header_text, bg: BTSColors.MarketData.ask);
public static GridColumnSettings ask_merged_size => _mk(Columns.AskMergedQty, ColHeader.MergedQty, ColWidth.MergedQty, fg: BTSColors.MarketData.ask);
public static GridColumnSettings ask_direct_size => _mk(Columns.AskDirectQty, ColHeader.DirectQty, ColWidth.MergedQty, fg: BTSColors.MarketData.ask);
public static GridColumnSettings ask_implied_size => _mk(Columns.AskImpliedQty, ColHeader.ImpliedQty, ColWidth.MergedQty, fg: BTSColors.MarketData.ask);
@@ -150,8 +157,8 @@ namespace bts.shell.market_view {
}
public static IEnumerable<GridColumnSettings> all =>
ReflectionHelper.static_property_getters<GridColumnSettings>(typeof(DefaultColumns))
.Select(pg => pg.get());
ReflectionHelper.static_property_delegates_of_type<GridColumnSettings>(typeof(DefaultColumns))
.Select(g => g());
static GridColumnSettings _mk(Columns key, string display_name = null, double width = 80, bool is_visible = true, Color? fg = null, Color? bg = null, HorizontalAlignment h_align = HorizontalAlignment.Right) =>
new(col_id(key), display_name, is_visible, font_color_override: fg, width: width, horizontal_alignment: h_align, background_color_override: bg);
@@ -3,6 +3,7 @@ namespace mbts.spark {
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.api.position;
using bts.collections;
using bts.shell.market_view;
using bts.utils;
@@ -17,10 +18,8 @@ namespace mbts.spark {
using mbts.ui.utility;
using mbts.utils;
using Spark.Core;
using Spark.Core.Data;
using Spark.Core.Reflection;
using Spark.Trading;
using System;
using System.Collections.Generic;
@@ -48,8 +47,8 @@ namespace mbts.spark {
/// Viewmodel class designed for <see cref="ui.spark.MarketViewView"/>
/// </summary>
partial class MarketViewVM : DisposableViewModelBase, IHandleRowSelection {
static readonly IEnumerable<Func<MarketViewVM, IDataGridColumnFilter<Row>>> _filter_getters =
ReflectionHelper.property_getters<MarketViewVM, IDataGridColumnFilter<Row>>().Cut2();
static readonly IReadOnlyList<Func<MarketViewVM, IDataGridColumnFilter<Row>>> _filter_getters =
ReflectionHelper.property_delegates_of_type<MarketViewVM, IDataGridColumnFilter<Row>>().ToReadOnlyList();
static readonly IComparer<SecurityMD> _sec_md_key_comparer = Comparer<uint>.Default.wrap(SecurityMD.key_fn);
static readonly IComparer<Row> _row_key_comparer = _sec_md_key_comparer.wrap<SecurityMD, Row>(r => r.security_md);
@@ -64,7 +63,7 @@ namespace mbts.spark {
readonly IList<SecurityMD> _wrapped_rows;
readonly ListCollectionView _rows_view;
readonly Property<Row> _current_row;
readonly DeferrableAction _refresh_filter;
readonly DeferrableActionWrapper _refresh_filter;
Func<Row, bool> _filter;
IComparer<Row> _comparer;
@@ -188,7 +187,7 @@ namespace mbts.spark {
// row vm filter
// Althoguh securities are filtered at the row 'model' level (SecurityMD), the column base filters have to be applied at the row vm level,
// because they access market data, which is polled periodically and cached in the row vm.
_refresh_filter = new DeferrableAction(() => _filter_changed?.Invoke());
_refresh_filter = new DeferrableActionWrapper(() => _filter_changed?.Invoke());
var row_filter_source = Observable.Create<Func<Row, bool>>(o => {
notify();
_filter_changed += notify;
@@ -197,7 +196,7 @@ namespace mbts.spark {
o.OnNext(get_filter_states().build_predicate());
});
foreach (var f in _all_filters) {
f.filter_changed += _refresh_filter.Invoke;
f.filter_changed += _refresh_filter.execute;
}
_dispose = Disposable.Create(
@@ -492,7 +491,7 @@ namespace mbts.spark {
_ => null
};
state.grid = GridSettingsHelper.hide_cols(state.grid, new[] { ui.spark.FillsView.Columns.Security });
var sec_keys = securities.Select(SecurityImmutable.key_fn);
var sec_keys = securities.Select(SecurityDataHelper.key_fn);
if (securities.All(s => s.ContractCase == Security.ContractOneofCase.Synthetic)) {
state.root_securities = sec_keys.ToArray();
} else {
@@ -507,8 +506,7 @@ namespace mbts.spark {
IEnumerable<SecurityImmutable> securities, ColKey column) {
var (title_desc, fg) = _orderbook_title(column);
var filters = new bts.shell.orderbook.FilterStates {
security_criteria = SecurityCriteria.from_keys(
securities.Select(SecurityImmutable.key_fn)),
security_criteria = SecurityCriteria.from_keys(securities.Select(SecurityDataHelper.key_fn)),
order_types = securities.All(s => s.ContractCase == Security.ContractOneofCase.Synthetic) ?
new[] { new AlgoID(CustomOrderDefinition.CustomOneofCase.Spreader) } :
AlgoID.exchange_algo_keys,
@@ -1,6 +1,7 @@
using bts;
using bts.api;
using bts.api.core;
using bts.api.position;
using bts.collections;
using bts.shell;
using bts.shell.fills;
@@ -16,7 +17,6 @@ using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using Spark.Trading;
using System;
using System.Collections.Generic;
@@ -1,4 +1,5 @@
using bts.api;
using bts.api.position;
using bts.proto;
using bts.settings;
using bts.shell.market_view;
@@ -9,7 +10,6 @@ using mbts.ui;
using mbts.ui.settings;
using Spark.Core.Data;
using Spark.Trading;
using System;
using System.Composition;
@@ -83,6 +83,18 @@ namespace bts.shell {
}
}
[Export(typeof(IMarketViewGridSettingsMigrationRule))]
class InitBackgroundOverrideMigrationRule : IMarketViewGridSettingsMigrationRule {
public bool apply(GridSettings settings, out GridSettings new_settings) {
if (!settings.enable_background_color) {
new_settings = settings.with(enable_background_color: true);
return true;
}
new_settings = default;
return false;
}
}
[Export(typeof(IMarketViewGridSettingsMigrationRule))]
class EnsureSelectionHighlightTranslucency : IMarketViewGridSettingsMigrationRule {
public bool apply(GridSettings settings, out GridSettings new_settings) =>
@@ -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; }
@@ -132,8 +138,8 @@ namespace bts.shell.time_and_sales {
}
public static IEnumerable<GridColumnSettings> all =>
ReflectionHelper.static_property_getters<GridColumnSettings>(typeof(DefaultColumns))
.Select(pg => pg.get());
ReflectionHelper.static_property_delegates_of_type<GridColumnSettings>(typeof(DefaultColumns))
.Select(g => g());
static GridColumnSettings _mk_col(
ColKey key,
@@ -17,7 +17,6 @@
using mbts.user.settings;
using mbts.utils;
using Spark.Core;
using Spark.Core.Reflection;
using System;
@@ -47,7 +46,7 @@
readonly RowFactory _row_factory = new();
readonly LoggerContext _log;
readonly IWindowSettingsManager<GridSettings> _settings_manager;
readonly DeferrableAction
readonly DeferrableActionWrapper
_refresh_filter,
_refresh_sort,
_refresh_selected_rows;
@@ -97,9 +96,9 @@
delta_filter = new DoubleMinMax<TimeAndSalesRowVM>(r => r.display_delta, nameof(TimeAndSalesRowVM.display_delta));
// deferrable filter/sort refresh
_refresh_filter = new DeferrableAction(_refresh_filter_impl);
_refresh_sort = new DeferrableAction(_refresh_sort_impl);
_refresh_selected_rows = new DeferrableAction(() => selected_rows_changed?.Invoke(_selected_rows));
_refresh_filter = new DeferrableActionWrapper(_refresh_filter_impl);
_refresh_sort = new DeferrableActionWrapper(_refresh_sort_impl);
_refresh_selected_rows = new DeferrableActionWrapper(() => selected_rows_changed?.Invoke(_selected_rows));
// grid settings
grid_settings_manager = new SimpleGridSettingsManager<TimeAndSalesRowVM>(
@@ -132,11 +131,11 @@
// resources
var resources = new List<IDisposable>();
resources.AddRange(_filters.Select(f => {
f.filter_changed += _refresh_filter.Invoke;
return Disposable.Create(() => f.filter_changed -= _refresh_filter.Invoke);
f.filter_changed += _refresh_filter.execute;
return Disposable.Create(() => f.filter_changed -= _refresh_filter.execute);
}));
_sort_manager.active_sorting_changed += _refresh_sort.Invoke;
resources.Add(Disposable.Create(() => _sort_manager.active_sorting_changed -= _refresh_sort.Invoke));
_sort_manager.active_sorting_changed += _refresh_sort.execute;
resources.Add(Disposable.Create(() => _sort_manager.active_sorting_changed -= _refresh_sort.execute));
_dispose = Disposable.Create(resources.ToArray());
static string fmt_sec(TimeAndSalesRowVM row) => row.security.ToString();
@@ -239,7 +238,7 @@
var sorted_rows = rows.ToArray();
var snapshot = _selected_rows;
Array.Sort(sorted_rows, _comparer_backing);
using (_refresh_selected_rows.defer()) {
using (_refresh_selected_rows.defer_execution()) {
for (int i = 0; i < sorted_rows.Length; i++) {
if (rows[i].row_key != sorted_rows[i].row_key)
rows[i] = sorted_rows[i];
@@ -282,15 +281,15 @@
}
IEnumerable<IDataGridColumnFilter<TimeAndSalesRowVM>> _filters =>
ReflectionHelper.property_getters<TimeAndSalesVM, IDataGridColumnFilter<TimeAndSalesRowVM>>()
.Select(pg => pg.get(this));
ReflectionHelper.property_delegates_of_type<TimeAndSalesVM, IDataGridColumnFilter<TimeAndSalesRowVM>>()
.Select(fn => fn(this));
public (TimeAndSalesFilterSettings filters, IReadOnlyList<SortingCriteria> sorting_criteria, GridSettings grid_settings) create() =>
(_get_filter_states(), _sorting_criteria, grid_settings_manager.create());
public void load(TimeAndSalesFilterSettings filters, IEnumerable<SortingCriteria> sorting_criteria, GridSettings grid_settings) {
using (_refresh_filter.defer())
using (_refresh_sort.defer()) {
using (_refresh_filter.defer_execution())
using (_refresh_sort.defer_execution()) {
_log.info($"begin load settings ({++_load_settings_count})...");
var timer = new Stopwatch();
timer.Start();
@@ -390,7 +389,7 @@
bd.removeRange(e.RemovedItems.OfType<TimeAndSalesRowVM>());
}
_selected_rows = bd.ToImmutable();
_refresh_selected_rows.Invoke();
_refresh_selected_rows.execute();
}
static IComparer<TimeAndSalesRowVM> _get_column_comparer(string column_name) =>
@@ -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();
}
}
@@ -426,7 +426,7 @@
</c:ContractPickerPopup.Background>
<c:ContractPickerPopup.HeaderTemplate>
<DataTemplate>
<TextBlock Foreground="{u:BTSColor header_text}" Text="{Binding}" />
<TextBlock Foreground="{x:Static u:BTSColors.header_text_brush}" Text="{Binding}"/>
</DataTemplate>
</c:ContractPickerPopup.HeaderTemplate>
</c:ContractPickerPopup>
@@ -320,14 +320,7 @@ namespace mbts.ui.spark {
if (_vm.GetErrors(nameof(SyntheticEditorVM.tick_factors)).Cast<string>().Any())
this.draw_border(drawing_context, _tick_factors_picker.value, null, new Pen(Brushes.Red, 1));
string error_text = string.Join(", ", _vm.AllErrors);
this.draw_relative_text(
RelativePosition.Below,
error_text,
drawing_context,
_name_text_box.value,
BTSColors.header_error_text.to_brush(),
0,
y_offset);
this.draw_relative_text(RelativePosition.Below, error_text, drawing_context, _name_text_box.value, BTSColors.header_error_text_brush, 0, y_offset);
}
}
}
@@ -69,9 +69,9 @@ namespace bts.shell {
if (securities.Count == 1) {
var sec = securities.First();
switch (sec.ContractCase) {
case api.Security.ContractOneofCase.Future: _show_synthetic_create(new ContractLeg[] { SyntheticDataHelper.Defaults.ContractLeg(sec) }); break;
case api.Security.ContractOneofCase.Spread: _show_synthetic_create(sec.Spread.Legs.Select(l => l.CloneToMutable())); break;
case api.Security.ContractOneofCase.Synthetic: _show_synthetic_create(sec.Synthetic.Legs.Select(l => l.CloneToMutable())); break;
case Security.ContractOneofCase.Future: _show_synthetic_create(new ContractLeg[] { SyntheticDataHelper.Defaults.ContractLeg(sec) }); break;
case Security.ContractOneofCase.Spread: _show_synthetic_create(sec.Spread.Legs.Select(l => l.CloneToMutable())); break;
case Security.ContractOneofCase.Synthetic: _show_synthetic_create(sec.Synthetic.Legs.Select(l => l.CloneToMutable())); break;
default: Log.Ui.warn($"{GetType()} unable to process security: {sec}"); break;
}
} else
@@ -79,7 +79,7 @@ namespace bts.shell {
}
void _show_synthetic_strategy(SecurityImmutable security) {
if (security.ContractCase != api.Security.ContractOneofCase.Synthetic)
if (security.ContractCase != Security.ContractOneofCase.Synthetic)
Log.Ui.warn($"{GetType()} observed a non-synthetic-security posted on {nameof(SparkTags.ShowSyntheticStrategyTag)}: {security}");
else
_show_synthetic_strategy_async(security).ignore();
@@ -92,7 +92,7 @@ namespace bts.shell {
}
void _show_synthetic_clone((SecurityImmutable security, ExecutionStrategyImmutable strategy) args) {
if (args.security.ContractCase == api.Security.ContractOneofCase.Synthetic) {
if (args.security.ContractCase == Security.ContractOneofCase.Synthetic) {
var mutable_sec = args.security.CloneToMutable();
mutable_sec.Id = 0;
mutable_sec.Synthetic.Name = _get_clone_name(mutable_sec.Synthetic.Name);
@@ -103,10 +103,10 @@ namespace bts.shell {
void _show_synthetic_create(IEnumerable<ContractLeg> legs) {
var syn = SyntheticDataHelper.Defaults.SyntheticContract("Synthetic", legs);
var sec = new SecurityImmutable(new api.Security {
var sec = new SecurityImmutable(new Security {
Synthetic = syn,
Symbol = legs.FirstOrDefault()?.Security.Symbol ?? string.Empty,
ContractSpec = Security.Defaults.ContractSpecification
ContractSpec = SecurityDataHelper.Defaults.ContractSpecification
});
_show_synthetic_editor(new SyntheticEditorVM(_bus, _model.spreader, sec, new ExecutionStrategyImmutable(SyntheticDataHelper.Defaults.ExecutionStrategy(sec))));
}
@@ -57,6 +57,12 @@ namespace bts.shell {
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();
@@ -82,7 +82,7 @@ namespace mbts.spark {
can_execute, select_security_id
), SparkCommand.create("Change", Icons.ModifySynthetic, SparkTags.ShowSyntheticStrategyTag).complete(
current_row_source,
r => r != null, r => r?.security ?? Security.Defaults.SecurityImmutable
r => r != null, r => r?.security ?? SecurityDataHelper.Defaults.SecurityImmutable
), SparkCommand.create("Clone", Icons.CloneSynthetic, SparkTags.ShowSyntheticCloneTag).complete(
current_row_connectable_builder.create(observe_row_strategy),
rs => rs.HasValue, select_row_strategy_tuple
@@ -1,28 +1,25 @@
using mbts.ui;
using mbts.ui.controls;
using System.Collections.Generic;
using System.Windows.Media;
namespace bts.shell {
public static class ActivityLogCategory {
public static ILogViewerCategory order { get; } = _mk("Order", BTSColors.Orders.sent);
public static ILogViewerCategory fill { get; } = _mk("Fill", BTSColors.Orders.filled_dark);
public static ILogViewerCategory cancel { get; } = _mk("Cancel", BTSColors.Orders.working_cancel);
public static ILogViewerCategory modify { get; } = _mk("Modify", BTSColors.Orders.modified);
public static ILogViewerCategory warn { get; } = _mk("Warn", Colors.Gold);
public static IEnumerable<ILogViewerCategory> all_categories {
get {
yield return order;
yield return fill;
yield return cancel;
yield return modify;
yield return warn;
}
}
static ILogViewerCategory _mk(string name, Color color) =>
new LogViewerCategory(name, color.to_brush().frozen());
}
}
using mbts.ui;
using mbts.ui.controls;
using System.Collections.Generic;
using System.Windows.Media;
namespace bts.shell {
public static class ActivityLogCategory {
public static ILogViewerCategory order = new LogViewerCategory("Order", BTSColors.Orders.sent_brush);
public static ILogViewerCategory fill = new LogViewerCategory("Fill", BTSColors.Orders.filled_dark_brush);
public static ILogViewerCategory cancel = new LogViewerCategory("Cancel", BTSColors.Orders.working_cancel_brush);
public static ILogViewerCategory modify = new LogViewerCategory("Modify", BTSColors.Orders.modified_brush);
public static ILogViewerCategory warn = new LogViewerCategory("Warn", Brushes.Gold);
public static IEnumerable<ILogViewerCategory> all_categories {
get {
yield return order;
yield return fill;
yield return cancel;
yield return modify;
yield return warn;
}
}
}
}
@@ -219,14 +219,7 @@
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Rectangle
Grid.ColumnSpan="3"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"
Fill="{u:BTSBrush dialog_skirt}"
UseLayoutRounding="True" />
<Rectangle Grid.ColumnSpan="3" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Fill="{x:Static u:BTSColors.dialog_skirt_brush}" UseLayoutRounding="True"/>
<Button
x:Name="custom_badge_color_picker_button"
Background="{Binding selected_definition.badge_fill}"
@@ -12,8 +12,6 @@ using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -46,7 +44,7 @@ namespace mbts.spark {
readonly DelegateProperty<bool> _is_favorite, _is_dirty, _can_undo, _can_redo;
readonly Property<string> _name, _abbreviation;
readonly ObservableKeyedCollection<IAlgoVM, AlgoKey> _algo_roots = new ObservableKeyedCollection<IAlgoVM, AlgoKey>(vm => vm.id);
readonly DeferrableAction _refresh_on_local_changes;
readonly DeferrableActionWrapper _refresh_on_local_changes;
readonly EnumMaskInt32<AlgoEditingPermissions> _permissions_mask = new EnumMaskInt32<AlgoEditingPermissions>();
int? _favorite_index;
@@ -102,22 +100,22 @@ namespace mbts.spark {
_can_redo.Changed += on_can_redo_changed;
_can_undo.Changed += on_can_undo_changed;
custom_badge_color.enabled_changed += on_use_custom_badge_color_changed;
_refresh_on_local_changes = new DeferrableAction(on_local_changed);
_refresh_on_local_changes = new DeferrableActionWrapper(on_local_changed);
// load initial state
// visible_algo_root is selected_template.algo_root if user can add templates, otherwise algo_root
// - this behavior is configurable in 'AlgoStudioOptions' in UI.proto (01/28/2018)
resources.Add(_algo_root.observe_current(true).Subscribe(_visible_algo_root.set));
// set hooks/subscriptions
using (_refresh_on_local_changes.supress()) {
using (_refresh_on_local_changes.supress_execution()) {
resources.AddRange(
custom_badge_color.observe_nullable(true).Subscribe(v => Set(ref _badge_fill, (v ?? algo_root.safe_get_badge_color()).to_brush(), nameof(badge_fill))),
as_demuxer().subscribe_many(_refresh_on_local_changes.Invoke, nameof(this.name), nameof(abbreviation), nameof(badge_fill)),
as_demuxer().subscribe_many(_refresh_on_local_changes.execute, nameof(this.name), nameof(abbreviation), nameof(badge_fill)),
_edit_pane_vs_model.add_source(VisualStateNames.BadgeSelector.GroupName, custom_badge_color.observe_nullable(true).Select(t => t.HasValue ? VisualStateNames.BadgeSelector.Active : VisualStateNames.BadgeSelector.Inactive)),
_edit_pane_vs_model.add_source(VisualStateNames.Abbreviation.GroupName, _abbreviation.observe_current(true).Select(a => string.IsNullOrEmpty(a) ? VisualStateNames.Abbreviation.Unpopulated : VisualStateNames.Abbreviation.Populated)),
_algo_root.observe_current(true).SubscribeEach(vm => {
if (vm != null) {
root_algo_color_item.assign_color(vm.meta.Color.argb_color());
return vm.subscribe_definition().Subscribe(_ => _refresh_on_local_changes.Invoke());
return vm.subscribe_definition().Subscribe(_ => _refresh_on_local_changes.execute());
}
return null;
}),
@@ -276,7 +274,7 @@ namespace mbts.spark {
public void undo() => _restore(_edit_stack.try_undo);
public void redo() => _restore(_edit_stack.try_redo);
public void load_committed() {
using (_refresh_on_local_changes.defer())
using (_refresh_on_local_changes.defer_execution())
_assign_from_data(_committed.Value);
_on_committed_changed();
}
@@ -326,7 +324,7 @@ namespace mbts.spark {
_assert_can_load(data.key);
if (algo_root != null)
_edit_stack.push_distinct(_version.value);
using (_refresh_on_local_changes.defer())
using (_refresh_on_local_changes.defer_execution())
_assign_from_data(data);
_on_committed_changed();
}
@@ -382,7 +380,7 @@ namespace mbts.spark {
OrderTypeVMFactory.create(AlgoData.from_custom_def(definition), is_expanded: true);
void _on_metadata(AlgoDefinitionMetadata metadata) {
using (_refresh_on_local_changes.supress()) {
using (_refresh_on_local_changes.supress_execution()) {
_abbreviation.set(metadata.abbreviation);
custom_badge_color.set_nullable(metadata.badge_color);
_version.increment_version();
@@ -405,7 +403,7 @@ namespace mbts.spark {
void _restore(TryGetValue<Snapshot> try_get_snapshot) {
while (try_get_snapshot(out Snapshot next_state)) {
if (!_version.value.Equals(next_state)) {
using (_refresh_on_local_changes.defer()) {
using (_refresh_on_local_changes.defer_execution()) {
_assign_from_data(next_state);
return;
}
@@ -63,7 +63,7 @@ namespace mbts.ui.spark {
if (pvm is IAlgoParamVM<QuantityMeasureImmutable?>) return QuantityMeasureTemplate;
if (pvm is IAlgoParamVM<ExecutionStrategy>) return ExecutionStrategyTemplate;
if (pvm is IAlgoParamVM<Google.Protobuf.WellKnownTypes.Timestamp>) return TimestampTemplate;
var targ = ReflectionHelper.get_generic_type_args(pvm.GetType(), generic_algo_param_itype).FirstOrDefault();
var targ = ReflectionHelper.GetGenericTypeArgs(pvm.GetType(), generic_algo_param_itype).FirstOrDefault();
if (targ != null) {
if (targ.IsEnum)
return EnumTemplate;
@@ -1,55 +0,0 @@
#nullable enable
namespace Spark.Trading {
using mbts.spark.filters;
using mbts.ui;
using mbts.ui.controls;
using System;
using System.Collections.Generic;
static class DayFillsColumn {
public static DayFillsColumn<TColFilter> create<TColFilter>(
DayFillsColumnType key,
IComparer<DayFillsRowData> comparer_model,
IDataGridColumnPersistentFilter<DayFillsRowData, TColFilter> filter_model,
string filter_template) {
var (get_filter, set_filter) =
DIYGridFilterModel.get_filter_prop_delegates<DayFillsFilterSettings, TColFilter>(key.ToString());
return create(key, comparer_model, filter_model, get_filter, set_filter, filter_template);
}
public static DayFillsColumn<TColFilter> create<TColFilter>(
DayFillsColumnType key,
IComparer<DayFillsRowData> comparer_model,
IDataGridColumnPersistentFilter<DayFillsRowData, TColFilter> filter_model,
Func<DayFillsFilterSettings, TColFilter> get_col_filter,
Action<DayFillsFilterSettings, TColFilter> set_col_filter,
string filter_template) =>
new(key, comparer_model, filter_model, get_col_filter, set_col_filter, filter_template);
}
class DayFillsColumn<TColFilter> : DIYGridColumnModel<DayFillsColumnType, DayFillsRowData, DayFillsFilterSettings>, IDayFillsColumn, DIYGrid.IFilterableColumn {
public DayFillsColumn(
DayFillsColumnType key,
IComparer<DayFillsRowData> comparer_model,
IDataGridColumnPersistentFilter<DayFillsRowData, TColFilter> filter_model,
Func<DayFillsFilterSettings, TColFilter> get_col_filter,
Action<DayFillsFilterSettings, TColFilter> set_col_filter,
string filter_template) : base(
key,
comparer_model,
filter_model,
filter_template,
f => get_col_filter(f),
(f, cf_obj) => {
if (cf_obj is TColFilter cf) {
set_col_filter(f, cf);
}
return f;
}) { }
IDataGridColumnFilter<DayFillsRowData> IFilterableDIYGridColumn<DayFillsRowData, DayFillsColumnType>.filter_model => filter_model;
IDataGridColumnFilter IFilterableDIYGridColumn.filter_model => filter_model;
IDataGridColumnFilter DIYGrid.IFilterableColumn.filter_model => filter_model;
}
}
@@ -1,33 +0,0 @@
namespace Spark.Trading {
enum DayFillsColumnType {
FillTime,
User,
Account,
Exchange,
Security,
Symbol,
Side,
Quantity,
Price,
Bid,
Ask,
Driver,
Theo,
PNL,
PositionDelta,
PositionGamma,
PositionVega,
PositionTheta,
PositionOptionEquivalent,
FillKind,
FillStatus,
SecurityKey,
OrderKey,
FillKey
}
static class DayFillsColumnTypeExtensions {
public static string col_id(this DayFillsColumnType col) =>
col.ToString();
}
}
@@ -1,48 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api;
using bts.api.core;
using mbts.analytics;
using mbts.spark;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
class DayFillsDataSource {
public static IObservable<TableUpdate<DayFillsRowData, DayFillsRowKey>> create(
IBus bus, SecurityStore sec_store) {
var users = bus.subscribe(SparkTags.Users);
var inverse_users = users
.Select(d => d.ToDictionary(kv => kv.Value.name, kv => kv.Value))
.Table(u => u.name);
var pnl_data_source = bus.subscribe(SparkTags.ReportBlackboardTags.PNL.PNLData);
return create(pnl_data_source, inverse_users, sec_store);
}
public static IObservable<TableUpdate<DayFillsRowData, DayFillsRowKey>> create(
IObservable<PNLData> pnl_data_source,
IObservable<TableUpdate<UserTuple, string>> inverse_users,
SecurityStore sec_store) =>
// join pnl data w/ security and user
pnl_data_source
.Select(d => d.day_trades
.Select(DayFillsRowData.from_trade)
.ToDictionary(DayFillsRowData.key_fn))
.Table(DayFillsRowData.key_fn)
.join_table(sec_store, rd => rd.security_key)
.Select(tup => new DayFillsRowData(tup.val.trade, tup.sec), DayFillsRowData.key_fn)
.LeftJoin(
inverse_users,
DayFillsRowData.key_fn,
user => user.name,
row_data => row_data.user_name,
(row_data, row_key, user, user_name) => new DayFillsRowData(
row_data.trade, row_data.security, user.id),
(row_data, row_key, user_name) => row_data,
DayFillsRowData.key_fn);
}
}
@@ -1,184 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts.api;
using bts.api.orderman;
using bts.utils;
using mbts.spark.filters;
using mbts.ui;
using mbts.ui.controls;
using ProtoBuf;
using Spark.Core.Protobuf;
using System;
using System.Collections.Generic;
[ProtoContract]
class DayFillsFilterSettings : IProtobuf<DayFillsFilterSettings>{
[ProtoMember(1)]
[DIYGridColumnID(nameof(DayFillsColumnType.FillTime))]
public TimeFilterTuple? fill_time { get; set; }
[ProtoMember(2)]
[DIYGridColumnID(nameof(DayFillsColumnType.User))]
public uint[]? user { get; set; }
[ProtoMember(3)]
[DIYGridColumnID(nameof(DayFillsColumnType.Account))]
public uint[]? account { get; set; }
[ProtoMember(4)]
[DIYGridColumnID(nameof(DayFillsColumnType.Exchange))]
public Venue[]? exchange { get; set; }
[ProtoMember(5)]
[DIYGridColumnID(nameof(DayFillsColumnType.Security))]
public string? security { get; set; }
[ProtoMember(6)]
[DIYGridColumnID(nameof(DayFillsColumnType.Symbol))]
public string[]? symbol { get; set; }
[ProtoMember(7)]
[DIYGridColumnID(nameof(DayFillsColumnType.Side))]
public Side[]? side { get; set; }
[ProtoMember(8)]
[DIYGridColumnID(nameof(DayFillsColumnType.Quantity))]
public DoubleMinMaxState? quantity { get; set; }
[ProtoMember(9)]
[DIYGridColumnID(nameof(DayFillsColumnType.Price))]
public DoubleMinMaxState? price { get; set; }
[ProtoMember(10)]
[DIYGridColumnID(nameof(DayFillsColumnType.Bid))]
public DoubleMinMaxState? bid { get; set; }
[ProtoMember(11)]
[DIYGridColumnID(nameof(DayFillsColumnType.Ask))]
public DoubleMinMaxState? ask { get; set; }
[ProtoMember(12)]
[DIYGridColumnID(nameof(DayFillsColumnType.Driver))]
public DoubleMinMaxState? driver { get; set; }
[ProtoMember(13)]
[DIYGridColumnID(nameof(DayFillsColumnType.Theo))]
public DoubleMinMaxState? theo { get; set; }
[ProtoMember(14)]
[DIYGridColumnID(nameof(DayFillsColumnType.PNL))]
public DoubleMinMaxState? pnl { get; set; }
[ProtoMember(15)]
[DIYGridColumnID(nameof(DayFillsColumnType.PositionDelta))]
public DoubleMinMaxState? pos_delta { get; set; }
[ProtoMember(16)]
[DIYGridColumnID(nameof(DayFillsColumnType.PositionGamma))]
public DoubleMinMaxState? pos_gamma { get; set; }
[ProtoMember(17)]
[DIYGridColumnID(nameof(DayFillsColumnType.PositionVega))]
public DoubleMinMaxState? pos_vega { get; set; }
[ProtoMember(18)]
[DIYGridColumnID(nameof(DayFillsColumnType.PositionTheta))]
public DoubleMinMaxState? pos_theta { get; set; }
[ProtoMember(19)]
[DIYGridColumnID(nameof(DayFillsColumnType.PositionOptionEquivalent))]
public DoubleMinMaxState? pos_oev { get; set; }
[ProtoMember(20)]
[DIYGridColumnID(nameof(DayFillsColumnType.FillKind))]
public Fill.Types.FillKind[]? fill_kind { get; set; }
[ProtoMember(21)]
[DIYGridColumnID(nameof(DayFillsColumnType.FillStatus))]
public Fill.Types.FillStatus[]? fill_status { get; set; }
[ProtoMember(22)]
[DIYGridColumnID(nameof(DayFillsColumnType.SecurityKey))]
public string? security_key { get; set; }
[ProtoMember(23)]
[DIYGridColumnID(nameof(DayFillsColumnType.OrderKey))]
public string? order_key { get; set; }
[ProtoMember(24)]
[DIYGridColumnID(nameof(DayFillsColumnType.FillKey))]
public string? fill_key { get; set; }
public Func<DayFillsRowData, bool> build_predicate() {
var pb = new ColumnPredicateBuilder<DayFillsRowData>();
pb.add_time_filter(fill_time ?? TimeFilterTuple.empty, r => r.fill_time);
pb.add_discrete_values(user.empty_if_null(), r => r.user_id);
pb.add_discrete_values(account.empty_if_null(), r => r.account_id);
pb.add_discrete_values(exchange.empty_if_null(), r => r.exchange);
pb.add_regex(security, r => r.security.ToString());
pb.add_discrete_values(symbol, r => r.symbol);
pb.add_discrete_values(side, r => r.side);
pb.add_numeric(quantity, r => r.quantity);
pb.add_numeric(price, r => r.price);
pb.add_numeric(bid, r => r.bid);
pb.add_numeric(ask, r => r.ask);
pb.add_numeric(driver, r => r.driver);
pb.add_numeric(theo, r => r.theo);
pb.add_numeric(pnl, r => r.pnl);
pb.add_numeric(pos_delta, r => r.pos_delta);
pb.add_numeric(pos_gamma, r => r.pos_gamma);
pb.add_numeric(pos_vega, r => r.pos_vega);
pb.add_numeric(pos_theta, r => r.pos_theta);
pb.add_numeric(pos_oev, r => r.pos_oev);
pb.add_discrete_values(fill_kind, r => r.fill_kind);
pb.add_discrete_values(fill_status, r => r.fill_status);
pb.add_regex(security_key, r => r.security_key);
pb.add_regex(order_key, r => r.order_key);
pb.add_regex(fill_key, r => r.fill_key);
return pb.to_predicate();
}
public DayFillsFilterSettings Clone() =>
ProtobufSerializationHelper.clone(this);
public bool Equals(DayFillsFilterSettings? other) =>
other is not null &&
EqualityComparer.nullable_equals(fill_time, other.fill_time) &&
user.safe_sequence_equals(other.user) &&
account.safe_sequence_equals(other.account) &&
exchange.safe_sequence_equals(other.exchange) &&
security == other.security &&
symbol.safe_sequence_equals(other.symbol) &&
side.safe_sequence_equals(other.side) &&
quantity.safe_equals(other.quantity) &&
price.safe_equals(other.price) &&
bid.safe_equals(other.bid) &&
ask.safe_equals(other.ask) &&
driver.safe_equals(other.driver) &&
theo.safe_equals(other.theo) &&
pnl.safe_equals(other.pnl) &&
pos_delta.safe_equals(other.pos_delta) &&
pos_gamma.safe_equals(other.pos_gamma) &&
pos_vega.safe_equals(other.pos_vega) &&
pos_theta.safe_equals(other.pos_theta) &&
pos_oev.safe_equals(other.pos_oev) &&
fill_kind.safe_sequence_equals(other.fill_kind) &&
fill_status.safe_sequence_equals(other.fill_status) &&
security_key == other.security_key &&
order_key == other.order_key &&
fill_key == other.fill_key;
public override bool Equals(object? obj) =>
Equals(obj as DayFillsFilterSettings);
public override int GetHashCode() =>
GetType().GetHashCode();
object ICloneable.Clone() =>
Clone();
}
}
@@ -1,12 +0,0 @@
#nullable enable
namespace Spark.Trading {
using System;
[Flags]
enum DayFillsMatchType {
None = 0,
Quantity = 1,
Price = 1 << 1
}
}
@@ -1,26 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api.core;
using System;
using System.Collections.Generic;
using RowData = DayFillsRowData;
using RowKey = DayFillsRowKey;
class DayFillsModel {
public DayFillsModel(
IObservable<TableUpdate<RowData, RowKey>> day_fills,
IObservable<IReadOnlyDictionary<uint, AccountTuple>> accounts,
IObservable<IReadOnlyDictionary<uint, UserTuple>> users) {
this.day_fills = day_fills;
this.accounts = accounts;
this.users = users;
}
public IObservable<TableUpdate<RowData, RowKey>> day_fills { get; }
public IObservable<IReadOnlyDictionary<uint, AccountTuple>> accounts { get; }
public IObservable<IReadOnlyDictionary<uint, UserTuple>> users { get; }
}
}
@@ -1,102 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api;
using bts.api.orderman;
using bts.utils;
using mbts;
using mbts.analytics;
using mbts.spark;
using System;
readonly struct DayFillsRowData : IEquatable<DayFillsRowData> {
public DayFillsRowData(
IPNLTradeRow trade, SecurityImmutable? security = null, uint user_id = 0) {
this.trade = trade;
this.security = security;
this.user_id = user_id;
}
public static Func<DayFillsRowData, DayFillsRowKey> key_fn => rd => rd.row_key;
public DayFillsRowKey row_key => new(fill_key);
public IPNLTradeRow trade { get; }
// user
public UserTuple user => new(user_id, user_name);
public uint user_id { get; }
public string user_name => trade.tl_row.user;
// account
public AccountTuple account => new(account_id, account_name);
public uint account_id => trade.tl_row.account_id;
public string account_name => trade.tl_row.account;
// security
public SecurityImmutable? security { get; }
public uint security_key => trade.tl_row.security_key;
public Venue exchange =>
trade.tl_row.security_expiration?.exchange ?? Venue.Unset;
public string? symbol => security?.Symbol;
// order
public int order_key => trade.tl_row.order_key;
public Side side => trade.tl_row.size switch {
> 0 => Side.Buy,
< 0 => Side.Sell,
_ => Side.Undefined
};
// fill
public string fill_key => trade.tl_row.key;
public DateTime fill_time => trade.tl_row.time_entered.ToLocalTime();
public Fill.Types.FillKind fill_kind => trade.tl_row.fill_kind;
public Fill.Types.FillStatus fill_status => trade.tl_row.fill_status;
public double quantity => trade.tl_row.size;
public double price => trade.tl_row.price;
// market
public double bid => trade.top_of_book.bid;
public double ask => trade.top_of_book.ask;
public double driver => trade.driver;
// theos/greeks
public double theo => trade.theo;
public double pnl => trade.pnl;
public double pos_delta => trade.pos_delta;
public double pos_gamma => trade.pos_gamma;
public double pos_vega => trade.pos_vega;
public double pos_theta => trade.pos_theta;
public double pos_oev => trade.pos_oev;
public bts.api.domain.TickDisplaySettingsImmutable price_display(
bts.api.domain.SecurityMetadataItemImmutable? meta = null) {
var rv = meta.HasValue && meta.Value.HasValue && meta.Value.Value.HasPriceDisplay ?
meta.Value.Value.PriceDisplay : Security.Defaults.price_display_settingsi;
if (security.HasValue) {
rv = rv.with(
tick_factors: security.spec_or_default().tick_factors().to_api_tick_factors());
}
return rv;
}
public static DayFillsRowData from_trade(IPNLTradeRow trade) =>
new(trade);
public DayFillsRowData with(Optional<SecurityImmutable?> security, uint? user_id = null) =>
new(trade, security.value_or(this.security), user_id ?? this.user_id);
public bool Equals(DayFillsRowData other) =>
Equals(trade, other.trade) &&
EqualityComparer.nullable_equals(security, other.security) &&
user == other.user;
public override bool Equals(object? obj) =>
obj is DayFillsRowData other && Equals(other);
public override int GetHashCode() =>
HashCode.Combine(trade);
}
}
@@ -1,34 +0,0 @@
#nullable enable
namespace Spark.Trading {
using System;
readonly struct DayFillsRowKey : IEquatable<DayFillsRowKey>, IComparable<DayFillsRowKey> {
readonly string _value;
public DayFillsRowKey(string value) =>
_value = value ?? throw new ArgumentNullException(nameof(value));
public string value => _value ?? string.Empty;
public int CompareTo(DayFillsRowKey other) =>
value.CompareTo(other.value);
public bool Equals(DayFillsRowKey other) =>
value == other.value;
public override bool Equals(object? obj) =>
obj is DayFillsRowKey other && Equals(other);
public override int GetHashCode() =>
value?.GetHashCode() ?? 0;
public override string ToString() =>
value.ToString();
public static bool operator ==(DayFillsRowKey l, DayFillsRowKey r) =>
l.Equals(r);
public static bool operator !=(DayFillsRowKey l, DayFillsRowKey r) =>
!(l == r);
}
}
@@ -1,114 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api;
using bts.utils;
using mbts;
using mbts.ui.controls;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable;
class DayFillsRowVM : DisposableViewModelBase, DIYGrid.IRowVM, IEquatable<DayFillsRowVM> {
// guarentees deterministic sorting if the rows in the collection have unique row_keys
public static readonly IComparer<DayFillsRowVM> key_comparer =
Comparer<DayFillsRowKey>.Default.wrap<DayFillsRowKey, DayFillsRowVM>(r => r.row_key)
.to_safe();
DayFillsRowData _data;
// display
TickDisplaySettingsImmutable _quantity_display = Security.Defaults.quantity_display_settingsi;
TickDisplaySettingsImmutable _theo_display = Security.Defaults.price_display_settingsi
.with(tick_factors: new() {
TickBase = 10000,
TickUnit = 1
});
public DayFillsRowVM(DayFillsRowData data) =>
_data = data;
public event Action? invalidated;
public DayFillsRowData data {
get => _data;
set {
using var _ = detect_property_changes();
_data = value;
}
}
public DayFillsRowKey row_key => _data.row_key;
public UserTuple user => _data.user;
public AccountTuple account => _data.account;
// security
public SecurityImmutable? security => _data.security;
public uint security_key => _data.security_key;
public Venue exchange => _data.exchange;
public string? symbol => _data.symbol;
// order
public int order_key => _data.order_key;
public Side side => _data.side;
public string fill_key => _data.fill_key;
public DateTime fill_time => _data.fill_time;
public bts.api.orderman.Fill.Types.FillKind fill_kind => _data.fill_kind;
public bts.api.orderman.Fill.Types.FillStatus fill_status => _data.fill_status;
public double quantity => _data.quantity;
public double price => _data.price;
// market
public double bid => _data.bid;
public double ask => _data.ask;
public double driver => _data.driver;
// theos/greeks
public double theo => _data.theo;
public double pnl => _data.pnl;
public double pos_delta => _data.pos_delta;
public double pos_gamma => _data.pos_gamma;
public double pos_vega => _data.pos_vega;
public double pos_theta => _data.pos_theta;
public double pos_oev => _data.pos_oev;
// display
public TickDisplaySettingsImmutable quantity_display {
get => _quantity_display;
set => Set(ref _quantity_display, value);
}
public TickDisplaySettingsImmutable price_display => _data.price_display();
public TickDisplaySettingsImmutable driver_display =>
(security?.ContractCase ?? Security.ContractOneofCase.None) switch {
Security.ContractOneofCase.Future => price_display,
_ => Security.Defaults.price_display_settingsi.with(tick_factors: new() {
TickBase = 10000,
TickUnit = 1
})
};
public TickDisplaySettingsImmutable theo_display {
get => _theo_display;
set => Set(ref _theo_display, value);
}
public void raise_invalidated() =>
invalidated?.Invoke();
public bool Equals(DayFillsRowVM? other) =>
order_key == other?.order_key;
public override bool Equals(object? obj) =>
Equals(obj as DayFillsRowVM);
public override int GetHashCode() =>
order_key.GetHashCode();
}
}
@@ -1,201 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts.shell;
using bts.utils;
using mbts.ui;
using mbts.ui.settings;
using ProtoBuf;
using Spark.Core.Protobuf;
using Spark.Core.Reflection;
using System;
using System.Collections.Generic;
using ColKey = DayFillsColumnType;
using ColHeader = mbts.ui.controls.DIYGrid.DefaultColumnHeaders;
using ColWidth = mbts.ui.controls.DIYGrid.DefaultColumnWidths;
using System.Windows;
using System.Linq;
using System.Windows.Media;
using bts.collections;
[ProtoContract]
class DayFillsSettings : IProtobuf<DayFillsSettings> {
public const int VERSION = 1;
[ProtoMember(1)]
List<SortingCriteria>? _sorting_criteria;
public IList<SortingCriteria> sorting_criteria =>
_sorting_criteria ??= new(1);
[ProtoMember(2)]
public GridSettings? grid { get; set; }
[ProtoMember(3)]
public DayFillsFilterSettings? filter { get; set; }
[ProtoMember(4)]
public SparkMenuDisplaySettings menu_display { get; set; } = SparkMenuDisplaySettings.Default;
public static DayFillsSettings Default() {
var rv = new DayFillsSettings() {
filter = new()
};
rv.sorting_criteria.AddRange(DefaultColumns.default_sorting_criteria);
rv.grid = default_grid();
return rv;
}
public static GridSettings default_grid() =>
GridSettings.Default.with(columns: DefaultColumns.all);
public bool Equals(DayFillsSettings? other) =>
other is not null &&
grid.safe_equals(other.grid) &&
sorting_criteria.safe_sequence_equals(other.sorting_criteria) &&
filter.safe_equals(other.filter) &&
menu_display.Equals(other.menu_display);
public override bool Equals(object? obj) =>
Equals(obj as DayFillsSettings);
public override int GetHashCode() =>
GetType().GetHashCode();
public DayFillsSettings Clone() =>
ProtobufSerializationHelper.clone(this);
object ICloneable.Clone() =>
Clone();
static class DefaultColumns {
public static GridColumnSettings fill_time => _mk(
ColKey.FillTime, ColHeader.FillTime, ColWidth.Time);
public static GridColumnSettings user => _mk(
ColKey.User, ColHeader.User, ColWidth.User, false);
public static GridColumnSettings account => _mk(
ColKey.Account, ColHeader.Account, ColWidth.Account);
public static GridColumnSettings exchange => _mk(
ColKey.Exchange, ColHeader.Exchange, ColWidth.Exchange);
public static GridColumnSettings security => _mk(
ColKey.Security, ColHeader.Security, ColWidth.Security);
public static GridColumnSettings symbol => _mk(
ColKey.Symbol, ColHeader.Symbol, ColWidth.Symbol);
public static GridColumnSettings side => _mk(
ColKey.Side, ColHeader.Side, ColWidth.Side, false, fw: FontWeights.Bold);
public static GridColumnSettings quantity => _mkn(
ColKey.Quantity, ColHeader.Qty, ColWidth.Qty);
public static GridColumnSettings price => _mkn(
ColKey.Price, ColHeader.Price, ColWidth.Price);
public static GridColumnSettings bid => _mkn(
ColKey.Bid, ColHeader.Bid, ColWidth.Price, false);
public static GridColumnSettings ask => _mkn(
ColKey.Ask, ColHeader.Ask, ColWidth.Price, false);
public static GridColumnSettings driver => _mkn(
ColKey.Driver, ColHeader.Driver, ColWidth.Price);
public static GridColumnSettings theo => _mkn(
ColKey.Theo, ColHeader.Theo, ColWidth.Price);
public static GridColumnSettings pnl => _mkn(
ColKey.PNL, ColHeader.PNLHeaders.PNL, ColWidth.Price);
public static GridColumnSettings pos_delta => _mkn(
ColKey.PositionDelta, "Delta", ColWidth.Price);
public static GridColumnSettings pos_gamma => _mkn(
ColKey.PositionGamma, "Gamma", ColWidth.Price);
public static GridColumnSettings pos_vega => _mkn(
ColKey.PositionVega, "Vega", ColWidth.Price);
public static GridColumnSettings pos_theta => _mkn(
ColKey.PositionTheta, "Theta", ColWidth.Price);
public static GridColumnSettings pos_oev => _mkn(
ColKey.PositionOptionEquivalent, "OEV", ColWidth.Price);
public static GridColumnSettings fill_kind => _mk(
ColKey.FillKind, ColHeader.FillKind, ColWidth.FillKind, false);
public static GridColumnSettings fill_status => _mk(
ColKey.FillStatus, ColHeader.FillStatus, ColWidth.FillStatus);
public static GridColumnSettings fill_key => _mk(
ColKey.FillKey, ColHeader.FillKey, ColWidth.FillKey, false);
public static GridColumnSettings order_key => _mk(
ColKey.OrderKey, ColHeader.OrderKey, ColWidth.OrderKey, false);
public static GridColumnSettings security_key => _mk(
ColKey.SecurityKey, ColHeader.SecurityKey, ColWidth.SecurityKey, false);
public static IEnumerable<SortingCriteria> default_sorting_criteria {
get {
yield return new(fill_time.id, false);
}
}
public static IEnumerable<GridColumnSettings> all =>
ReflectionHelper.static_property_getters<GridColumnSettings>(typeof(DefaultColumns))
.Select(pg => pg.get());
/// <summary>
/// Makes a [non-numeric] column
/// </summary>
static GridColumnSettings _mk(
ColKey key,
string? display_name = null,
double width = 80,
bool is_visible = true,
Color? fg = null,
Color? bg = null,
HorizontalAlignment h_align = HorizontalAlignment.Left,
FontWeight? fw = null) =>
new(
key.ToString(),
display_name,
is_visible,
font_color_override: fg,
width: width,
horizontal_alignment: h_align,
background_color_override: bg,
font_weight_override: fw);
/// <summary>
/// Makes a numeric column
/// </summary>
static GridColumnSettings _mkn(
ColKey key,
string? display_name = null,
double width = 80,
bool is_visible = true,
Color? fg = null,
Color? bg = null,
HorizontalAlignment h_align = HorizontalAlignment.Right) =>
new(
key.ToString(),
display_name,
is_visible,
font_color_override: fg,
width: width,
horizontal_alignment: h_align,
background_color_override: bg);
}
}
}
@@ -1,251 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts.api.core;
using bts.api.orderman;
using bts.collections;
using bts.utils;
using mbts;
using mbts.collections;
using mbts.persist;
using mbts.spark;
using mbts.spark.filters;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using static mbts.ui.controls.DIYGrid;
using ColKey = DayFillsColumnType;
using FilterType = mbts.spark.filters.DataGridFilterKnownTemplates;
using RowData = DayFillsRowData;
using RowKey = DayFillsRowKey;
using RowVM = DayFillsRowVM;
class DayFillsVM : DisposableViewModelBase, IHandleGridSorting {
readonly IWindowSettingsManager<GridSettings> _settings_manager;
readonly DIYGridRowsModel<RowData, ColKey, DayFillsFilterSettings> _rows_model;
readonly ObservableKeyedCollection<IDayFillsColumn, ColKey> _columns = new(c => c.id);
public DayFillsVM(
DayFillsModel model,
IWindowSettingsManager<GridSettings> settings_manager,
ISecurityMetadataStore security_metadata) {
_settings_manager = settings_manager;
columns = _columns.WrapSelector(c => c.column_view);
column_models = _columns.AsReadOnlyKeyedCollection().WrapSelector(
c => (IDIYGridColumnModel)c);
// filters
var fill_time_filter = new TimeFilterVM<RowData>(r => r.fill_time);
var user_filter = DiscreteValuesFilterVM.Common.user<RowData>(
model.users.Select(us => us.Values), r => r.user);
var account_filter = DiscreteValuesFilterVM.Common.account<RowData>(
model.accounts.Select(us => us.Values), r => r.account);
var exchange_filter = DiscreteValuesFilterVM.Common.exchange<RowData>(
r => r.exchange);
var security_filter = new RegexFilterVM<RowData>(r => r.security.ToString());
var symbol_filter = DiscreteValuesFilterVM.Common.symbol<RowData>(
r => r.symbol ?? string.Empty);
var side_filter = DiscreteValuesFilterVM.Common.side<RowData>(r => r.side);
var quantity_filter = new DoubleMinMax<RowData>(r => r.quantity);
var price_filter = new DoubleMinMax<RowData>(r => r.price);
var bid_filter = new DoubleMinMax<RowData>(r => r.bid);
var ask_filter = new DoubleMinMax<RowData>(r => r.ask);
var driver_filter = new DoubleMinMax<RowData>(r => r.driver);
var theo_filter = new DoubleMinMax<RowData>(r => r.theo);
var pnl_filter = new DoubleMinMax<RowData>(r => r.pnl);
var pos_delta_filter = new DoubleMinMax<RowData>(r => r.pos_delta);
var pos_gamma_filter = new DoubleMinMax<RowData>(r => r.pos_gamma);
var pos_vega_filter = new DoubleMinMax<RowData>(r => r.pos_vega);
var pos_theta_filter = new DoubleMinMax<RowData>(r => r.pos_theta);
var pos_oev_filter = new DoubleMinMax<RowData>(r => r.pos_oev);
var fill_status_filter = DiscreteValuesFilterVM.Create<RowData, Fill.Types.FillStatus>(
EnumHelper.get_values<Fill.Types.FillStatus>(), r => r.fill_status);
var fill_kind_filter = DiscreteValuesFilterVM.Create<RowData, Fill.Types.FillKind>(
EnumHelper.get_values<Fill.Types.FillKind>(), r => r.fill_kind);
var security_key_filter = new RegexFilterVM<RowData>(r => r.security_key.ToString());
var order_key_filter = new RegexFilterVM<RowData>(r => r.order_key.ToString());
var fill_key_filter = new RegexFilterVM<RowData>(r => r.fill_key.ToString());
// columns
add_col(ColKey.FillTime, fill_time_filter, FilterType.TimeFilter);
add_col(ColKey.User, user_filter, FilterType.DiscreteValues);
add_col(ColKey.Account, account_filter, FilterType.DiscreteValues);
add_col(ColKey.Exchange, exchange_filter, FilterType.DiscreteValues);
add_col(ColKey.Security, security_filter, FilterType.Regex);
add_col(ColKey.Symbol, symbol_filter, FilterType.DiscreteValues);
add_col(ColKey.Side, side_filter, FilterType.DiscreteValues);
add_col(ColKey.Quantity, quantity_filter, FilterType.DoubleMinMax);
add_col(ColKey.Price, price_filter, FilterType.DoubleMinMax);
add_col(ColKey.Bid, bid_filter, FilterType.DoubleMinMax);
add_col(ColKey.Ask, ask_filter, FilterType.DoubleMinMax);
add_col(ColKey.Driver, driver_filter, FilterType.DoubleMinMax);
add_col(ColKey.Theo, theo_filter, FilterType.DoubleMinMax);
add_col(ColKey.PNL, pnl_filter, FilterType.DoubleMinMax);
add_col(ColKey.PositionDelta, pos_delta_filter, FilterType.DoubleMinMax);
add_col(ColKey.PositionGamma, pos_gamma_filter, FilterType.DoubleMinMax);
add_col(ColKey.PositionVega, pos_vega_filter, FilterType.DoubleMinMax);
add_col(ColKey.PositionTheta, pos_theta_filter, FilterType.DoubleMinMax);
add_col(ColKey.PositionOptionEquivalent, pos_oev_filter, FilterType.DoubleMinMax);
add_col(ColKey.FillKind, fill_kind_filter, FilterType.DiscreteValues);
add_col(ColKey.FillStatus, fill_status_filter, FilterType.DiscreteValues);
add_col(ColKey.SecurityKey, security_key_filter, FilterType.Regex);
add_col(ColKey.OrderKey, order_key_filter, FilterType.Regex);
add_col(ColKey.FillKey, fill_key_filter, FilterType.Regex);
// rows
_rows_model = DIYGridRowsModel.create(
DayFillsWindow.WINDOW_TYPE_NAME,
ColKey.FillKey,
_columns.WrapSelector(c => c.as_filterable()),
_columns.WrapSelector(c => c.as_sortable()),
_get_column_comparer,
fs => fs.build_predicate());
// grid settings
grid_settings_manager = new SimpleGridSettingsManager<RowVM>(
columns, null, rows, _load_col_settings);
var row_observers = RXCollection.observers<RowVM, RowData, RowKey>(
rows, create_row_vm, r => r.data, update_row_vm, false);
_dispose = Disposable.Create(
_settings_manager.subscribe_current().OnDispatcher().Subscribe(
grid_settings_manager.load_from),
_rows_model.observe_comparer().OnDispatcher().Subscribe(row_observers.comp),
model.day_fills.Filter(_rows_model.observe_filter()).OnDispatcher().Subscribe(
row_observers.table));
void add_col<TFilter>(
ColKey col_key,
IDataGridColumnPersistentFilter<RowData, TFilter> filter,
string filter_template) {
var comp = _get_column_comparer(col_key);
var col = DayFillsColumn.create(col_key, comp, filter, filter_template);
var grid = _settings_manager.current_settings();
if (GridSettingsHelper.try_find_column(grid.columns, col_key, out var cs)) {
col.settings = cs;
}
_columns.Add(col);
}
RowVM create_row_vm(RowData rd) {
var rvm = new RowVM(rd);
if (!rd.security.HasValue) {
return rvm;
}
var meta = security_metadata.get(rd.security.Value);
if (!meta.HasValue) {
return rvm;
}
if (meta.Value.HasQuantityDisplay) {
rvm.quantity_display = meta.Value.QuantityDisplay;
}
return rvm;
}
RowVM update_row_vm(RowVM rvm, RowData rd) {
rvm.data = rd;
return rvm;
}
}
public IReadOnlyObservableCollection<IDIYGridColumnModel> column_models { get; }
public IReadOnlyObservableCollection<ColumnBase> columns { get; }
public ObservableCollection<RowVM> rows { get; } = new();
public SimpleGridSettingsManager<RowVM> grid_settings_manager { get; }
public DayFillsSettings get_settings() {
var rv = new DayFillsSettings {
grid = grid_settings_manager.create(),
filter = get_filter_settings()
};
rv.sorting_criteria.AddRange(_rows_model.get_sorting_criteria());
return rv;
}
public DayFillsFilterSettings get_filter_settings() {
var fs = new DayFillsFilterSettings();
_rows_model.assign_to_filter(fs);
return fs;
}
public void load_settings(DayFillsSettings settings) {
_rows_model.on_settings(settings.filter ?? new(), settings.sorting_criteria);
if (settings.grid is not null) {
load_grid_settings(settings.grid);
}
}
public void load_grid_settings(GridSettings grid_settings) =>
grid_settings_manager.load_from(grid_settings);
public void on_sorting(object sender, DIYGridSortingEventArgs e) =>
_rows_model.on_sorting(e);
static IComparer<RowData> _get_column_comparer(ColKey column) {
return column switch {
ColKey.FillTime => wrap(r => r.fill_time),
ColKey.User => wrap(r => r.user),
ColKey.Account => wrap(r => r.account),
ColKey.Exchange => wrap(r => r.exchange),
ColKey.Security => wrap(r => r.security),
ColKey.Symbol => wrap(r => r.symbol),
ColKey.Side => wrap(r => r.side),
ColKey.Quantity => wrap(r => r.quantity),
ColKey.Price => wrap(r => r.price),
ColKey.Bid => wrap(r => r.bid),
ColKey.Ask => wrap(r => r.ask),
ColKey.Driver => wrap(r => r.driver),
ColKey.Theo => wrap(r => r.theo),
ColKey.PNL => wrap(r => r.pnl),
ColKey.PositionDelta => wrap(r => r.pos_delta),
ColKey.PositionGamma => wrap(r => r.pos_gamma),
ColKey.PositionVega => wrap(r => r.pos_vega),
ColKey.PositionTheta => wrap(r => r.pos_theta),
ColKey.PositionOptionEquivalent => wrap(r => r.pos_oev),
ColKey.FillKind => wrap(r => r.fill_kind),
ColKey.FillStatus => wrap(r => r.fill_status),
ColKey.SecurityKey => wrap(r => r.security_key),
ColKey.OrderKey => wrap(r => r.order_key),
ColKey.FillKey => wrap(r => r.fill_key),
_ => throw ExceptionBuilder.Argument.unexpected_case(column, nameof(column)),
};
static IComparer<RowData> wrap<T>(Func<RowData, T> selector) =>
Comparer<T>.Default.wrap(selector);
}
void _load_col_settings(GridSettings grid_settings) {
var col_settings_id_map = grid_settings.columns.ToDictionary(
cs => EnumHelper.parse<ColKey>(cs.id));
if (col_settings_id_map.Count == _columns.Count) {
CollectionHelper.sync_with_never_duplicate(
_columns,
grid_settings.columns,
cs => throw new InvalidOperationException(),
c => c.id,
cs => EnumHelper.parse<ColKey>(cs.id));
}
// don't assume that columns:column_settings have a perfect 1:1 relationship (they
// should, but it is possible we accidentally break the settings as grids/uis change)
foreach (var col in _columns) {
if (col_settings_id_map.TryGetValue(col.id, out var cs)) {
col.column_view.load_from(cs);
}
}
}
}
}
@@ -1,340 +0,0 @@
<UserControl
x:Class="Spark.Trading.DayFillsView"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:api="clr-namespace:bts.api;assembly=spark_api"
xmlns:bv="clr-namespace:bts.view"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:trading="clr-namespace:Spark.Trading"
u:WindowStyle.UnsafeWindow="{Binding Path='(u:WindowStyle.UnsafeWindow)', RelativeSource={RelativeSource AncestorType=bv:SparkWindowView}}"
FocusManager.IsFocusScope="True"
Background="{StaticResource CommonBackground}">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/FilterTemplates.xaml"/>
</ResourceDictionary.MergedDictionaries>
<!--
For some reason, the default style for TextCell (i.e., without an x:Key), is completely
ignored. This is particularly annoying because it means the Style attribute must be
specified for every TextCell in the RowTemplate
-->
<Style x:Key="TextCell" TargetType="c:TextCell">
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="{Binding Path='(c:DIYGrid.Column).horizontal_alignment', RelativeSource={RelativeSource Self}}" />
<Setter Property="Padding" Value="{x:Static c:DIYGrid.DefaultCellPadding}" />
<Setter Property="Background" Value="{Binding Path='(c:DIYGrid.Column).background_brush', RelativeSource={RelativeSource Self}}" />
<Setter Property="FontFamily" Value="{Binding Path='(c:DIYGrid.Column).font_family', RelativeSource={RelativeSource Self}}" />
<Setter Property="FontSize" Value="{Binding Path='(c:DIYGrid.Column).font_size', RelativeSource={RelativeSource Self}}" />
<Setter Property="FontWeight" Value="{Binding Path='(c:DIYGrid.Column).font_weight', RelativeSource={RelativeSource Self}}" />
<Setter Property="Foreground" Value="{Binding Path='(c:DIYGrid.Column).font_brush', RelativeSource={RelativeSource Self}}" />
<Setter Property="SnapsToDevicePixels" Value="True" />
</Style>
</ResourceDictionary>
</UserControl.Resources>
<AdornerDecorator>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<c:DIYGrid
x:Name="_grid"
Grid.Row="0"
Columns="{Binding columns, Mode=OneWay}"
CurrentRow="{Binding current_row}"
Rows="{Binding rows}"
SelectionHighlight="{Binding grid_settings_manager.selection_highlight, Mode=OneWay}"
SyncColumnSortDirectionWithSortDescriptions="False">
<c:DIYGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/>
<KeyBinding Key="Return" Command="{x:Static c:DIYGrid.DefaultRowCommand}" />
</c:DIYGrid.InputBindings>
<c:DIYGrid.CommandBindings>
<CommandBinding
Command="{x:Static c:DIYGrid.DefaultRowCommand}"
Executed="{x:Static c:DIYGrid.DefaultRowActionExecuted}"
CanExecute="{x:Static c:DIYGrid.DefaultRowActionCanExecute}"
/>
</c:DIYGrid.CommandBindings>
<c:DIYGrid.RowTemplate>
<DataTemplate>
<Grid
x:Name="RowView"
c:DIYGrid.SyncWithColumnGeometry="True"
Height="{Binding RowHeight, RelativeSource={RelativeSource AncestorType=c:DIYGrid}}">
<u:StateManager.Groups>
<u:StateGroupsManager AttachToMembers="True">
<u:StateDefinitionCollection>
<u:ModalStateDefinition Mode="Quantity">
<u:StateDefinition State="{Binding
Path='(u:StateDefinition.Group).(u:StateGroupsManager.Target).(Grid.DataContext).(trading:DayFillsRowVM.quantity)',
RelativeSource={RelativeSource Self},
Converter={x:Static trading:DayFillsView.numeric_sign_state_converter}}" />
</u:ModalStateDefinition>
<u:ModalStateDefinition Mode="PNL">
<u:StateDefinition State="{Binding
Path='(u:StateDefinition.Group).(u:StateGroupsManager.Target).(Grid.DataContext).(trading:DayFillsRowVM.pnl)',
RelativeSource={RelativeSource Self},
Converter={x:Static trading:DayFillsView.numeric_sign_state_converter}}" />
</u:ModalStateDefinition>
<u:ModalStateDefinition Mode="PositionDelta">
<u:StateDefinition State="{Binding
Path='(u:StateDefinition.Group).(u:StateGroupsManager.Target).(Grid.DataContext).(trading:DayFillsRowVM.pos_delta)',
RelativeSource={RelativeSource Self},
Converter={x:Static trading:DayFillsView.numeric_sign_state_converter}}" />
</u:ModalStateDefinition>
</u:StateDefinitionCollection>
</u:StateGroupsManager>
</u:StateManager.Groups>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="QuantityStates">
<VisualState Name="QuantityZero" />
<VisualState Name="QuantityInvalid" />
<VisualState Name="QuantityPositive">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="quantity" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush MarketData.bid}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="side" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush MarketData.bid}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="QuantityNegative">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="quantity" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush MarketData.ask}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="side" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush MarketData.ask}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup Name="PNLStates">
<VisualState Name="PNLZero" />
<VisualState Name="PNLInvalid" />
<VisualState Name="PNLPositive">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pnl" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush PNL.profit}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pnl" Storyboard.TargetProperty="FontWeight">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static FontWeights.Bold}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="PNLNegative">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pnl" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush PNL.loss}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pnl" Storyboard.TargetProperty="FontWeight">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static FontWeights.Bold}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup Name="PositionDeltaStates">
<VisualState Name="PositionDeltaZero" />
<VisualState Name="PositionDeltaInvalid" />
<VisualState Name="PositionDeltaPositive">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pos_delta" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush PNL.profit}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pos_delta" Storyboard.TargetProperty="FontWeight">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static FontWeights.Bold}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="PositionDeltaNegative">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pos_delta" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush PNL.loss}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pos_delta" Storyboard.TargetProperty="FontWeight">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static FontWeights.Bold}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.FillTime}"
Text="{Binding fill_time}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.User}"
Text="{Binding user}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Account}"
Text="{Binding account}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Exchange}"
Text="{Binding exchange}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Security}"
Text="{Binding security}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Symbol}"
Text="{Binding symbol}"
Style="{StaticResource TextCell}" />
<c:TextCell
x:Name="side"
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Side}"
Text="{Binding side}"
Style="{StaticResource TextCell}" />
<c:TextCell
x:Name="quantity"
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Quantity}"
Style="{StaticResource TextCell}">
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="quantity" />
<Binding Path="quantity_display" />
</MultiBinding>
</c:TextCell>
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Price}"
Style="{StaticResource TextCell}">
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="price" />
<Binding Path="price_display" />
</MultiBinding>
</c:TextCell>
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Bid}"
Style="{StaticResource TextCell}">
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="bid" />
<Binding Path="price_display" />
</MultiBinding>
</c:TextCell>
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Ask}"
Style="{StaticResource TextCell}">
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="ask" />
<Binding Path="price_display" />
</MultiBinding>
</c:TextCell>
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Driver}"
Style="{StaticResource TextCell}">
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="driver" />
<Binding Path="driver_display" />
</MultiBinding>
</c:TextCell>
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.Theo}"
Style="{StaticResource TextCell}">
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="theo" />
<Binding Path="theo_display" />
</MultiBinding>
</c:TextCell>
<c:TextCell
x:Name="pnl"
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.PNL}"
Text="{Binding pnl, StringFormat='#,0.000'}"
Style="{StaticResource TextCell}" />
<c:TextCell
x:Name="pos_delta"
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.PositionDelta}"
Text="{Binding pos_delta, StringFormat='#,0.000'}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.PositionGamma}"
Text="{Binding pos_gamma, StringFormat='#,0.000'}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.PositionVega}"
Text="{Binding pos_vega, StringFormat='#,0.000'}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.PositionTheta}"
Text="{Binding pos_theta, StringFormat='#,0.000'}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.PositionOptionEquivalent}"
Text="{Binding pos_oev, StringFormat='#,0.000'}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.FillKind}"
Text="{Binding fill_kind}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.FillStatus}"
Text="{Binding fill_status}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.SecurityKey}"
Text="{Binding security_key}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.OrderKey}"
Text="{Binding order_key}"
Style="{StaticResource TextCell}" />
<c:TextCell
c:DIYGrid.ColumnKey="{x:Static trading:DayFillsColumnType.FillKey}"
Text="{Binding fill_key}"
Style="{StaticResource TextCell}" />
</Grid>
</DataTemplate>
</c:DIYGrid.RowTemplate>
</c:DIYGrid>
</Grid>
</AdornerDecorator>
</UserControl>
@@ -1,24 +0,0 @@
#nullable enable
namespace Spark.Trading {
using mbts.ui.converters;
using System.Windows.Controls;
using System.Windows.Data;
/// <summary>
/// Interaction logic for DayFillsView.xaml
/// </summary>
partial class DayFillsView : UserControl {
public DayFillsView() =>
InitializeComponent();
public static IValueConverter numeric_sign_state_converter =>
ValueConverter.create<double, string>(v =>
v switch {
> 0.0 => "Positive",
< 0.0 => "Negative",
0.0 => "Zero",
_ => "Invalid"
});
}
}
@@ -1,139 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api;
using bts.api.core;
using bts.collections;
using bts.shell;
using bts.spark;
using bts.view;
using mbts;
using mbts.config;
using mbts.persist;
using mbts.spark;
using mbts.ui;
using mbts.ui.settings;
using mbts.ui.spark;
using mbts.ui.utility;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reactive.Linq;
using System.Windows;
class DayFillsWindow : SparkWindow<DayFillsSettings>, ISharedWindow {
public const string WINDOW_TYPE_NAME = "DayFills";
public const string WINDOW_TITLE = "Day P&L";
readonly List<SparkCommand> _commands = new();
readonly IWindowSettingsManager<GridSettings> _settings_manager;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _security_metadata;
readonly UserTuple _user;
DayFillsModel? _model;
DayFillsView? _view;
DayFillsVM? _vm;
SparkMenuDisplayVM? _menu_display_vm;
DayFillsSettings _settings;
public DayFillsWindow(
IBus bus,
ISaveWindow<DayFillsSettings> save,
IPositionModel position_model,
ISecurityMetadataStore security_metadata,
DayFillsSettings settings,
IWindowSettingsManager<GridSettings> settings_manager,
UserTuple user)
: base(WINDOW_TITLE, bus, save, Icons.DayFills) {
thread_id = Configuration.get<bts.config.MultiThreadedWindows>().day_fills ?
WINDOW_TYPE_NAME : null;
_position_model = position_model;
_security_metadata = security_metadata;
_settings = settings;
_settings_manager = settings_manager;
_user = user;
_dispose = Disposable.Create(() => {
Disposable.dispose(ref _menu_display_vm);
Disposable.dispose(ref _vm);
});
}
public string? thread_id { get; }
public override string window_type => WINDOW_TYPE_NAME;
public override IEnumerable<SparkCommand> Commands => _commands;
public override DayFillsSettings SaveState {
get {
if (_vm is not null) {
_settings = _vm.get_settings();
_settings.menu_display = _menu_display_vm?.create() ??
SparkMenuDisplaySettings.Default;
}
return _settings;
}
}
public override UIElement Content =>
_view ?? throw new InvalidOperationException("Internal view is null");
public override double MinWidth {
get {
if (_settings.grid is null) {
return base.MinWidth;
}
var grid_width = _settings.grid.columns.Where(c => c.is_visible).Sum(gcs => gcs.width);
return grid_width
+ SPARK_MENU_COLLAPSED_WIDTH
+ LAUNCHER_BUTTON_BORDER_WIDTH
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
}
}
[MemberNotNull(nameof(_model), nameof(_view), nameof(_vm), nameof(_menu_display_vm))]
public void thread_init() {
Contract.Requires(_model is null);
Contract.Requires(_view is null);
Contract.Requires(_vm is null);
Contract.Requires(_menu_display_vm is null);
Contract.Requires(!_commands.Any());
var accounts_src = _bus.subscribe(SparkTags.AccountsTag);
var users_src = _bus.subscribe(SparkTags.Users);
_model = new(_position_model.day_fills, accounts_src, users_src);
_vm = new(_model, _settings_manager, _security_metadata);
_vm.load_settings(_settings);
_view = new DayFillsView {
DataContext = _vm
};
_menu_display_vm = new();
_menu_display_vm.load_from(_settings.menu_display);
var settings_cmd = SparkCommands.window_settings_command(new DialogCommand(() => {
var vm = new ShellSettingsDialogVM<GridSettings, SimpleGridSettingsVM>(
_settings_manager,
us => us.fills_grid,
UserSettings.FileExtensions.GRID,
s => _vm.grid_settings_manager.create_vm(
// we need to get the most up to date GridSettings when launching b/c users may
// have changed some settings on the grid directly, like column widths.
s.with(_vm.columns.Select(c => c.create())))
);
vm.SubscribeDisposed(literal_title_source.OnDispatcher().Subscribe(t => vm.title = t));
var dialog = new ShellSettingsDialog { DataContext = vm };
vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog);
return dialog;
}));
_commands.AddRange(settings_cmd, _menu_display_vm.spark_cmd);
}
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
_menu_display_vm.safe_bind_to_view(parent_view);
}
}
@@ -1,54 +0,0 @@
#nullable enable
namespace Spark.Trading {
using bts;
using bts.api;
using bts.api.core;
using bts.api.position;
using bts.shell;
using mbts.persist;
using mbts.spark;
using mbts.ui;
using Spark.Core.Data;
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
class DayFillsWindowFactory : ShellWindowFactory<DayFillsSettings> {
readonly IBus _bus;
readonly UserSettingsHub _settings_hub;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _security_metadata;
readonly UserTuple _user;
public DayFillsWindowFactory(
IShellModule module,
IBus bus,
UserSettingsHub settings_hub,
IPositionModel position_model,
ISecurityMetadataStore security_metadata,
UserTuple user)
: base(module, DayFillsWindow.WINDOW_TYPE_NAME) {
_bus = bus;
_settings_hub = settings_hub;
_position_model = position_model;
_security_metadata = security_metadata;
_user = user;
_dispose = bus.subscribe(SparkTags.show_day_fills).OnDispatcher().Subscribe(_show);
}
public override Task<IShellWindow> load(DayFillsSettings state) =>
Task.FromResult(_create(state));
void _show(DayFillsSettings settings) =>
_bus.post(SparkTags.ShowWindow, _create(settings));
IShellWindow _create(DayFillsSettings state) {
var settings_man = _settings_hub.create_day_fills_settings_manager(state.grid);
return new DayFillsWindow(
_bus, this, _position_model, _security_metadata, state, settings_man, _user);
}
}
}
@@ -1,17 +0,0 @@
namespace Spark.Trading {
using mbts.ui;
using mbts.ui.controls;
interface IDayFillsColumn : IFilterableDIYGridColumn<DayFillsRowData, DayFillsColumnType, DayFillsFilterSettings>, ISortableDIYGridColumn<DayFillsColumnType> {
DIYGrid.ColumnBase column_view { get; }
}
static class DayFillsColumnExtensions {
public static IFilterableDIYGridColumn<DayFillsRowData, DayFillsColumnType, DayFillsFilterSettings> as_filterable(
this IDayFillsColumn rr_column) =>
rr_column;
public static ISortableDIYGridColumn<DayFillsColumnType> as_sortable(this IDayFillsColumn rr_column) =>
rr_column;
}
}
Loaded 100 of 376 files, more files were not shown because too many files have changed in this diff. Show more