refactor\cleanup OrderTypeVMBase and impls
This commit is contained in:
1 parent
109fee099f
commit
16d30e450f
15 files changed
+488
-360
No files matched your search
@@ -10,7 +10,7 @@ namespace mbts.spark {
|
||||
public readonly AlgoKey key;
|
||||
|
||||
public AlgoData(CustomOrderDefinitionImmutable value)
|
||||
: this(value, value.CustomCase.display_name(), new AlgoKey(value.CustomCase)) { }
|
||||
: this(value, value.display_name(), OrderDataHelper.get_shallow_factory_key(value)) { }
|
||||
|
||||
public AlgoData(CustomOrderDefinitionImmutable value, string name, AlgoKey key) {
|
||||
this.value = value;
|
||||
|
||||
@@ -72,7 +72,7 @@ namespace mbts.spark {
|
||||
_build_structure(definition.CloneToMutable(), ref structure, pos);
|
||||
|
||||
static void _build_structure(CustomOrderDefinition algo, ref int[] structure, int pos) {
|
||||
var cad = OrderDataHelper.get_child_algo_data(algo.CustomCase);
|
||||
var cad = OrderDataHelper.get_child_algo_data(algo);
|
||||
for (int di = 0; di < cad.Count; di++) {
|
||||
if (cad[di].get_child(algo) is CustomOrderDefinition child_algo) {
|
||||
ArrayHelper.ensure_capacity(ref structure, pos + 1);
|
||||
@@ -87,7 +87,7 @@ namespace mbts.spark {
|
||||
|
||||
static void _build_def(int[] structure, ref int pos, ref CustomOrderDefinition algo) {
|
||||
for (int i = pos; i < structure.Length; i++) {
|
||||
var cad = OrderDataHelper.get_child_algo_data(algo.CustomCase);
|
||||
var cad = OrderDataHelper.get_child_algo_data(algo);
|
||||
for (int di = 0; di < cad.Count; di++) {
|
||||
int mask = 1 << (31 - di);
|
||||
if ((structure[i] & mask) == mask) {
|
||||
@@ -95,10 +95,10 @@ namespace mbts.spark {
|
||||
var child_algo = OrderDataHelper.Defaults.CustomOrderDefinition(type);
|
||||
pos++;
|
||||
_build_def(structure, ref pos, ref child_algo);
|
||||
cad[di].set_child(algo, child_algo);
|
||||
cad[di].assign_child(algo, child_algo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
using bts.api;
|
||||
using bts.api.orderman;
|
||||
using bts.utils;
|
||||
using Google.Protobuf.Reflection;
|
||||
using mbts.utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.Composition;
|
||||
@@ -10,6 +13,9 @@ namespace mbts.spark {
|
||||
[Export]
|
||||
public class DynamicOrderHelper
|
||||
{
|
||||
static readonly IReadOnlyDictionary<DynamicOrderParam.ValueOneofCase, (FieldDescriptor field_descriptor, Type field_type)> _descriptor_case_index =
|
||||
ProtoHelper.get_oneof_descriptor_index<DynamicOrderParam, DynamicOrderParam.ValueOneofCase>(nameof(DynamicOrderParam.ValueCase));
|
||||
|
||||
readonly RegisteredDynamicOrderTypes _dynamic_types;
|
||||
[ImportingConstructor]
|
||||
private DynamicOrderHelper(OrderService order_service)
|
||||
@@ -28,11 +34,47 @@ namespace mbts.spark {
|
||||
foreach(var p in d.ParamDesc)
|
||||
dorder.Dynamic.OrderParams.Add( p.ParamName, new DynamicOrderParam() );
|
||||
defs.Add(new CustomOrderDefinitionImmutable(dorder));
|
||||
var de = get_descriptor("");
|
||||
}
|
||||
}
|
||||
|
||||
internal DynamicOrderDescriptor get_descriptor(string dynamic_type) =>
|
||||
_dynamic_types.DynamicOrderDesc.FirstOrDefault(d => d.DynamicOrderType == dynamic_type);
|
||||
_dynamic_types.DynamicOrderDesc.FirstOrDefault(d => d.DynamicOrderType == dynamic_type) ?? new DynamicOrderDescriptor();
|
||||
|
||||
internal DynamicOrderDefinition create_def(string dynamic_type) {
|
||||
var desc = get_descriptor(dynamic_type);
|
||||
var def = new DynamicOrderDefinition();
|
||||
foreach (var p in desc.ParamDesc) {
|
||||
if (_is_child_algo_desc(p)) {
|
||||
def.OrderParams[p.ParamName] = new DynamicOrderParam { AsOrderDef = new CustomOrderDefinition() };
|
||||
} else if (_is_value_param_desc(p)) {
|
||||
var value_case = _get_value_case(p.ParamType.Primitive);
|
||||
if (_descriptor_case_index.TryGetValue(value_case, out (FieldDescriptor fd, Type type) tup)) {
|
||||
var dop = new DynamicOrderParam();
|
||||
tup.fd.Accessor.SetValue(dop, ConvertUtils.get_default(tup.type));
|
||||
def.OrderParams[p.ParamName] = dop;
|
||||
}
|
||||
}
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
static DynamicOrderParam.ValueOneofCase _get_value_case(DynamicOrderPrimitiveDescriptor primitive_descriptor_case) {
|
||||
switch (primitive_descriptor_case) {
|
||||
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveBool: return DynamicOrderParam.ValueOneofCase.AsBool;
|
||||
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveDouble: return DynamicOrderParam.ValueOneofCase.AsBool;
|
||||
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveInt: return DynamicOrderParam.ValueOneofCase.AsInt32;
|
||||
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveUint: return DynamicOrderParam.ValueOneofCase.AsUint32;
|
||||
case DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveString: return DynamicOrderParam.ValueOneofCase.AsString;
|
||||
default: throw ExceptionBuilder.Argument.unexpected_case(primitive_descriptor_case, nameof(primitive_descriptor_case));
|
||||
}
|
||||
}
|
||||
|
||||
static bool _is_child_algo_desc(DynamicOrderParamDescriptor desc) =>
|
||||
desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive &&
|
||||
desc.ParamType.Primitive == DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef;
|
||||
|
||||
static bool _is_value_param_desc(DynamicOrderParamDescriptor desc) =>
|
||||
desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated ||
|
||||
(desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive && desc.ParamType.Primitive != DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,28 +1,36 @@
|
||||
using bts.api.orderman;
|
||||
using mbts.collections;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using mbts.spark.utilities;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Threading.Tasks;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
namespace mbts.spark {
|
||||
static partial class OrderTypeVMFactory {
|
||||
class DynamicOrderVM : OrderTypeVMBase<DynamicOrderDefinition, DynamicOrderDefinitionImmutable> {
|
||||
readonly ObservableKeyedCollection<DynamicOrderParamVM, string> _parameters = new ObservableKeyedCollection<DynamicOrderParamVM, string>(vm => vm.descriptor.ParamName);
|
||||
readonly Property<string> _dyn_type;
|
||||
OrdersModel _model;
|
||||
bool _active;
|
||||
|
||||
public DynamicOrderVM(AlgoKey key, string dyn_type, string display_name, AlgoEditingPermissions editing_permissions)
|
||||
: base(key, display_name, editing_permissions) {
|
||||
_dyn_type = add_property(nameof(this.dyn_type), DynamicOrderDefinition.DynamicOrderTypeFieldNumber, dyn_type);
|
||||
_parameters = new ObservableKeyedCollection<DynamicOrderParamVM, string>(vm => vm.descriptor.ParamName);
|
||||
_resources.AddRange(
|
||||
_dyn_type.Subscribe(_ => _reset_dynamic_types()),
|
||||
_dyn_type.Subscribe(_ => {
|
||||
_sync_dynamic_params();
|
||||
sync_selectors();
|
||||
}),
|
||||
ObservableAutoWrapper.connect_item_hooks(_parameters.AsCollection(), pvm => {
|
||||
add_property(pvm.descriptor.ParamName, mdef => mdef.OrderParams[pvm.descriptor.ParamName] = pvm.param, mdef => {
|
||||
if (mdef.OrderParams.TryGetValue(pvm.descriptor.ParamName, out DynamicOrderParam p))
|
||||
pvm.param = p;
|
||||
});
|
||||
return Disposable.Create(() => remove_property(pvm.descriptor.ParamName));
|
||||
}),
|
||||
ObservableAutoWrapper.connect_item_hooks(_parameters, p => {
|
||||
p.PropertyChanged += on_param_prop_changed;
|
||||
return Disposable.Create(() => p.PropertyChanged -= on_param_prop_changed);
|
||||
@@ -31,103 +39,26 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
public string dyn_type => _dyn_type.Value;
|
||||
public ObservableCollection<DynamicOrderParamVM> parameters {
|
||||
get {
|
||||
_ensure_init();
|
||||
return _parameters;
|
||||
public ObservableCollection<DynamicOrderParamVM> parameters => _parameters;
|
||||
|
||||
protected override void on_model_internal() =>
|
||||
_sync_dynamic_params();
|
||||
|
||||
protected override IEnumerable<ChildAlgoData> get_selector_datum() =>
|
||||
OrderDataHelper.get_child_algo_data(new CustomOrderDefinition {
|
||||
Dynamic = model?.dynamic_helper?.create_def(dyn_type) ?? new DynamicOrderDefinition()
|
||||
});
|
||||
|
||||
void _sync_dynamic_params() {
|
||||
if (model != null) {
|
||||
var desc = model.dynamic_helper.get_descriptor(dyn_type);
|
||||
_parameters.SyncWithDictionary(desc.ParamDesc.Where(_is_value_param_desc).ToDictionary(p => p.ParamName), DynamicOrderParamVM.create);
|
||||
}
|
||||
}
|
||||
|
||||
protected override void assign_to_internal(DynamicOrderDefinition dynamic_def) {
|
||||
foreach (var vm in _parameters.Values)
|
||||
dynamic_def.OrderParams[vm.descriptor.ParamName] = vm.param;
|
||||
}
|
||||
|
||||
protected override void load_from_internal(DynamicOrderDefinitionImmutable dyn_defi) {
|
||||
foreach (var p in _parameters) {
|
||||
if (dyn_defi.OrderParams.TryGetValue(p.descriptor.ParamName, out DynamicOrderParam dop)) {
|
||||
p.param = dop;
|
||||
} else {
|
||||
p.param.ClearValue();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override async Task on_load_from_async(CustomOrderDefinitionImmutable defi) {
|
||||
await Wait.until_true(() => _model != null, TimeSpan.FromSeconds(60));
|
||||
_ensure_init();
|
||||
}
|
||||
|
||||
void _ensure_init() {
|
||||
if (!_active) {
|
||||
_active = true;
|
||||
// lazy initialization is required to avoid a stack overflow (otherwise, the algo-hierarchy would grow recursively without stopping).
|
||||
_reset_dynamic_types();
|
||||
}
|
||||
}
|
||||
protected override void on_model_internal(OrdersModel model) {
|
||||
_model = model;
|
||||
_reset_dynamic_types();
|
||||
}
|
||||
|
||||
void _reset_dynamic_types() {
|
||||
if (!_active)
|
||||
return;
|
||||
var value_descs = new Dictionary<string, DynamicOrderParamDescriptor>();
|
||||
var child_descs = new Dictionary<string, DynamicOrderParamDescriptor>();
|
||||
if (_model != null) {
|
||||
var desc = _model.dynamic_helper.get_descriptor(dyn_type);
|
||||
if (desc != null) {
|
||||
foreach (var p in desc.ParamDesc) {
|
||||
if (_is_value_param_desc(p)) {
|
||||
value_descs[p.ParamName] = p;
|
||||
} else if (_is_child_algo_desc(p)) {
|
||||
child_descs[p.ParamName] = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_parameters.SyncWithDictionary(value_descs, DynamicOrderParamVM.create);
|
||||
using (reset_selectors()) {
|
||||
foreach (var kv in child_descs) {
|
||||
add_selector(kv.Key, get_child, set_child);
|
||||
// local methods
|
||||
CustomOrderDefinitionImmutable? get_child(DynamicOrderDefinitionImmutable dyn_defi) {
|
||||
if (dyn_defi.OrderParams.TryGetValue(kv.Key, out DynamicOrderParam p) && p.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef)
|
||||
return new CustomOrderDefinitionImmutable(p.AsOrderDef);
|
||||
return null;
|
||||
}
|
||||
void set_child(DynamicOrderDefinition dyn_def, CustomOrderDefinition child) =>
|
||||
dyn_def.OrderParams[kv.Key] = new DynamicOrderParam { AsOrderDef = child };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static bool _is_child_algo_desc(DynamicOrderParamDescriptor desc) =>
|
||||
desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive &&
|
||||
desc.ParamType.Primitive == DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef;
|
||||
|
||||
static bool _is_value_param_desc(DynamicOrderParamDescriptor desc) =>
|
||||
desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Enumerated ||
|
||||
(desc.ParamType.DescriptorCase == DynamicOrderTypeDescriptor.DescriptorOneofCase.Primitive && desc.ParamType.Primitive != DynamicOrderPrimitiveDescriptor.DynamicOrderPrimitiveOrderDef);
|
||||
|
||||
public class SelectorVM : ViewModelBase {
|
||||
readonly IAlgoSelector _selector;
|
||||
|
||||
public SelectorVM(IAlgoSelector selector) {
|
||||
_selector = selector;
|
||||
_selector.selected_algo_changed += _on_selected_algo_changed;
|
||||
}
|
||||
|
||||
public IAlgoVM selected_algo { get => _selector.selected_algo; set => _selector.selected_algo = value; }
|
||||
public ObservableCollection<IAlgoVM> algos => _selector.algos;
|
||||
|
||||
public void Dispose() =>
|
||||
_selector.selected_algo_changed -= _on_selected_algo_changed;
|
||||
|
||||
void _on_selected_algo_changed(IAlgoVM oldval, IAlgoVM newval) =>
|
||||
RaisePropertyChanged(nameof(selected_algo));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -113,11 +113,12 @@ namespace mbts.spark {
|
||||
readonly IDictionary<string, object> _children_vm = new ExpandoObject();
|
||||
protected CompositeDisposable _resources = new CompositeDisposable();
|
||||
|
||||
readonly List<(Action<TMutable> assign, Action<TMutable> load)> _auto_props = new List<(Action<TMutable> assign, Action<TMutable> load)>();
|
||||
readonly ObservableKeyedCollection<(string name, Action<TMutable> assign, Action<TMutable> load), string> _auto_props = new ObservableKeyedCollection<(string name, Action<TMutable> assign, Action<TMutable> load), string>(t => t.name);
|
||||
readonly ObservableKeyedCollection<AlgoSelectorData, string> _child_algo_selector_data = new ObservableKeyedCollection<AlgoSelectorData, string>(sd => sd.prop_name);
|
||||
readonly ObservableAutoWrapper<IAlgoSelector, AlgoSelectorData> _child_algo_selectors;
|
||||
readonly Property<bool> _is_expanded, _can_save_values, _can_save_structure;
|
||||
readonly DeferrableActionWrapper _def_change_notifier;
|
||||
IDisposable _pending_load;
|
||||
|
||||
protected OrderTypeVMBase(AlgoKey id, string display_name, AlgoEditingPermissions editing_permissions) {
|
||||
this.id = id;
|
||||
@@ -127,9 +128,7 @@ namespace mbts.spark {
|
||||
_can_save_values = backing(nameof(can_save_values), true);
|
||||
_can_save_structure = backing(nameof(can_save_structure), true);
|
||||
_is_expanded = backing<bool>(nameof(is_expanded));
|
||||
foreach (var c in OrderDataHelper.get_child_algo_data(order_type)) {
|
||||
_children_vm[c.name] = add_selector(c.name, c.descriptor);
|
||||
}
|
||||
meta = OrderDataHelper.get_metadata(order_type);
|
||||
_def_change_notifier = new DeferrableActionWrapper(() => definition_changed?.Invoke());
|
||||
PropertyChanged += (s, e) => {
|
||||
switch (e.PropertyName) {
|
||||
@@ -170,39 +169,41 @@ namespace mbts.spark {
|
||||
}, true));
|
||||
}
|
||||
|
||||
public AlgoEditingPermissions editing_permissions { get; private set; }
|
||||
public event Action definition_changed;
|
||||
// core
|
||||
public AlgoDefi definition => new AlgoDefi(this.created_assigned());
|
||||
public AlgoType order_type => OrderDataHelper.get_order_type(new TMutable());
|
||||
public bool is_bts_type => display_name.StartsWith("BTS");
|
||||
public AlgoKey id { get; }
|
||||
// display
|
||||
public bool is_bts_type => display_name.StartsWith("BTS");
|
||||
public string display_name { get; private set; }
|
||||
public OrderMetadata meta => OrderDataHelper.get_metadata(order_type);
|
||||
public virtual bool can_expand => !meta.NoProps;
|
||||
public virtual bool is_expanded {
|
||||
get => _is_expanded.Value;
|
||||
set => _is_expanded.Value = value;
|
||||
}
|
||||
public OrderMetadata meta { get; }
|
||||
// child algos
|
||||
public dynamic children_vm => _children_vm;
|
||||
public ObservableCollection<IAlgoSelector> child_algo_selectors => _child_algo_selectors;
|
||||
// editing permissions
|
||||
public AlgoEditingPermissions editing_permissions { get; private set; }
|
||||
public bool can_edit_values => EnumHelper.includes_flag(editing_permissions, AlgoEditingPermissions.AllowEditValues);
|
||||
public bool can_edit_structure => EnumHelper.includes_flag(editing_permissions, AlgoEditingPermissions.AllowEditStructure);
|
||||
public bool can_save_values => _can_save_values.Value;
|
||||
public bool can_save_structure => _can_save_structure.Value;
|
||||
// misc
|
||||
public virtual bool can_expand => !meta.NoProps;
|
||||
public virtual bool is_expanded { get => _is_expanded.Value; set => _is_expanded.Value = value; }
|
||||
// protected (observed props)
|
||||
protected OrdersModel model { get; private set; }
|
||||
protected SecurityMD? security_md { get; private set; }
|
||||
protected SecurityImmutable? security => security_md?.security;
|
||||
|
||||
public void assign_to(AlgoDef value) {
|
||||
var algo = new TMutable();
|
||||
foreach (var (assign, load) in _auto_props)
|
||||
foreach (var (name, assign, load) in _auto_props)
|
||||
assign(algo);
|
||||
_descriptor.Accessor.SetValue(value, algo);
|
||||
foreach (var sd in _child_algo_selector_data) {
|
||||
if (sd.selector.selected_algo != null)
|
||||
sd.set_order(value, sd.selector.selected_algo.created_assigned());
|
||||
}
|
||||
assign_to_internal(algo);
|
||||
}
|
||||
|
||||
public void set_permissions(AlgoEditingPermissions editing_permissions) {
|
||||
@@ -217,26 +218,23 @@ namespace mbts.spark {
|
||||
public void load_from(AlgoDefi value) {
|
||||
if (value.CustomCase != order_type)
|
||||
return;
|
||||
using (_def_change_notifier.defer_execution()) {
|
||||
foreach (var sd in _child_algo_selector_data) {
|
||||
var inner_def = sd.get_order(value);
|
||||
if (inner_def.HasValue) {
|
||||
if (security.HasValue) {
|
||||
inner_def = OrderDataHelper.fit_to_type(inner_def.Value, security.Value.ContractCase);
|
||||
if (!inner_def.HasValue)
|
||||
continue;
|
||||
var algom = _descriptor.Accessor.GetValue(value.CloneToMutable()) as TMutable ?? new TMutable();
|
||||
Disposable.replace(ref _pending_load,
|
||||
new CompositeDisposable(
|
||||
ObservableAutoWrapper.connect_item_actions(_child_algo_selector_data.AsCollection(), sd => {
|
||||
var inner_def = sd.get_order(value);
|
||||
if (inner_def.HasValue) {
|
||||
if (security.HasValue) {
|
||||
inner_def = OrderDataHelper.fit_to_type(inner_def.Value, security.Value.ContractCase);
|
||||
if (!inner_def.HasValue)
|
||||
return;
|
||||
}
|
||||
var vm = sd.selector.algos.GetOrAdd(OrderDataHelper.get_shallow_factory_key(inner_def.Value), k => create(k, inner_def.Value.display_name(), inner_def.Value.CustomCase));
|
||||
vm.load_from(inner_def.Value);
|
||||
sd.selector.selected_algo = vm;
|
||||
}
|
||||
var vm = sd.selector.algos.GetOrAdd(OrderDataHelper.get_shallow_factory_key(inner_def.Value), k => create(k, inner_def.Value.display_name(), inner_def.Value.CustomCase));
|
||||
vm.load_from(inner_def.Value);
|
||||
sd.selector.selected_algo = vm;
|
||||
}
|
||||
}
|
||||
var algom = _descriptor.Accessor.GetValue(value.CloneToMutable()) as TMutable ?? new TMutable();
|
||||
var algoi = _create_immutable(algom);
|
||||
foreach (var (assign, load) in _auto_props)
|
||||
load(algom);
|
||||
load_from_internal(algoi);
|
||||
}
|
||||
}),
|
||||
ObservableAutoWrapper.connect_item_actions(_auto_props.AsCollection(), p => p.load(algom))));
|
||||
}
|
||||
|
||||
public virtual async Task<AlgoDefi?> load_from_async(AlgoDefi defi) {
|
||||
@@ -254,92 +252,72 @@ namespace mbts.spark {
|
||||
}
|
||||
}
|
||||
var algom = _descriptor.Accessor.GetValue(defi.CloneToMutable()) as TMutable ?? new TMutable();
|
||||
var algoi = _create_immutable(algom);
|
||||
foreach (var (assign, load) in _auto_props)
|
||||
foreach (var (name, assign, load) in _auto_props)
|
||||
load(algom);
|
||||
load_from_internal(algoi);
|
||||
return defi;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual Task on_load_from_async(AlgoDefi defi) => Task.CompletedTask;
|
||||
protected virtual void assign_to_internal(TMutable value) { }
|
||||
protected virtual void load_from_internal(TImmutable value) { }
|
||||
|
||||
protected void raise_definition_changed() =>
|
||||
_def_change_notifier.execute();
|
||||
|
||||
protected virtual void validate() { }
|
||||
|
||||
protected virtual void on_permissions_changed() {
|
||||
foreach (var vm in child_algo_selectors.SelectMany(s => s.algos.AsCollection()))
|
||||
vm.set_permissions(editing_permissions);
|
||||
}
|
||||
|
||||
protected void raise_definition_changed() =>
|
||||
_def_change_notifier.execute();
|
||||
|
||||
protected virtual void validate() { }
|
||||
|
||||
protected override void Dispose(bool disposing) =>
|
||||
Disposable.dispose(ref _resources);
|
||||
|
||||
#region Chidl Algo Selectors (add/remove/reset)
|
||||
protected IAlgoSelector add_selector(string vm_prop_name, FieldDescriptor inner_desc) {
|
||||
return add_selector(vm_prop_name, def => {
|
||||
if (_descriptor.Accessor.GetValue(def.CloneToMutable()) is TMutable mval) {
|
||||
if (inner_desc.Accessor.GetValue(mval) is AlgoDef inner_def)
|
||||
return new AlgoDefi(inner_def);
|
||||
}
|
||||
return null;
|
||||
}, (mdef, inner_def) => {
|
||||
if (_descriptor.Accessor.GetValue(mdef) is TMutable mval)
|
||||
inner_desc.Accessor.SetValue(mval, inner_def);
|
||||
});
|
||||
}
|
||||
|
||||
protected IAlgoSelector add_selector(string prop_name, Func<AlgoDefi, AlgoDefi?> get_order, Action<AlgoDef, AlgoDef> set_order) =>
|
||||
add_selector(prop_name, get_order, set_order, (s, e) => validate());
|
||||
|
||||
protected IAlgoSelector add_selector(string prop_name, Func<AlgoDefi, AlgoDefi?> get_order, Action<AlgoDef, AlgoDef> set_order, EventHandler<DataErrorsChangedEventArgs> on_errors_changed) {
|
||||
var rv = new AlgoSelector();
|
||||
_child_algo_selector_data[prop_name] = new AlgoSelectorData(prop_name, rv, get_order, set_order);
|
||||
return rv;
|
||||
}
|
||||
|
||||
protected IAlgoSelector add_selector(string prop_name, Func<TImmutable, AlgoDefi?> get_algo, Action<TMutable, AlgoDef> set_algo) {
|
||||
var rv = new AlgoSelector();
|
||||
_child_algo_selector_data[prop_name] = new AlgoSelectorData(prop_name, rv, def => _descriptor.Accessor.GetValue(def.CloneToMutable()) is TMutable mval ? get_algo(_create_immutable(mval)) : null,
|
||||
(def, child_def) => {
|
||||
if (_descriptor.Accessor.GetValue(def) is TMutable mval)
|
||||
set_algo(mval, child_def);
|
||||
});
|
||||
return rv;
|
||||
}
|
||||
|
||||
protected bool remove_selector(string prop_name) =>
|
||||
_child_algo_selector_data.Remove(prop_name);
|
||||
|
||||
/// TODO: maybe <see cref="_child_algo_selector_data"/> should just be a protected field?
|
||||
/// Conversely, it is nice to hide these sort of implementation-specific details from inheriting classes.
|
||||
/// Fwiw, as of 2/12/2019, the only class that needs the ability to add/remove selectors dynamically is <see cref="DynamicOrderVM"/>.
|
||||
/// The other implementations simply add a whatever selectors they need in their constructor.
|
||||
protected IDisposable reset_selectors() {
|
||||
var to_remove = _child_algo_selector_data.Keys.ToList();
|
||||
_child_algo_selector_data.CollectionChanged += on_change;
|
||||
void on_change(object sender, NotifyCollectionChangedEventArgs e) {
|
||||
switch (e.Action) {
|
||||
case NotifyCollectionChangedAction.Reset:
|
||||
throw new InvalidOperationException($"{nameof(_child_algo_selector_data)} was reset; unable to continue processing incremental changes.");
|
||||
default:
|
||||
// catches Replace/Remove/Add ops (Add ops account for cases where the item was effectively replaced by a remove/re-add)
|
||||
if (e.NewItems != null) {
|
||||
foreach (AlgoSelectorData sd in e.NewItems)
|
||||
to_remove.Remove(sd.prop_name);
|
||||
}
|
||||
break;
|
||||
#region Child Algo Selectors
|
||||
protected virtual IEnumerable<ChildAlgoData> get_selector_datum() =>
|
||||
OrderDataHelper.get_child_algo_data(order_type);
|
||||
|
||||
protected void sync_selectors() {
|
||||
using (reset()) {
|
||||
foreach (var c in get_selector_datum()) {
|
||||
_children_vm[c.name] = mk_selector(c.name, new Func<AlgoDefi, AlgoDefi?>(defi => {
|
||||
var mchild = c.get_child(defi.CloneToMutable());
|
||||
if (mchild != null)
|
||||
return new AlgoDefi(mchild);
|
||||
return null;
|
||||
}),
|
||||
c.assign_child);
|
||||
}
|
||||
_populate_selectors();
|
||||
}
|
||||
// local methods
|
||||
IDisposable reset() {
|
||||
var to_remove = _child_algo_selector_data.Keys.ToList();
|
||||
_child_algo_selector_data.CollectionChanged += on_change;
|
||||
void on_change(object sender, NotifyCollectionChangedEventArgs e) {
|
||||
switch (e.Action) {
|
||||
case NotifyCollectionChangedAction.Reset:
|
||||
throw new InvalidOperationException($"{nameof(_child_algo_selector_data)} was reset; unable to continue processing incremental changes.");
|
||||
default:
|
||||
// catches Replace/Remove/Add ops (Add ops account for cases where the item was effectively replaced by a remove/re-add)
|
||||
if (e.NewItems != null) {
|
||||
foreach (AlgoSelectorData sd in e.NewItems)
|
||||
to_remove.Remove(sd.prop_name);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return Disposable.Create(() => {
|
||||
_child_algo_selector_data.CollectionChanged -= on_change;
|
||||
foreach (var id in to_remove)
|
||||
_child_algo_selector_data.Remove(id);
|
||||
});
|
||||
}
|
||||
IAlgoSelector mk_selector(string prop_name, Func<AlgoDefi, AlgoDefi?> get_order, Action<AlgoDef, AlgoDef> set_order) {
|
||||
var rv = new AlgoSelector();
|
||||
_child_algo_selector_data[prop_name] = new AlgoSelectorData(prop_name, rv, get_order, set_order);
|
||||
return rv;
|
||||
}
|
||||
return Disposable.Create(() => {
|
||||
_child_algo_selector_data.CollectionChanged -= on_change;
|
||||
foreach (var id in to_remove)
|
||||
_child_algo_selector_data.Remove(id);
|
||||
});
|
||||
}
|
||||
#endregion
|
||||
|
||||
@@ -347,7 +325,7 @@ namespace mbts.spark {
|
||||
protected Property<T> add_property<T>(string prop_name, int target_field_number, T init_value = default) {
|
||||
var prop = backing(prop_name, init_value);
|
||||
var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number);
|
||||
_auto_props.Add((mval => {
|
||||
_auto_props.Add((prop_name, mval => {
|
||||
if (mval != null)
|
||||
field_desc.Accessor.SetValue(mval, prop.Value);
|
||||
}, mval => {
|
||||
@@ -356,22 +334,12 @@ namespace mbts.spark {
|
||||
return prop;
|
||||
}
|
||||
|
||||
protected UserProperty<T> add_user_property<T>(string prop_name, int target_field_number, T init_value = default) {
|
||||
var prop = user_backing(prop_name, init_value);
|
||||
var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number);
|
||||
add_property(
|
||||
mdef => ConvertUtils.try_convert<T>(field_desc.Accessor.GetValue(mdef)),
|
||||
(mdef, val) => field_desc.Accessor.SetValue(mdef, val),
|
||||
val => prop.bypass_setter(val),
|
||||
() => prop.Value);
|
||||
return prop;
|
||||
}
|
||||
|
||||
protected Property<TImmutableValue> add_property<TMutableValue, TImmutableValue>(string prop_name, int target_field_number, TImmutableValue init_value = default) where TMutableValue : class, IMessage, new() where TImmutableValue : IImmutableMessage {
|
||||
var prop = backing(prop_name, init_value);
|
||||
var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number);
|
||||
var immutable_factory = OrderTypeVMUtils.immutable_factory<TMutableValue, TImmutableValue>();
|
||||
add_property<TMutableValue>(
|
||||
prop_name,
|
||||
mdef => field_desc.Accessor.GetValue(mdef) as TMutableValue,
|
||||
(mdef, mval) => field_desc.Accessor.SetValue(mdef, mval),
|
||||
mval => prop.set(immutable_factory(mval ?? new TMutableValue())),
|
||||
@@ -383,15 +351,36 @@ namespace mbts.spark {
|
||||
return prop;
|
||||
}
|
||||
|
||||
protected void add_property<TValue>(Func<TMutable, TValue> get_from_def, Action<TMutable, TValue> assign_to_def, Action<TValue> set_local, Func<TValue> get_local) =>
|
||||
_auto_props.Add((def => {
|
||||
protected void add_property<TValue>(string prop_name, Func<TMutable, TValue> get_from_def, Action<TMutable, TValue> assign_to_def, Action<TValue> set_local, Func<TValue> get_local) =>
|
||||
_auto_props.Add((
|
||||
prop_name,
|
||||
def => {
|
||||
assign_to_def(def, get_local());
|
||||
}, def => {
|
||||
set_local(get_from_def(def));
|
||||
}));
|
||||
|
||||
protected virtual void on_model_internal(OrdersModel model) { }
|
||||
protected virtual void on_security_md_internal(SecurityMD? security_md) { }
|
||||
protected void add_property(string prop_name, Action<TMutable> assign, Action<TMutable> load) =>
|
||||
_auto_props[prop_name] = (prop_name, assign, load);
|
||||
|
||||
protected UserProperty<T> add_user_property<T>(string prop_name, int target_field_number, T init_value = default) {
|
||||
var prop = user_backing(prop_name, init_value);
|
||||
var field_desc = new TMutable().Descriptor.FindFieldByNumber(target_field_number);
|
||||
add_property(
|
||||
prop_name,
|
||||
mdef => ConvertUtils.try_convert<T>(field_desc.Accessor.GetValue(mdef)),
|
||||
(mdef, val) => field_desc.Accessor.SetValue(mdef, val),
|
||||
val => prop.bypass_setter(val),
|
||||
() => prop.Value);
|
||||
return prop;
|
||||
}
|
||||
|
||||
protected void remove_property(string prop_name) =>
|
||||
_auto_props.Remove(prop_name);
|
||||
#endregion
|
||||
|
||||
protected virtual void on_model_internal() { }
|
||||
protected virtual void on_security_md_internal() { }
|
||||
|
||||
// model
|
||||
void IObserver<OrdersModel>.OnNext(OrdersModel model) {
|
||||
@@ -402,36 +391,39 @@ namespace mbts.spark {
|
||||
return;
|
||||
}
|
||||
this.model = model;
|
||||
on_model_internal(model);
|
||||
_reset();
|
||||
using (_def_change_notifier.defer_execution()) {
|
||||
on_model_internal();
|
||||
sync_selectors();
|
||||
}
|
||||
}
|
||||
void IObserver<OrdersModel>.OnError(Exception error) { }
|
||||
void IObserver<OrdersModel>.OnCompleted() { }
|
||||
// security md
|
||||
void IObserver<SecurityMD?>.OnNext(SecurityMD? security_md) {
|
||||
this.security_md = security_md;
|
||||
on_security_md_internal(security_md);
|
||||
_reset();
|
||||
using (_def_change_notifier.defer_execution()) {
|
||||
on_security_md_internal();
|
||||
_populate_selectors();
|
||||
}
|
||||
}
|
||||
void IObserver<SecurityMD?>.OnError(Exception error) { }
|
||||
void IObserver<SecurityMD?>.OnCompleted() { }
|
||||
|
||||
IDisposable _hook;
|
||||
void _reset() {
|
||||
IDisposable _selector_data_hooks;
|
||||
void _populate_selectors() {
|
||||
if (model != null && security.HasValue) {
|
||||
var algo_data = model.factory.default_algos(security.Value);
|
||||
var default_algo = new AlgoKey(OrderDataHelper.get_default_algo(OrderDataHelper.get_algo_format(security.Value.ContractCase)));
|
||||
foreach (var sd in _child_algo_selectors)
|
||||
sd.load_algo_data_recursive(algo_data, default_algo);
|
||||
Disposable.replace(ref _hook, ObservableAutoWrapper.connect_item_hooks(child_algo_selectors, s => {
|
||||
s.load_algo_data_recursive(algo_data, default_algo);
|
||||
return Disposable.empty;
|
||||
}));
|
||||
Disposable.replace(
|
||||
ref _selector_data_hooks,
|
||||
ObservableAutoWrapper.connect_item_hooks(child_algo_selectors, s => {
|
||||
s.load_algo_data_recursive(algo_data, default_algo);
|
||||
return Disposable.empty;
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
public IDisposable Subscribe(IObserver<OrdersModel> observer) => throw new NotImplementedException();
|
||||
#endregion
|
||||
}
|
||||
|
||||
struct AlgoSelectorData {
|
||||
@@ -521,4 +513,4 @@ namespace mbts.spark {
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,38 @@ namespace mbts.spark {
|
||||
_template = backing<SpreaderDefi?>(nameof(template));
|
||||
/// <see cref="_strategy_editor_wrapper"/> depends on <see cref="_template"/> (i.e. initialize the latter first).
|
||||
_strategy_editor_wrapper = new StrategyEditorWrapper(this);
|
||||
concat_disposable(_strategy_editor_wrapper, _template.Subscribe(vals => validate()));
|
||||
_resources.AddRange(_strategy_editor_wrapper, _template.Subscribe(vals => validate()));
|
||||
// strategy
|
||||
add_property(
|
||||
nameof(SpreaderDef.ExecutionStrategy),
|
||||
mdef => mdef.ExecutionStrategy,
|
||||
(mdef, val) => mdef.ExecutionStrategy = val,
|
||||
val => {
|
||||
if (template.HasValue) {
|
||||
template = template.Value.with(execution_strategy: val);
|
||||
} else {
|
||||
var mdef = new SpreaderDef {
|
||||
Security = security?.CloneToMutable(),
|
||||
ExecutionStrategy = val
|
||||
};
|
||||
template = new SpreaderDefi(mdef);
|
||||
}
|
||||
},
|
||||
() => strategy_editor?.get_strategy().CloneToMutable());
|
||||
// security
|
||||
add_property(
|
||||
nameof(SpreaderDef.Security),
|
||||
mdef => mdef.Security,
|
||||
(mdef, val) => mdef.Security = val,
|
||||
val => {
|
||||
if (template.HasValue) {
|
||||
template = template.Value.with(security: val);
|
||||
} else {
|
||||
var mdef = new SpreaderDef { Security = val };
|
||||
template = new SpreaderDefi(mdef);
|
||||
}
|
||||
},
|
||||
() => security?.CloneToMutable());
|
||||
validate();
|
||||
}
|
||||
|
||||
@@ -43,12 +74,6 @@ namespace mbts.spark {
|
||||
}
|
||||
public bool is_loaded { get; private set; }
|
||||
|
||||
protected override void assign_to_internal(SpreaderDef value) =>
|
||||
value.MergeFrom(template.HasValue ? template.Value.CloneToMutable() : new SpreaderDef());
|
||||
|
||||
protected override void load_from_internal(SpreaderDefi value) =>
|
||||
_template.set(value);
|
||||
|
||||
protected override void validate() {
|
||||
base.validate();
|
||||
if (!template.HasValue)
|
||||
|
||||
@@ -31,11 +31,6 @@ namespace mbts.spark {
|
||||
|
||||
public ContractSpecificationImmutable? spec => _security_md.spec_or_default();
|
||||
|
||||
protected override void load_from_internal(StopLimitDefi value) {
|
||||
// TODO: the StopLimitOrderDefinition, StopLimitOrderDefinitionImmutable needs relative vs absolute prices to function as a useful template (talk to Pedro)
|
||||
_stop_price.bypass_setter(value.StopPrice);
|
||||
}
|
||||
|
||||
// no need to constantly poll the md, just check the inline props when the popup opens, and right before sending an order
|
||||
// (if the user never looks at the popup, assume that the bid_price will be used)
|
||||
// TODO: add settings so the trigger-price can default to something relative to the md, e.g "bid-price" or "ask-price - nticks" or "best-bid-price with a minimum size of 10"
|
||||
|
||||
@@ -16,14 +16,26 @@ namespace mbts.spark {
|
||||
|
||||
public TimeBoxOrderVM(AlgoKey key, string display_name, AlgoEditingPermissions editing_permissions)
|
||||
: base(key, display_name, editing_permissions) {
|
||||
add_property(def => def.Start, (def, val) => def.Start = val, val => absolute_start = TimeTextTuple.FromDateTime(val.ToDateTime()), () => {
|
||||
_validate(out DateTime? start_time, out DateTime? _);
|
||||
return start_time.GetValueOrDefault().ToUniversalTime().ToGoogleTime();
|
||||
});
|
||||
add_property(def => def.Stop, (def, val) => def.Stop = val, val => absolute_stop = TimeTextTuple.FromDateTime(val.ToDateTime()), () => {
|
||||
_validate(out DateTime? _, out DateTime? stop_time);
|
||||
return stop_time.GetValueOrDefault().ToUniversalTime().ToGoogleTime();
|
||||
});
|
||||
// start
|
||||
add_property(
|
||||
nameof(TimeBoxOrderDefinition.Start),
|
||||
def => def.Start,
|
||||
(def, val) => def.Start = val,
|
||||
val => absolute_start = TimeTextTuple.FromDateTime(val.ToDateTime()),
|
||||
() => {
|
||||
_validate(out DateTime? start_time, out DateTime? _);
|
||||
return start_time.GetValueOrDefault().ToUniversalTime().ToGoogleTime();
|
||||
});
|
||||
// stop
|
||||
add_property(
|
||||
nameof(TimeBoxOrderDefinition.Stop),
|
||||
def => def.Stop,
|
||||
(def, val) => def.Stop = val,
|
||||
val => absolute_stop = TimeTextTuple.FromDateTime(val.ToDateTime()),
|
||||
() => {
|
||||
_validate(out DateTime? _, out DateTime? stop_time);
|
||||
return stop_time.GetValueOrDefault().ToUniversalTime().ToGoogleTime();
|
||||
});
|
||||
validate();
|
||||
}
|
||||
|
||||
|
||||
@@ -31,13 +31,64 @@ namespace mbts.spark {
|
||||
_is_priceout_checked = create_user_prop(nameof(is_priceout_checked), false);
|
||||
_is_timeout_checked = create_user_prop(nameof(is_timeout_checked), false);
|
||||
_timeout_secs = create_user_prop(nameof(timeout_secs), 10);
|
||||
add_property(nameof(TriggerDef), assign, load);
|
||||
validate();
|
||||
//
|
||||
// local methods
|
||||
UserProperty<T> create_user_prop<T>(string name, T default_value = default) {
|
||||
var rv = user_backing(name, default_value);
|
||||
rv.Changed += validation_callback;
|
||||
return rv;
|
||||
}
|
||||
void assign(TriggerDef trigger_def) {
|
||||
trigger_def.TriggerAction = new TriggerAction();
|
||||
if (security.HasValue)
|
||||
trigger_def.TriggerAction.SecurityId = security.Value.Id;
|
||||
trigger_def.TriggerCondition = new TriggerCondition() {
|
||||
PriceType = trigger_price_type,
|
||||
AbsolutePriceTrigger = new AbsolutePriceTrigger() { TriggerQuantity = new TriggerQuantity() },
|
||||
};
|
||||
trigger_def.ExitCondition = new TriggerExitCondition {
|
||||
ConditionalCancel = is_priceout_checked,
|
||||
TimeoutEnabled = is_timeout_checked,
|
||||
TimeoutSeconds = (uint)(timeout_secs)
|
||||
};
|
||||
switch (order_price_case) {
|
||||
case OrderpriceOneofCase.Price:
|
||||
// should already be null, setting it here for clarity
|
||||
trigger_def.TriggerAction.Payup = null;
|
||||
trigger_def.TriggerAction.Price = fixed_price;
|
||||
break;
|
||||
case OrderpriceOneofCase.Payup:
|
||||
trigger_def.TriggerAction.Price = double.NaN;
|
||||
trigger_def.TriggerAction.Payup = new TriggerPayupPrice {
|
||||
PayupTicks = payup_ticks,
|
||||
PayupPriceType = payup_price_type
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
void load(TriggerDef trigger_defi) {
|
||||
if (trigger_defi.TriggerCondition is TriggerCondition c) {
|
||||
trigger_price_type = c.PriceType;
|
||||
}
|
||||
if (trigger_defi.ExitCondition is TriggerExitCondition ec) {
|
||||
is_priceout_checked = ec.ConditionalCancel;
|
||||
is_timeout_checked = ec.TimeoutEnabled;
|
||||
if (ec.TimeoutSeconds < int.MaxValue)
|
||||
timeout_secs = (int)ec.TimeoutSeconds;
|
||||
}
|
||||
if (trigger_defi.TriggerAction is TriggerAction a) {
|
||||
if (a.Payup is TriggerPayupPrice pp) {
|
||||
order_price_case = OrderpriceOneofCase.Payup;
|
||||
fixed_price = double.NaN;
|
||||
payup_ticks = pp.PayupTicks;
|
||||
payup_price_type = pp.PayupPriceType;
|
||||
} else {
|
||||
order_price_case = OrderpriceOneofCase.Price;
|
||||
fixed_price = a.Price;
|
||||
}
|
||||
}
|
||||
}
|
||||
void validation_callback<T>(T oldval, T newval) => validate();
|
||||
}
|
||||
|
||||
@@ -56,68 +107,20 @@ namespace mbts.spark {
|
||||
public bool is_timeout_checked { get => _is_timeout_checked.Value; set => _is_timeout_checked.Value = value; }
|
||||
public int timeout_secs { get => _timeout_secs.Value; set => _timeout_secs.Value = value; }
|
||||
|
||||
protected override void assign_to_internal(TriggerDef trigger_def) {
|
||||
trigger_def.TriggerAction = new TriggerAction();
|
||||
if (security.HasValue)
|
||||
trigger_def.TriggerAction.SecurityId = security.Value.Id;
|
||||
trigger_def.TriggerCondition = new TriggerCondition() {
|
||||
PriceType = trigger_price_type,
|
||||
AbsolutePriceTrigger = new AbsolutePriceTrigger() { TriggerQuantity = new TriggerQuantity() },
|
||||
};
|
||||
trigger_def.ExitCondition = new TriggerExitCondition {
|
||||
ConditionalCancel = is_priceout_checked,
|
||||
TimeoutEnabled = is_timeout_checked,
|
||||
TimeoutSeconds = (uint)(timeout_secs)
|
||||
};
|
||||
switch (order_price_case) {
|
||||
case OrderpriceOneofCase.Price:
|
||||
// should already be null, setting it here for clarity
|
||||
trigger_def.TriggerAction.Payup = null;
|
||||
trigger_def.TriggerAction.Price = fixed_price;
|
||||
break;
|
||||
case OrderpriceOneofCase.Payup:
|
||||
trigger_def.TriggerAction.Price = double.NaN;
|
||||
trigger_def.TriggerAction.Payup = new TriggerPayupPrice {
|
||||
PayupTicks = payup_ticks,
|
||||
PayupPriceType = payup_price_type
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void load_from_internal(TriggerDefi trigger_defi) {
|
||||
if (trigger_defi.HasTriggerCondition) {
|
||||
trigger_price_type = trigger_defi.TriggerCondition.PriceType;
|
||||
}
|
||||
if (trigger_defi.HasExitCondition) {
|
||||
var exit_condition = trigger_defi.ExitCondition;
|
||||
is_priceout_checked = exit_condition.ConditionalCancel;
|
||||
is_timeout_checked = exit_condition.TimeoutEnabled;
|
||||
if (exit_condition.TimeoutSeconds < int.MaxValue)
|
||||
timeout_secs = (int)exit_condition.TimeoutSeconds;
|
||||
}
|
||||
if (trigger_defi.HasTriggerAction) {
|
||||
var trigger_action = trigger_defi.TriggerAction;
|
||||
if (trigger_action.HasPayup) {
|
||||
order_price_case = OrderpriceOneofCase.Payup;
|
||||
fixed_price = double.NaN;
|
||||
var payup = trigger_action.Payup;
|
||||
payup_ticks = payup.PayupTicks;
|
||||
payup_price_type = payup.PayupPriceType;
|
||||
} else {
|
||||
order_price_case = OrderpriceOneofCase.Price;
|
||||
fixed_price = trigger_action.Price;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _refresh_md() {
|
||||
protected override void on_security_md_internal() {
|
||||
if (security.HasValue) {
|
||||
security_md.Value.md.get_bbo(ref _bbo_ref, out co2.NativePriceSize bid, out co2.NativePriceSize ask);
|
||||
_best_bid = bid.price;
|
||||
_best_ask = ask.price;
|
||||
security_md.Value.md.get_last_trade(ref _last_trade_ref, out co2.NativePriceSize ps, out DateTime ts, out ulong v);
|
||||
}
|
||||
if (double.IsNaN(fixed_price) || !_fixed_price.setter_called) {
|
||||
switch (trigger_price_type) {
|
||||
case TriggerPriceType.Bid: _fixed_price.bypass_setter(_best_bid); break;
|
||||
case TriggerPriceType.Ask: _fixed_price.bypass_setter(_best_ask); break;
|
||||
case TriggerPriceType.LastTradePrice: _fixed_price.bypass_setter(_last_trade_price); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected override void validate() {
|
||||
@@ -131,17 +134,6 @@ namespace mbts.spark {
|
||||
}
|
||||
assert(!is_timeout_checked || timeout_secs > 0, nameof(timeout_secs), "Please specify valid Timeout(secs).");
|
||||
}
|
||||
|
||||
protected override void on_security_md_internal(SecurityMD? security_md) {
|
||||
_refresh_md();
|
||||
if (double.IsNaN(fixed_price) || !_fixed_price.setter_called) {
|
||||
switch (trigger_price_type) {
|
||||
case TriggerPriceType.Bid: _fixed_price.bypass_setter(_best_bid); break;
|
||||
case TriggerPriceType.Ask: _fixed_price.bypass_setter(_best_ask); break;
|
||||
case TriggerPriceType.LastTradePrice: _fixed_price.bypass_setter(_last_trade_price); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
using bts.collections;
|
||||
using bts.utils;
|
||||
using mbts.utils;
|
||||
using NUnit.Framework;
|
||||
@@ -11,11 +10,6 @@ using System.Linq;
|
||||
using System.Reactive.Disposables;
|
||||
|
||||
namespace mbts.ui.utility {
|
||||
/// <summary>
|
||||
/// The sole purpose of this class is to offer a less verbose alternative to
|
||||
/// "new ObservableAutoWrapper<LongTypeName............, AnotherLongTypeName.........>(doodi, poodi)"
|
||||
/// when the generic types are implicit
|
||||
/// </summary>
|
||||
static class ObservableAutoWrapper {
|
||||
public static ObservableAutoWrapper<View, Model> Create<View, Model>(ObservableCollection<Model> models, Func<Model, View> converter) {
|
||||
return new ObservableAutoWrapper<View, Model>(models, converter);
|
||||
@@ -198,6 +192,12 @@ namespace mbts.ui.utility {
|
||||
}
|
||||
}
|
||||
|
||||
public static IDisposable connect_item_actions<T>(IReadOnlyObservableCollection<T> source, Action<T> action) =>
|
||||
source.Subscribe((s, e) => CollectionHelper.process_new_items(source, action, e));
|
||||
|
||||
public static IDisposable connect_item_actions<T>(ObservableCollection<T> source, Action<T> action) =>
|
||||
source.Subscribe((s, e) => CollectionHelper.process_new_items(source, action, e));
|
||||
|
||||
public static IDisposable connect_item_hooks<T>(IReadOnlyObservableCollection<T> source, Func<T, IDisposable> get_item_hook) {
|
||||
var item_hooks = source.Select(get_item_hook).ToList();
|
||||
return new CompositeDisposable(
|
||||
|
||||
@@ -75,6 +75,20 @@ namespace mbts.utils {
|
||||
}
|
||||
}
|
||||
|
||||
public static void process_new_items<T>(IEnumerable<T> source, Action<T> on_new_item, NotifyCollectionChangedEventArgs e) {
|
||||
switch (e.Action) {
|
||||
case NotifyCollectionChangedAction.Add:
|
||||
case NotifyCollectionChangedAction.Replace:
|
||||
foreach (T v in e.NewItems)
|
||||
on_new_item(v);
|
||||
break;
|
||||
case NotifyCollectionChangedAction.Reset:
|
||||
foreach (T v in source)
|
||||
on_new_item(v);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Note: this is not optimized, be wary of use with large collections
|
||||
public static void sync_with_never_duplicate<T>(ObservableCollection<T> dest, IEnumerable<T> src) =>
|
||||
sync_with_never_duplicate(dest, src, EqualityComparer<T>.Default);
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
using mbts;
|
||||
using Google.Protobuf;
|
||||
using Google.Protobuf.Reflection;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using mbts.utils;
|
||||
|
||||
namespace bts.utils {
|
||||
static class ProtoHelper {
|
||||
const string
|
||||
_case_suffix = "Case",
|
||||
_oneof_case_suffix = "OneofCase";
|
||||
|
||||
public static MessageDescriptor Descriptor<T>() where T : IMessage, new() =>
|
||||
_DescriptorImpl<T>.value;
|
||||
|
||||
public static OneofDescriptor get_oneof_descriptor<T>(string prop_name) where T : IMessage, new() {
|
||||
prop_name = prop_name.iremove_suffix(_case_suffix);
|
||||
return Descriptor<T>().Oneofs.FirstOrDefault(d => d.Name.iequals(prop_name));
|
||||
}
|
||||
|
||||
public static IReadOnlyDictionary<TOneofCase, (FieldDescriptor field_descriptor, Type field_type)> get_oneof_descriptor_index<T, TOneofCase>(string prop_name)
|
||||
where T : IMessage, new()
|
||||
where TOneofCase : struct =>
|
||||
_DescriptorImpl<T>.OneofImpl<TOneofCase>.get_descriptor_case_index(prop_name);
|
||||
|
||||
public static FieldDescriptor get_oneof_field_descriptor<T, TOneofCase>(TOneofCase oneof_case) where T : IMessage, new() where TOneofCase : struct {
|
||||
string oneof_name = oneof_case.ToString();
|
||||
return Descriptor<T>().Fields.InFieldNumberOrder().FirstOrDefault(fd => fd.Name.Replace("_", "").iequals(oneof_name));
|
||||
}
|
||||
|
||||
public static Type get_field_type(FieldDescriptor field_descriptor) {
|
||||
switch (field_descriptor.FieldType) {
|
||||
case FieldType.Bool: return typeof(bool);
|
||||
case FieldType.Bytes: return typeof(ByteString);
|
||||
case FieldType.Double: return typeof(double);
|
||||
case FieldType.Float: return typeof(float);
|
||||
case FieldType.UInt32: return typeof(uint);
|
||||
case FieldType.UInt64: return typeof(ulong);
|
||||
// int
|
||||
case FieldType.SFixed32:
|
||||
case FieldType.Fixed32:
|
||||
case FieldType.SInt32:
|
||||
case FieldType.Int32: return typeof(int);
|
||||
// long
|
||||
case FieldType.SFixed64:
|
||||
case FieldType.Fixed64:
|
||||
case FieldType.SInt64:
|
||||
case FieldType.Int64: return typeof(long);
|
||||
//
|
||||
case FieldType.String: return typeof(string);
|
||||
case FieldType.Enum: return field_descriptor.EnumType.ClrType;
|
||||
case FieldType.Message: return field_descriptor.MessageType.ClrType;
|
||||
default: throw ExceptionBuilder.Argument.unexpected_case(field_descriptor.FieldType, nameof(field_descriptor));
|
||||
}
|
||||
}
|
||||
|
||||
public static IReadOnlyDictionary<TOneofCase, FieldDescriptor> get_oneof_descriptor_index<TOneofCase>(OneofDescriptor descriptor) where TOneofCase : struct =>
|
||||
descriptor.Fields.ToDictionary(fd => EnumHelper.parse<TOneofCase>(fd.Name.Replace("_", "")));
|
||||
|
||||
static class _DescriptorImpl<T> where T : IMessage, new() {
|
||||
public static readonly MessageDescriptor value = new T().Descriptor;
|
||||
|
||||
public static class OneofImpl<TOneofCase> where TOneofCase : struct {
|
||||
static Dictionary<string, IReadOnlyDictionary<TOneofCase, (FieldDescriptor field_descriptor, Type field_type)>> _descriptor_case_indices =
|
||||
new Dictionary<string, IReadOnlyDictionary<TOneofCase, (FieldDescriptor field_descriptor, Type field_type)>>();
|
||||
|
||||
public static IReadOnlyDictionary<TOneofCase, (FieldDescriptor field_descriptor, Type field_type)> get_descriptor_case_index(string prop_name) {
|
||||
/// Use local copy because <see cref="_descriptor_case_indices"/> is updated atomically.
|
||||
var dci = _descriptor_case_indices;
|
||||
if (!dci.TryGetValue(prop_name, out IReadOnlyDictionary<TOneofCase, (FieldDescriptor field_descriptor, Type field_type)> rv)) {
|
||||
/// Update <see cref="_descriptor_case_indices"/> atomically (lock-free).
|
||||
/// 1) clone the local copy.
|
||||
/// 2) add the new KeyValue to the clone.
|
||||
/// 3) assign the clone back to <see cref="_descriptor_case_indices"/>.
|
||||
rv = get_oneof_descriptor_index<TOneofCase>(get_oneof_descriptor<T>(prop_name))
|
||||
.ToDictionary(kv => kv.Key, kv => (kv.Value, get_field_type(kv.Value)));
|
||||
dci = dci.ToDictionary();
|
||||
dci.Add(prop_name, rv);
|
||||
/// It is possible for add ops to be overwritten.
|
||||
/// This is perfectly safe, just means that the 'clone-add-assign' will be repeated the next time a caller requests this key.
|
||||
_descriptor_case_indices = dci;
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -213,7 +213,7 @@ namespace mbts.spark {
|
||||
// local methods
|
||||
void impl(StringBuilder sb, CustomOrderDefinition mdef) {
|
||||
sb.Append(abbreviate(mdef.CustomCase));
|
||||
foreach (var cad in OrderDataHelper.get_child_algo_data(def.CustomCase)) {
|
||||
foreach (var cad in OrderDataHelper.get_child_algo_data(def.CloneToMutable())) {
|
||||
var child = cad.get_child(mdef);
|
||||
sb.Append(".[");
|
||||
impl(sb, child);
|
||||
|
||||
@@ -17,12 +17,27 @@ using System.Reactive.Linq;
|
||||
using OrderState = bts.api.orderman.OrderState;
|
||||
|
||||
namespace mbts.spark.utilities {
|
||||
struct ChildAlgoData {
|
||||
public readonly string name;
|
||||
public readonly Func<IMessage, CustomOrderDefinition> get_child_from_impl;
|
||||
public readonly Action<IMessage, CustomOrderDefinition> assign_child_to_impl;
|
||||
public readonly Func<CustomOrderDefinition, CustomOrderDefinition> get_child;
|
||||
public readonly Action<CustomOrderDefinition, CustomOrderDefinition> assign_child;
|
||||
|
||||
public ChildAlgoData(string name, Func<IMessage, CustomOrderDefinition> get_child_from_impl, Action<IMessage, CustomOrderDefinition> assign_child_to_impl, Func<CustomOrderDefinition, CustomOrderDefinition> get_child, Action<CustomOrderDefinition, CustomOrderDefinition> assign_child) {
|
||||
this.name = name;
|
||||
this.get_child = get_child;
|
||||
this.assign_child = assign_child;
|
||||
this.get_child_from_impl = get_child_from_impl;
|
||||
this.assign_child_to_impl = assign_child_to_impl;
|
||||
}
|
||||
}
|
||||
|
||||
// at some point, user-default settings for orders can be managed here
|
||||
// OrdersModel imports and exposes OrderFactory as a public property
|
||||
[Export(typeof(OrderFactory))]
|
||||
class OrderFactory : IDisposable {
|
||||
static readonly OrderMetadata _default_order_metadata = new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.spreader_order };
|
||||
|
||||
static readonly OrderMetadata _default_order_metadata = new OrderMetadata { KeyBinding = "", Color = BTSColors.Orders.default_order };
|
||||
readonly AdminModel _admin_model;
|
||||
readonly DynamicOrderHelper _dynamic_helper;
|
||||
IDisposable _dispose;
|
||||
@@ -250,20 +265,6 @@ namespace mbts.spark.utilities {
|
||||
}
|
||||
}
|
||||
|
||||
public struct ChildAlgoData {
|
||||
public readonly Func<CustomOrderDefinition, CustomOrderDefinition> get_child;
|
||||
public readonly Action<CustomOrderDefinition, CustomOrderDefinition> set_child;
|
||||
public readonly string name;
|
||||
public readonly FieldDescriptor descriptor;
|
||||
|
||||
public ChildAlgoData(string name, FieldDescriptor descriptor, Func<CustomOrderDefinition, CustomOrderDefinition> get_child, Action<CustomOrderDefinition, CustomOrderDefinition> set_child) {
|
||||
this.name = name;
|
||||
this.get_child = get_child;
|
||||
this.set_child = set_child;
|
||||
this.descriptor = descriptor;
|
||||
}
|
||||
}
|
||||
|
||||
// algo-type-case maps
|
||||
// Note: obv this will break if we change the name of the 'CustomOneofCase' field
|
||||
static readonly OneofDescriptor _oneof_desc = CustomOrderDefinition.Descriptor.Oneofs.FirstOrDefault(fd => fd.Name == "custom");
|
||||
@@ -283,12 +284,17 @@ namespace mbts.spark.utilities {
|
||||
var value_descriptors = new List<FieldDescriptor>(0);
|
||||
foreach (var f in fd.MessageType.Fields.InDeclarationOrder()) {
|
||||
if (is_child_algo_field(f)) {
|
||||
child_algo_data.Add(new ChildAlgoData(f.Name, f,
|
||||
child_algo_data.Add(new ChildAlgoData(f.Name,
|
||||
msg => f.Accessor.GetValue(msg) as CustomOrderDefinition,
|
||||
(msg, child) => f.Accessor.SetValue(msg, child),
|
||||
def => {
|
||||
var type_def = fd.Accessor.GetValue(def) as IMessage;
|
||||
return f.Accessor.GetValue(type_def) as CustomOrderDefinition;
|
||||
},
|
||||
(def, child) => f.Accessor.SetValue(def, child)));
|
||||
(def, child) => {
|
||||
if (fd.Accessor.GetValue(def) is IMessage m)
|
||||
f.Accessor.SetValue(m, child);
|
||||
}));
|
||||
} else {
|
||||
value_descriptors.Add(f);
|
||||
}
|
||||
@@ -302,6 +308,30 @@ namespace mbts.spark.utilities {
|
||||
f.FieldType == FieldType.Message && f.MessageType.ClrType == typeof(CustomOrderDefinition);
|
||||
}
|
||||
|
||||
public static IReadOnlyList<ChildAlgoData> get_child_algo_data(CustomOrderDefinitionImmutable defi) =>
|
||||
get_child_algo_data(defi.CloneToMutable());
|
||||
|
||||
public static IReadOnlyList<ChildAlgoData> get_child_algo_data(CustomOrderDefinition algo) {
|
||||
switch (algo.CustomCase) {
|
||||
case CustomOrderDefinition.CustomOneofCase.Dynamic:
|
||||
return algo.Dynamic.OrderParams.Where(kv => kv.Value.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef).Select(kv => new ChildAlgoData(kv.Key, def => {
|
||||
var p = ((DynamicOrderDefinition)def).OrderParams[kv.Key];
|
||||
if (p.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef)
|
||||
return p.AsOrderDef;
|
||||
return null;
|
||||
},
|
||||
(msg, child) => {
|
||||
if (msg is DynamicOrderDefinition dyn)
|
||||
dyn.OrderParams.GetOrAdd(kv.Key, k => new DynamicOrderParam()).AsOrderDef = child;
|
||||
},
|
||||
def => def.Dynamic.OrderParams.TryGetValue(kv.Key, out DynamicOrderParam param) && param.ValueCase == DynamicOrderParam.ValueOneofCase.AsOrderDef ? param.AsOrderDef : null,
|
||||
(def, child) => def.Dynamic.OrderParams.GetOrAdd(kv.Key, k => new DynamicOrderParam()).AsOrderDef = child))
|
||||
.ToList();
|
||||
default:
|
||||
return get_child_algo_data(algo.CustomCase);
|
||||
}
|
||||
}
|
||||
|
||||
public static IReadOnlyList<ChildAlgoData> get_child_algo_data(CustomOrderDefinition.CustomOneofCase algo_type) =>
|
||||
_algo_type_case_descriptor_data.TryGetValue(algo_type, out AlgoTypeCaseDescriptorData d) ? d.child_algo_data : Array.Empty<ChildAlgoData>();
|
||||
|
||||
@@ -366,7 +396,7 @@ namespace mbts.spark.utilities {
|
||||
// hide mutable-def implementation
|
||||
IEnumerable<CustomOrderDefinition.CustomOneofCase> impl(CustomOrderDefinition mdef) {
|
||||
yield return mdef.CustomCase;
|
||||
foreach (var sd in get_child_algo_data(mdef.CustomCase)) {
|
||||
foreach (var sd in get_child_algo_data(mdef)) {
|
||||
var child = sd.get_child(mdef);
|
||||
if (child != null) {
|
||||
yield return child.CustomCase;
|
||||
@@ -412,7 +442,7 @@ namespace mbts.spark.utilities {
|
||||
if (child == null)
|
||||
return null;
|
||||
var type_def = (IMessage)desc_data.type_case_descriptor.Accessor.GetValue(def);
|
||||
cad.descriptor.Accessor.SetValue(type_def, child);
|
||||
cad.assign_child_to_impl(type_def, child);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -429,13 +459,11 @@ namespace mbts.spark.utilities {
|
||||
def = new CustomOrderDefinition { Limit = new LimitOrderDefinition() };
|
||||
break;
|
||||
default:
|
||||
var desc_data = _algo_type_case_descriptor_data[def.CustomCase];
|
||||
foreach (var cad in desc_data.child_algo_data) {
|
||||
foreach (var cad in get_child_algo_data(def)) {
|
||||
var child = outright_impl(cad.get_child(def));
|
||||
if (child == null)
|
||||
return null;
|
||||
var type_def = (IMessage)desc_data.type_case_descriptor.Accessor.GetValue(def);
|
||||
cad.descriptor.Accessor.SetValue(type_def, child);
|
||||
cad.assign_child(def, child);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -501,8 +529,8 @@ namespace mbts.spark.utilities {
|
||||
fd.Accessor.SetValue(tgt_type_def, fd.Accessor.GetValue(src_type_def));
|
||||
}
|
||||
foreach (var cad in desc_data.child_algo_data) {
|
||||
var src_child = cad.descriptor.Accessor.GetValue(src_type_def) as CustomOrderDefinition;
|
||||
var tgt_child = cad.descriptor.Accessor.GetValue(tgt_type_def) as CustomOrderDefinition;
|
||||
var src_child = cad.get_child_from_impl(src_type_def);
|
||||
var tgt_child = cad.get_child_from_impl(tgt_type_def);
|
||||
copy_values(src_child, ref tgt_child);
|
||||
}
|
||||
}
|
||||
@@ -558,7 +586,7 @@ namespace mbts.spark.utilities {
|
||||
public static bool structure_equals(CustomOrderDefinitionImmutable a, CustomOrderDefinitionImmutable b) {
|
||||
return impl(a.CloneToMutable(), b.CloneToMutable());
|
||||
bool impl(CustomOrderDefinition ma, CustomOrderDefinition mb) =>
|
||||
a.CustomCase == b.CustomCase && get_child_algo_data(a.CustomCase).All(cad => impl(cad.get_child(ma), cad.get_child(mb)));
|
||||
ma.CustomCase == mb.CustomCase && get_child_algo_data(ma).All(cad => impl(cad.get_child(ma), cad.get_child(mb)));
|
||||
}
|
||||
|
||||
public static bool iceberg_equals(IcebergOrderDefinitionImmutable a, IcebergOrderDefinitionImmutable b) =>
|
||||
@@ -895,4 +923,4 @@ namespace mbts.spark.utilities {
|
||||
public static SpreaderOrderDefinition SpreaderOrderDefinition() => new SpreaderOrderDefinition { ExecutionStrategy = new ExecutionStrategy() };
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,12 @@ namespace mbts {
|
||||
public static bool iequals(this string str, string comparand) =>
|
||||
string.Equals(str, comparand, StringComparison.CurrentCultureIgnoreCase);
|
||||
|
||||
public static string iremove_suffix(this string str, string suffix) {
|
||||
if (str.EndsWith(suffix, StringComparison.CurrentCultureIgnoreCase))
|
||||
str = str.Remove(str.Length - suffix.Length);
|
||||
return str;
|
||||
}
|
||||
|
||||
public static T choose<T>(this Random r, IEnumerable<T> range) {
|
||||
var index = r.Next(0, range.Count());
|
||||
return range.Skip(index).First();
|
||||
|
||||
Reference in new issue
Block a user