AlgoStudio - fix up AlgoDefinitionTemplateVM (used by the original AlgoStudio configuration)

This commit is contained in:
John Colvin committed 2019-02-06 14:59:11 -06:00
1 parent 186fce0eaf
commit f4e654b3e0
11 files changed
+386 -225

No files matched your search

@@ -28,21 +28,24 @@ namespace mbts.spark {
}
struct AlgoStructureKey : IEquatable<AlgoStructureKey> {
const int
_child_mask = 1 << 31,
_hedge_mask = 1 << 30;
readonly int[] _structure;
public AlgoStructureKey(CustomOrderDefinitionImmutable definition) {
int[] s = new[] { (int)definition.CustomCase };
int pos = 1;
_build(OrderDataHelper.get_child_order(definition), OrderDataHelper.get_hedge_order(definition), ref s, ref pos);
_build(definition, ref s, 1);
_structure = s;
}
public AlgoStructureKey(int[] structure) =>
_structure = structure;
public CustomOrderDefinitionImmutable build_def() {
int pos = 0;
var mdef = new CustomOrderDefinition();
_build_def(_structure, ref pos, ref mdef);
return new CustomOrderDefinitionImmutable(mdef);
}
public bool Equals(AlgoStructureKey other) =>
_structure.Length == other._structure.Length &&
_structure.SequenceEqual(other._structure);
@@ -56,18 +59,34 @@ namespace mbts.spark {
public static bool operator ==(AlgoStructureKey a, AlgoStructureKey b) => a.Equals(b);
public static bool operator !=(AlgoStructureKey a, AlgoStructureKey b) => !a.Equals(b);
static void _build(CustomOrderDefinitionImmutable? child, CustomOrderDefinitionImmutable? hedge, ref int[] structure, ref int pos) {
if (child.HasValue) {
ArrayHelper.ensure_capacity(ref structure, pos + 1);
structure[pos++] = (int)child.Value.CustomCase | _child_mask;
_build(OrderDataHelper.get_child_order(child.Value), OrderDataHelper.get_hedge_order(child.Value), ref structure, ref pos);
}
if (hedge.HasValue) {
ArrayHelper.ensure_capacity(ref structure, pos + 1);
structure[pos++] = -(int)hedge.Value.CustomCase | _hedge_mask;
_build(OrderDataHelper.get_child_order(hedge.Value), OrderDataHelper.get_hedge_order(hedge.Value), ref structure, ref pos);
static void _build(CustomOrderDefinitionImmutable definition, ref int[] structure, int pos) {
for (int di = 0; di < OrderDataHelper.inner_order_dels.Length; di++) {
(var get_order, var get_orderi, var assign) = OrderDataHelper.inner_order_dels[di];
var inner_order = get_orderi(definition);
if (inner_order.HasValue) {
ArrayHelper.ensure_capacity(ref structure, pos + 1);
int del_mask = 1 << (31 - di);
structure[pos++] = (int)inner_order.Value.CustomCase | del_mask;
_build(inner_order.Value, ref structure, pos);
break;
}
}
ArrayHelper.trim(ref structure, pos);
}
static void _build_def(int[] structure, ref int pos, ref CustomOrderDefinition definition) {
for (int i = pos; i < structure.Length; i++) {
for (int di = 0; di < OrderDataHelper.inner_order_dels.Length; di++) {
int mask = 1 << (31 - di);
if ((structure[i] & mask) == mask) {
var type = (CustomOrderDefinition.CustomOneofCase)(structure[i] ^ mask);
var order = OrderDataHelper.Defaults.CustomOrderDefinition(type);
pos++;
_build_def(structure, ref pos, ref order);
OrderDataHelper.inner_order_dels[di].assign(ref definition, order);
}
}
}
}
}
}
@@ -193,7 +193,7 @@
</ResourceDictionary>
</UserControl.Resources>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="NormalStates">
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.EditPane}}">
<VisualState Name="{x:Static u:VisualStates.Active}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="edit_pane" Storyboard.TargetProperty="(UIElement.Visibility)">
@@ -264,7 +264,19 @@
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type sp:AlgoDefinitionTemplateVM}">
<Grid Margin="-6,0,0,0">
<Grid u:StateManager.VisualStateCollection="{Binding tree_view_visual_states}" Margin="-6,0,0,0">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.FavoriteToggleButton}}">
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.FavoriteToggleButton}}"/>
<VisualState Name="{x:Static Inactive, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.FavoriteToggleButton}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="favorite_toggle" Storyboard.TargetProperty="(UIElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Collapsed}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
@@ -288,10 +300,6 @@
</DataTrigger.Binding>
<Setter TargetName="text_view" Property="Text" Value="{Binding name, StringFormat='{}{0}*'}"/>
</DataTrigger>
<DataTrigger Binding="{Binding is_default}" Value="{u:True}">
<Setter TargetName="text_view" Property="FontWeight" Value="{u:FontWeight Bold}"/>
<Setter TargetName="text_view" Property="ToolTip" Value="{x:Null}"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</TreeView.Resources>
@@ -348,7 +356,13 @@
</VisualStateGroup>
<!--Abbreviation-->
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}">
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}"/>
<VisualState Name="{x:Static Active, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_active_tooltip" Storyboard.TargetProperty="(FrameworkElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static Inactive, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_label" Storyboard.TargetProperty="(TextElement.Foreground)">
@@ -356,6 +370,22 @@
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="{x:Static NotSupportedForTemplates, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.Abbreviation}}">
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_root" Storyboard.TargetProperty="(ToolTipService.ShowOnDisabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_root" Storyboard.TargetProperty="(UIElement.IsEnabled)">
<DiscreteBooleanKeyFrame KeyTime="0" Value="False"/>
</BooleanAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_label" Storyboard.TargetProperty="(TextElement.Foreground)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:Brush Gray}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="abbreviation_not_supported_for_templates_tooltip" Storyboard.TargetProperty="(FrameworkElement.Visibility)">
<DiscreteObjectKeyFrame KeyTime="0" Value="{x:Static Visibility.Visible}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<!--Badge Selector-->
<VisualStateGroup Name="{x:Static GroupName, MemberType={u:Nested usp:AlgoStudioView.VisualStateNames.BadgeSelector}}">
@@ -391,15 +421,20 @@
Margin="{StaticResource Margin.LP1}"
Text="{Binding content_source.name, UpdateSourceTrigger=PropertyChanged, Delay=25}"
/>
<Grid Grid.Column="2">
<Grid x:Name="abbreviation_root" Grid.Column="2">
<Grid.ToolTip>
<TextBlock>
<TextBlock.Inlines>
<Run>Specify an abbreviation for this algo to use in ladder algo 'favorite' buttons.</Run>
<LineBreak/>
<Run FontStyle="Italic">Hint: To add/remove algos from 'favorites', open the ladder settings dialog and select the 'Algo Favorites' tab.</Run>
</TextBlock.Inlines>
</TextBlock>
<Grid>
<TextBlock x:Name="abbreviation_active_tooltip" Visibility="Collapsed">
<TextBlock.Inlines>
<Run>Specify an abbreviation for this algo to use in ladder algo 'favorite' buttons.</Run>
<LineBreak/>
<Run FontStyle="Italic">Hint: To add/remove algos from 'favorites', open the ladder settings dialog and select the 'Algo Favorites' tab.</Run>
</TextBlock.Inlines>
</TextBlock>
<TextBlock x:Name="abbreviation_not_supported_for_templates_tooltip" Visibility="Collapsed">
Not supported for templates.
</TextBlock>
</Grid>
</Grid.ToolTip>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
@@ -56,6 +56,14 @@ namespace mbts.ui.spark {
_controller.end_edit(e);
public static class VisualStateNames {
public static class EditPane {
public const string GroupName = nameof(EditPane);
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
}
public static class Name {
public const string GroupName = nameof(Name);
@@ -72,7 +80,8 @@ namespace mbts.ui.spark {
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
Inactive = $"{GroupName}{VisualStates.Inactive}",
NotSupportedForTemplates = $"{GroupName}{nameof(NotSupportedForTemplates)}";
}
public static class BadgeSelector {
@@ -90,6 +99,14 @@ namespace mbts.ui.spark {
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
}
public static class FavoriteToggleButton {
public const string GroupName = nameof(FavoriteToggleButton);
public static readonly string
Active = $"{GroupName}{VisualStates.Active}",
Inactive = $"{GroupName}{VisualStates.Inactive}";
}
}
}
}
@@ -4,9 +4,14 @@ using bts.utils;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reactive.Linq;
using System.Windows.Input;
using VisualStateNames = mbts.ui.spark.AlgoStudioView.VisualStateNames;
namespace mbts.spark {
class AlgoDefinitionTemplateVM : DisposableViewModelBase, IAlgoStudioContentVM, IEquatable<AlgoDefinitionTemplateVM> {
@@ -16,107 +21,125 @@ namespace mbts.spark {
/// After spending ~15 minutes investigating what was happening, [John]I decided it was more trouble than it was worth and opted for this workaround.
public static readonly Type CustomType = typeof(CustomTemplatePlaceholderVM);
readonly OrdersModel _model;
readonly VisualStateModel _edit_pane_vs_model = new VisualStateModel(), _tree_view_vs_model = new VisualStateModel();
/// Note: the difference between <see cref="EditStack{T}"/> and <see cref="VersionContainer{T}"/> is that the former implements push/pop functionality so the user may undo/redo (like ctrl+z/ctrl+y in text editors),
/// while the latter is a lazy delegate-based container for the most recent value (<see cref="VersionContainer{T}.increment_version"/>).
readonly EditStack<Snapshot> _edit_stack = new EditStack<Snapshot>();
readonly VersionContainer<Snapshot> _version;
readonly DeferrableActionWrapper _change_logger;
readonly DeferrableActionWrapper _refresh_on_local_change;
readonly Property<IOrderTypeVM> _algo_root;
readonly DelegateProperty<bool> _can_undo, _can_redo, _is_dirty;
readonly Property<bool> _is_default, _is_favorite, _is_selected;
readonly Property<string> _abbreviation;
readonly Property<string> _name, _abbreviation;
// maintains the state of each algo-root, so the user may change the definition root back and forth without any loss of state amongst the templates
Snapshot _committed;
string _name;
public AlgoDefinitionTemplateVM(AlgoDefinitionVM owner, OrdersModel model, AlgoTemplateData template)
: this(owner, model, template.value, template.name, template.key) { }
public AlgoDefinitionTemplateVM(AlgoDefinitionVM owner, OrdersModel model, CustomOrderDefinitionImmutable definition, string name, AlgoPersistedKey? id = null, OrderTypeEditingPermissions editing_permissions = OrderTypeEditingPermissions.AllowEditValues) {
// init core data
this.owner = owner;
_model = model;
vm_key = id.HasValue ? new AlgoVMKey(id.Value) : new AlgoVMKey(Guid.NewGuid());
_name = name;
_abbreviation = backing(nameof(abbreviation), name);
_version = new VersionContainer<Snapshot>(_snapshot);
// maintain states for different algo roots, so they aren't lost when the user changes the root algo type
var algo_map = new Dictionary<CustomOrderDefinition.CustomOneofCase, IOrderTypeVM> {
{ definition.CustomCase, algo_vm_factory(definition) }
};
// init backing props
_name = backing(nameof(this.name), name);
_abbreviation = backing(nameof(abbreviation), string.Empty);
_is_default = backing(nameof(is_default), false);
_is_favorite = backing(nameof(is_favorite), false);
algo_root = OrderTypeVMFactory.create(_model, owner.security_md_source, definition.CustomCase, editing_permissions: editing_permissions);
algo_root.load_from(definition);
algo_root.editable_properties_open = algo_root.has_editable_properties;
_change_logger = new DeferrableActionWrapper(on_definition_changed);
_version = new VersionContainer<Snapshot>(() => new Snapshot(this));
_committed = new Snapshot(name, definition, vm_key.persisted_id);
_is_dirty = backing(nameof(is_dirty), () => !_committed.Equals(_version.value));
_is_selected = backing(nameof(is_selected), false);
if (vm_key.mode == AlgoVMKey.Mode.Persisted)
_edit_stack.push(_committed);
_algo_root = backing(nameof(algo_root), get_algo_root(owner.algo_root));
_committed = _version.value;
_can_redo = backing(nameof(can_redo), () => _edit_stack.get_can_redo(_version.value));
_can_undo = backing(nameof(can_undo), () => _edit_stack.get_can_undo(_version.value));
_is_dirty = backing(nameof(is_dirty), () => !_committed.Equals(_version.value));
_can_redo.Changed += on_can_redo_changed;
_can_undo.Changed += on_can_undo_changed;
set_as_default_cmd = new DelegateCommand(() => {
// don't call the model if it is already the default - as of 1/21/2019, it's an async call, is not idemptotent, and pumps an observable notification to every ladder/algostudio window.
if (!is_default && vm_key.mode == AlgoVMKey.Mode.Persisted)
_model.algo_model.metadata_service.set_as_default(owner.vm_key.persisted_id, vm_key.persisted_id).ignore();
});
algo_root.definition_changed += _change_logger.execute;
_can_redo.Changed += on_can_redo_changed;
_can_undo.Changed += on_can_undo_changed;
_dispose = Disposable.Create(() => {
algo_root.definition_changed -= _change_logger.execute;
_can_redo.Changed -= on_can_redo_changed;
_can_undo.Changed -= on_can_undo_changed;
});
// init visual states
// TODO: implement these features in IAlgoMetadataService; until then, set the appropriate visual states.
_edit_pane_vs_model.set_state(VisualStateNames.Abbreviation.GroupName, VisualStateNames.Abbreviation.NotSupportedForTemplates);
_tree_view_vs_model.set_state(VisualStateNames.FavoriteToggleButton.GroupName, VisualStateNames.FavoriteToggleButton.Inactive);
switch (vm_key.mode) {
case AlgoVMKey.Mode.Persisted:
_edit_stack.push(_committed);
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Active);
break;
case AlgoVMKey.Mode.Unpersisted: _edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Active); break;
case AlgoVMKey.Mode.LegacyFlex: _edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Inactive); break;
}
// set hooks/subscriptions
_refresh_on_local_change = new DeferrableActionWrapper(on_local_changed);
_dispose = new System.Reactive.Disposables.CompositeDisposable(
as_demuxer().subscribe_many(_refresh_on_local_change.execute, nameof(name), nameof(abbreviation), nameof(is_default), nameof(is_favorite)),
owner.observe_algo_root().Subscribe(r => _algo_root.set(get_algo_root(r))),
_algo_root.observe_current(true).SelectManyInSeries(r => r?.subscribe_definition()).RefCount().Subscribe(_ => _refresh_on_local_change.execute()),
Disposable.wrap_collection(algo_map.Values)) {
() => {
_can_redo.Changed -= on_can_redo_changed;
_can_undo.Changed -= on_can_undo_changed;
}
};
// local methods
IOrderTypeVM algo_vm_factory(CustomOrderDefinitionImmutable def) => OrderTypeVMFactory.create(_model, Observable.Return<SecurityMD?>(null), new NamedCustomOrderDefinition(def), editing_permissions);
IOrderTypeVM get_algo_root(IOrderTypeVM owner_root) {
if (algo_map.TryGetValue(owner_root.order_type, out IOrderTypeVM vm)) {
vm.load_structure(owner_root.definition);
} else {
vm = algo_map.GetOrAdd(owner_root.order_type, ot => algo_vm_factory(owner_root.definition));
}
return vm;
}
void on_can_undo_changed(bool oldval, bool newval) => can_undo_changed?.Invoke();
void on_can_redo_changed(bool oldval, bool newval) => can_redo_changed?.Invoke();
void on_definition_changed() {
void on_local_changed() {
_version.increment_version();
_edit_stack.push_distinct(_version.value);
_can_redo.refresh();
_can_undo.refresh();
_is_dirty.refresh();
_refresh_undo_redo();
}
}
public event Action can_redo_changed, can_undo_changed;
public event PropertyChange<IOrderTypeVM> algo_root_changed;
public event PropertyChange<IOrderTypeVM> algo_root_changed { add => _algo_root.Changed += value; remove => _algo_root.Changed -= value; }
public AlgoDefinitionVM owner { get; }
public AlgoVMKey owner_vm_key => owner.vm_key;
public AlgoVMKey vm_key { get; }
public string name {
get => _name;
set {
if (Set(ref _name, value)) {
_change_logger.execute();
}
}
}
public string name { get => _name.Value; set => _name.set(value); }
public string abbreviation { get => _abbreviation.Value; set => _abbreviation.set(value); }
public bool can_edit_name {
get {
switch (vm_key.mode) {
case AlgoVMKey.Mode.Unpersisted: return true;
default: return false;
}
}
}
public bool is_dirty => _is_dirty.Value;
public bool can_redo => _can_redo.Value;
public bool can_undo => _can_undo.Value;
public bool is_default => _is_default.Value;
public bool is_favorite {
get => _is_favorite.Value;
set {
if (_is_favorite.set_new(value) && vm_key.mode == AlgoVMKey.Mode.Persisted) {
if (value) _model.algo_model.metadata_service.add_to_favorites(owner.vm_key.persisted_id, vm_key.persisted_id).ignore();
else _model.algo_model.metadata_service.remove_from_favorites(owner.vm_key.persisted_id, vm_key.persisted_id).ignore();
}
}
}
public IOrderTypeVM algo_root { get; }
public bool is_favorite { get => _is_favorite.Value; set => _is_favorite.set(value); }
public IOrderTypeVM algo_root => _algo_root.Value;
public virtual bool is_custom_placeholder => false;
public bool is_selected { get => _is_selected.Value; set => _is_selected.set(value); }
public bool is_expanded => false;
public bool is_persisted => vm_key.mode == AlgoVMKey.Mode.Persisted;
public ObservableCollection<string> edit_pane_visual_states => _edit_pane_vs_model.states;
public ObservableCollection<string> tree_view_visual_states => _tree_view_vs_model.states;
public ICommand set_as_default_cmd { get; }
public IObservable<bool> observe_is_dirty() => _is_dirty.observe_current(true);
public void undo() => _restore(_edit_stack.try_undo);
public void redo() => _restore(_edit_stack.try_redo);
public void on_meta(bool is_default, bool is_favorite) {
_is_default.set(is_default);
_is_favorite.set(is_favorite);
}
public AlgoTemplateData create() =>
create(owner.create_algo_def());
@@ -127,82 +150,69 @@ namespace mbts.spark {
return new AlgoTemplateData(algo_root.createi(), name, vm_key.persisted_id, record);
}
public void undo() => _restore(_edit_stack.try_undo);
public void redo() => _restore(_edit_stack.try_redo);
public void load_committed() => _load_from(_committed.name, _committed.definition);
public AlgoDefinitionTemplateVM to_persisted(AlgoDefinitionVM persisted_owner, AlgoTemplateData template) =>
new AlgoDefinitionTemplateVM(persisted_owner, _model, template);
public void load_committed() => _load_from(_committed.name, _committed.definition, true);
public void load_from(AlgoTemplateData value) {
if (vm_key.mode != AlgoVMKey.Mode.Persisted)
throw new InvalidOperationException("AlgoStructure has not been saved yet.");
else if (value.key != vm_key.persisted_id)
throw new InvalidOperationException("Value id does not match this id.");
_load_from(value.name, value.value);
_load_from(value.name, value.value, true);
}
public void on_meta(bool is_default, bool is_favorite) {
_is_default.set(is_default);
_is_favorite.set(is_favorite);
}
public IObservable<bool> observe_is_dirty() => _is_dirty.observe_current(true);
public AlgoDefinitionTemplateVM to_persisted(AlgoDefinitionVM persisted_owner, AlgoTemplateData template) =>
new AlgoDefinitionTemplateVM(persisted_owner, _model, template);
public bool Equals(AlgoDefinitionTemplateVM other) => other != null && vm_key == other.vm_key;
public override bool Equals(object obj) => Equals(obj as AlgoDefinitionTemplateVM);
public override int GetHashCode() => vm_key.GetHashCode();
void _load_from(string new_name, CustomOrderDefinitionImmutable new_def) {
using (_change_logger.defer_execution()) {
void _load_from(string new_name, CustomOrderDefinitionImmutable new_def, bool update_committed) {
using (_refresh_on_local_change.defer_execution()) {
name = new_name;
algo_root.load_from(new_def);
}
_version.increment_version();
_committed = _version.value;
_is_dirty.refresh();
if (update_committed) {
_committed = _version.value;
_is_dirty.refresh();
}
}
void _raise_algo_root_changed(IOrderTypeVM oldval, IOrderTypeVM newval) =>
algo_root_changed?.Invoke(oldval, newval);
void _restore(TryGetValue<Snapshot> try_get_snapshot) {
while (try_get_snapshot(out Snapshot next_state)) {
if (!_version.value.Equals(next_state)) {
_restore(next_state);
break;
}
}
void _refresh_undo_redo() {
_can_redo.refresh();
_can_undo.refresh();
}
void _restore(Snapshot state) {
using (_change_logger.supress_execution()) {
name = state.name;
algo_root.load_from(state.definition);
void _restore(TryGetValue<Snapshot> try_get_snapshot) {
while (try_get_snapshot(out Snapshot next_state)) {
if (!_version.value.Equals(next_state)) {
_load_from(next_state.name, next_state.definition, false);
break;
}
}
_version.increment_version();
_is_dirty.refresh();
}
Snapshot _snapshot() =>
new Snapshot(name, abbreviation, algo_root?.createi() ?? new CustomOrderDefinitionImmutable(new CustomOrderDefinition()), is_default, is_favorite);
struct Snapshot : IEquatable<Snapshot> {
public readonly string name;
public readonly AlgoPersistedKey id;
public readonly string name, abbreviation;
public readonly CustomOrderDefinitionImmutable definition;
public readonly bool is_default, is_favorite;
public Snapshot(AlgoDefinitionTemplateVM owner)
: this(owner.name, owner.algo_root.createi(), owner.vm_key.persisted_id) { }
public Snapshot(string name, CustomOrderDefinitionImmutable definition, AlgoPersistedKey id) {
public Snapshot(string name, string abbreviation, CustomOrderDefinitionImmutable definition, bool is_default, bool is_favorite) {
this.name = name;
this.id = id;
this.abbreviation = abbreviation;
this.definition = definition;
this.is_default = is_default;
this.is_favorite = is_favorite;
}
public bool Equals(Snapshot other) =>
id == other.id &&
name == other.name &&
abbreviation == other.abbreviation &&
is_default == other.is_default &&
is_favorite == other.is_favorite &&
OrderDataHelper.EqualsHelpers.equals(definition, other.definition);
public override bool Equals(object obj) =>
@@ -210,8 +220,10 @@ namespace mbts.spark {
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
id.GetHashCode(),
EqualityComparer.safe_aggregate_hash(name),
EqualityComparer.safe_aggregate_hash(abbreviation),
is_default.GetHashCode(),
is_favorite.GetHashCode(),
OrderDataHelper.EqualsHelpers.custom_order_def_compareri.GetHashCode(definition));
public static bool operator ==(Snapshot a, Snapshot b) => a.Equals(b);
@@ -223,7 +235,7 @@ namespace mbts.spark {
public CustomTemplatePlaceholderVM(AlgoDefinitionVM owner, OrdersModel model, IObservable<SecurityMD?> security_md_source, CustomOrderDefinitionImmutable definition)
: base(owner, model, definition, _custom_name, null, OrderTypeEditingPermissions.AllowEditStructure | OrderTypeEditingPermissions.AllowEditValues) {
_edit_stack.reset(new Snapshot(this));
_edit_stack.reset(_snapshot());
}
public override bool is_custom_placeholder => true;
@@ -26,6 +26,7 @@ namespace mbts.spark {
public const string new_algo_name = "New Algo";
public static readonly CustomOrderDefinitionImmutable new_algo_def = OrderDataHelper.Defaults.CustomOrderDefinitionImmutable(CustomOrderDefinition.CustomOneofCase.Iceberg);
readonly OrdersModel _model;
readonly VisualStateModel _edit_pane_vs_model = new VisualStateModel(), _tree_view_vs_model = new VisualStateModel();
readonly ObservableKeyedCollection<AlgoDefinitionTemplateVM, AlgoVMKey> _templates = new ObservableKeyedCollection<AlgoDefinitionTemplateVM, AlgoVMKey>(t => t.vm_key);
readonly EditStack<Snapshot> _edit_stack = new EditStack<Snapshot>();
readonly VersionContainer<Snapshot> _version;
@@ -33,14 +34,13 @@ namespace mbts.spark {
readonly Property<IOrderTypeVM> _algo_root, _visible_algo_root;
readonly Property<AlgoDefinitionTemplateVM> _selected_template;
readonly DelegateProperty<bool> _is_favorite, _is_dirty, _can_undo, _can_redo;
readonly Property<string> _abbreviation;
readonly Property<string> _name, _abbreviation;
readonly ObservableKeyedCollection<IOrderTypeVM, string> _algo_roots = new ObservableKeyedCollection<IOrderTypeVM, string>(vm => vm.id);
readonly ObservableAppendCollection<AlgoDefinitionTemplateVM> _templates_with_custom;
readonly DeferrableActionWrapper _refresh_on_local_changes;
readonly ReactiveThresholdMonitor<AlgoDefinitionTemplateVM> _any_templates_dirty_monitor = new ReactiveThresholdMonitor<AlgoDefinitionTemplateVM>(t => t.observe_is_dirty());
OrderTypeEditingPermissions _editing_permissions;
int? _favorite_index;
string _name;
Brush _badge_fill;
Snapshot? _committed;
AlgoDefinitionMetadata _metadata;
@@ -61,57 +61,53 @@ namespace mbts.spark {
new AlgoDefinitionVM(model, new AlgoVMKey(Guid.NewGuid()), new NamedCustomOrderDefinition(def), security_md_source, name);
AlgoDefinitionVM(OrdersModel model, AlgoVMKey vm_key, NamedCustomOrderDefinition init_algo_root, IObservable<SecurityMD?> security_md_source, string name) {
// init core data
_model = model;
this.vm_key = vm_key;
this.security_md_source = security_md_source ?? Observable.Return<SecurityMD?>(null);
_name = name;
_editing_permissions = _get_permissions();
_version = new VersionContainer<Snapshot>(_snapshot);
custom_badge_color_palettes.AddRange(ColorPalette.all_presets(model.factory).Select(p => new ColorPaletteVM(p)));
_abbreviation = backing(nameof(abbreviation), string.Empty);
_template_update_buffer = new TableUpdateBuffer<AlgoTemplateData, AlgoPersistedKey>(t => t.key);
_algo_root = backing(nameof(algo_root), _algo_roots.GetOrAdd(init_algo_root.id, _ => OrderTypeVMFactory.create(_model, this.security_md_source, init_algo_root, _editing_permissions)));
algo_root.load_from(init_algo_root.definition);
_templates_with_custom = new ObservableAppendCollection<AlgoDefinitionTemplateVM>(templates);
templates_view = (ListCollectionView)CollectionViewSource.GetDefaultView(_templates_with_custom);
custom_badge_color_palettes.AddRange(ColorPalette.all_presets(model.factory).Select(p => new ColorPaletteVM(p)));
_editing_permissions = _get_permissions();
_version = new VersionContainer<Snapshot>(_snapshot);
var resources = new CompositeDisposable();
// init backing props
_name = backing(nameof(this.name), name);
_abbreviation = backing(nameof(abbreviation), string.Empty);
_selected_template = backing<AlgoDefinitionTemplateVM>(nameof(selected_template));
_is_favorite = backing(nameof(is_favorite), () => _favorite_index.HasValue);
_is_expanded = backing(nameof(is_expanded), true);
_is_selected = backing(nameof(is_selected), true);
_is_dirty = backing(nameof(is_dirty), () => vm_key.mode != AlgoVMKey.Mode.Persisted || !_committed.HasValue || !_committed.Value.Equals(_version.value));
_algo_root = backing(nameof(algo_root), _algo_roots.GetOrAdd(init_algo_root.id, _ => OrderTypeVMFactory.create(_model, this.security_md_source, init_algo_root, _editing_permissions)));
_visible_algo_root = backing<IOrderTypeVM>(nameof(visible_algo_root));
_can_redo = backing(nameof(can_redo), () => _edit_stack.get_can_redo(_version.value));
_can_undo = backing(nameof(can_undo), () => _edit_stack.get_can_undo(_version.value));
_can_redo.Changed += on_can_redo_changed;
_can_undo.Changed += on_can_undo_changed;
// load initial state
algo_root.load_from(init_algo_root.definition);
_committed = _version.value;
// 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)
_visible_algo_root = backing<IOrderTypeVM>(nameof(visible_algo_root));
var resources = new CompositeDisposable();
if (_model.algo_model.templates_enabled()) {
resources.Add(_selected_template.observe_current(true).Subscribe(t => _visible_algo_root.set(t?.algo_root)));
} else {
resources.Add(_algo_root.observe_current(true).Subscribe(_visible_algo_root.set));
}
resources.Add(templates.ObserveSelf().Subscribe(_ => RaisePropertyChanged(nameof(can_edit_structure))));
_committed = _version.value;
_refresh_on_local_changes = new DeferrableActionWrapper(() => {
_version.increment_version();
if (algo_root != null)
_edit_stack.push_distinct(_version.value);
_is_dirty.refresh();
_refresh_undo_redo();
});
_is_favorite = backing(nameof(is_favorite), () => _favorite_index.HasValue);
_is_expanded = backing(nameof(is_expanded), true);
_is_selected = backing(nameof(is_selected), true);
_is_dirty = backing(nameof(is_dirty), () => vm_key.mode != AlgoVMKey.Mode.Persisted || !_committed.HasValue || !_committed.Value.Equals(_version.value));
_can_redo = backing(nameof(can_redo), () => _edit_stack.get_can_redo(_version.value));
_can_undo = backing(nameof(can_undo), () => _edit_stack.get_can_undo(_version.value));
_can_redo.Changed += on_can_redo_changed;
_can_undo.Changed += on_can_undo_changed;
tree_view_visual_states = new ObservableCollection<string> {
_model.algo_model.ui_configuration.show_badges_in_tree_view ? VisualStateNames.TreeViewBadge.Active : VisualStateNames.TreeViewBadge.Inactive
};
var vsm = new VisualStateModel();
visual_states = vsm.states;
// init tree view item visual state
_tree_view_vs_model.set_state(
VisualStateNames.TreeViewBadge.GroupName,
_model.algo_model.ui_configuration.show_badges_in_tree_view ? VisualStateNames.TreeViewBadge.Active : VisualStateNames.TreeViewBadge.Inactive);
// set hooks/subscriptions
_refresh_on_local_changes = new DeferrableActionWrapper(on_local_changed);
using (_refresh_on_local_changes.defer_execution()) {
resources.AddRange(
custom_badge_color.observe_nullable(true).Subscribe(v => Set(ref _badge_fill, (v ?? algo_root.safe_get_badge_color()).to_brush(), nameof(badge_fill))),
as_demuxer().subscribe_many(_refresh_on_local_changes.execute, nameof(name), nameof(abbreviation), nameof(badge_fill)),
vsm.add_source(VisualStateNames.BadgeSelector.GroupName, custom_badge_color.observe_nullable(true).Select(t => t.HasValue ? VisualStateNames.BadgeSelector.Active : VisualStateNames.BadgeSelector.Inactive)),
vsm.add_source(VisualStateNames.Abbreviation.GroupName, _abbreviation.observe_current(true).Select(a => string.IsNullOrEmpty(a) ? VisualStateNames.Abbreviation.Active : VisualStateNames.Abbreviation.Inactive)),
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.Active : VisualStateNames.Abbreviation.Inactive)),
templates.ObserveSelf().Select(_ => _get_permissions()).DistinctUntilChanged().OnDispatcher().Subscribe(on_editing_permissions),
_algo_root.observe_current(true).SubscribeHookLatest(ot => ot == null ? Disposable.empty : ot.subscribe_definition().Subscribe(d => _refresh_on_local_changes.execute())),
Disposable.wrap_collection(algo_roots),
@@ -126,14 +122,14 @@ namespace mbts.spark {
_metadata = new AlgoDefinitionMetadata(vm_key.persisted_id);
resources.Add(_template_update_buffer.OnDispatcher().Subscribe(_on_templates));
resources.Add(model.algo_model.metadata_service.subscribe_metadata(vm_key.persisted_id).OnDispatcher().Subscribe(_on_metadata));
vsm.set_state(VisualStateNames.Name.GroupName, _model.algo_model.ui_configuration.can_modify_definition_name ?
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, _model.algo_model.ui_configuration.can_modify_definition_name ?
VisualStateNames.Name.Active : VisualStateNames.Name.CannotRenameDefinition);
break;
case AlgoVMKey.Mode.LegacyFlex:
resources.Add(security_md_source.Subscribe(smd =>
_algo_roots.SyncWithDictionary(_model.factory.default_order_type_templates(smd.security()),
nd => OrderTypeVMFactory.create(_model, security_md_source, nd, _editing_permissions, true))));
vsm.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Inactive);
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Inactive);
_version.increment_version();
_committed = _version.value;
_edit_stack.reset(_committed.Value);
@@ -146,7 +142,7 @@ namespace mbts.spark {
if (!_algo_roots.ContainsKey(nd.id))
_algo_roots.Add(nd.id, OrderTypeVMFactory.create(_model, this.security_md_source, nd, _editing_permissions));
}
vsm.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Active);
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Active);
break;
}
_dispose = resources;
@@ -160,26 +156,24 @@ namespace mbts.spark {
}
void on_can_redo_changed(bool oldval, bool newval) => can_redo_changed?.Invoke();
void on_can_undo_changed(bool oldval, bool newval) => can_undo_changed?.Invoke();
void on_local_changed() {
_version.increment_version();
if (algo_root != null)
_edit_stack.push_distinct(_version.value);
_is_dirty.refresh();
_refresh_undo_redo();
}
}
public event Action can_redo_changed, can_undo_changed;
public event PropertyChange<IOrderTypeVM> algo_root_changed { add => _algo_root.Changed += value; remove => _algo_root.Changed -= value; }
public AlgoVMKey vm_key { get; }
public string name { get => _name; set => Set(ref _name, value); }
public string name { get => _name.Value; set => _name.set(value); }
public string abbreviation { get => _abbreviation.Value; set => _abbreviation.set(value); }
public ObservableCollection<IOrderTypeVM> algo_roots => _algo_roots;
public IOrderTypeVM algo_root { get => _algo_root.Value; set => _algo_root.set(value); }
public IOrderTypeVM visible_algo_root => _visible_algo_root.Value;
public AlgoDefinitionTemplateVM selected_template { get => _selected_template.Value; set => _selected_template.set(value); }
public bool can_edit_structure {
get {
switch (vm_key.mode) {
case AlgoVMKey.Mode.Unpersisted: return templates.Count == 0 || _model.algo_model.ui_configuration.can_modify_definition_structure;
case AlgoVMKey.Mode.Persisted: return _model.algo_model.ui_configuration.can_modify_definition_structure;
default: return true;
}
}
}
public int? favorite_index {
get => _favorite_index;
set {
@@ -208,8 +202,8 @@ namespace mbts.spark {
public ObservableAppendCollection<AlgoDefinitionTemplateVM> templates_with_custom => _templates_with_custom;
public ListCollectionView templates_view { get; }
public IObservable<SecurityMD?> security_md_source { get; }
public ObservableCollection<string> visual_states { get; }
public ObservableCollection<string> tree_view_visual_states { get; }
public ObservableCollection<string> edit_pane_visual_states => _edit_pane_vs_model.states;
public ObservableCollection<string> tree_view_visual_states => _tree_view_vs_model.states;
// idempotent
public void prepend_custom_template() {
@@ -27,6 +27,16 @@ namespace mbts.spark {
void load_committed();
}
static class AlgoStudioContentVMExtensions {
public static IObservable<IOrderTypeVM> observe_algo_root(this IAlgoStudioContentVM vm) =>
Observable.Create<IOrderTypeVM>(o => {
o.OnNext(vm.algo_root);
vm.algo_root_changed += on_algo_root_changed;
return Disposable.Create(() => vm.algo_root_changed -= on_algo_root_changed);
void on_algo_root_changed(IOrderTypeVM oldval, IOrderTypeVM newval) => o.OnNext(newval);
});
}
class AlgoStudioVM : DisposableViewModelBase, IHandleSelectedItemChanged {
readonly OrdersModel _model;
readonly Property<AlgoDefinitionVM> _selected_definition;
@@ -43,7 +53,7 @@ namespace mbts.spark {
_model = model;
_selected_definition = backing<AlgoDefinitionVM>(nameof(selected_definition));
_selected_template = backing<AlgoDefinitionTemplateVM>(nameof(selected_template));
_editable_content = backing<IOrderTypeVM>(nameof(editable_content));
_editable_content = backing(nameof(editable_content), observe_selected().SelectManyInSeries(tup => tup.template?.observe_algo_root() ?? tup.definition?.observe_algo_root()).RefCount().OnDispatcher());
_definitions_update_buffer = new TableUpdateBuffer<AlgoDefinitionData, AlgoPersistedKey>(def => def.key);
_definitions_view = new ListCollectionView<AlgoDefinitionVM>(definitions) {
CustomSort = AlgoDefinitionVMCollectionHelper.default_comparer.to_non_generic()
@@ -65,7 +75,7 @@ namespace mbts.spark {
_persisted_meta = meta;
definitions_view.Refresh();
}),
ObservableAutoWrapper.connect(observe_selected().Select(t => t.definition != null && t.template == null ? t.definition.visual_states : new ObservableCollection<string>()), content_visual_states),
ObservableAutoWrapper.connect(observe_selected().Select(t => t.template?.edit_pane_visual_states ?? t.definition?.edit_pane_visual_states ?? new ObservableCollection<string>()), content_visual_states),
observe_selected().SelectManyInSeries(t => t.template?.observe_is_dirty() ?? t.definition?.subscribe_is_definition_or_any_templates_dirty() ?? Observable.Return(false)).RefCount().OnDispatcher()
.Subscribe(new CompositeObserver<bool>(save_cmd, revert_cmd) { val => {
_save_cmd_tooltip.refresh();
@@ -221,27 +231,18 @@ namespace mbts.spark {
/// This behavior wasn't just quirky either, it actually conflicted with the double-click-to-set-template-as-default behavior.
/// (for details, <see cref="mbts.ui.spark.AlgoStudioView.EnableToggleDefaultOnDoubleClickProperty"/>)
void IHandleSelectedItemChanged.on_selected_item_changed(object old_value, object new_value) {
if (old_value is AlgoDefinitionVM old_def)
old_def.algo_root_changed -= _on_selected_definition_root_changed;
if (new_value is AlgoDefinitionVM def) {
selected_definition = def;
_editable_content.set(def.algo_root);
def.algo_root_changed += _on_selected_definition_root_changed;
selected_template = null;
} else if (new_value is AlgoDefinitionTemplateVM templ) {
selected_definition = templ.owner;
selected_template = templ;
_editable_content.set(templ.algo_root);
} else {
selected_definition = null;
selected_template = null;
_editable_content.set(null);
}
_selected_changed?.Invoke((selected_definition, selected_template));
RaisePropertyChanged(nameof(content_source));
}
void _on_selected_definition_root_changed(IOrderTypeVM oldval, IOrderTypeVM newval) =>
_editable_content.set(selected_definition?.algo_root);
}
}
@@ -332,8 +332,13 @@ namespace mbts.spark {
public void on_favorite_algos(LadderFavoriteAlgosSettings value) {
_favorite_algos_index = value.favorite_algos.Select((v, i) => (v, i)).ToDictionaryCrushed(t => t.v, t => t.i);
foreach (var d in algo_definitions)
foreach (var d in algo_definitions) {
d.favorite_index = _get_favorite_algo_index(d.vm_key);
foreach (var t in d.templates) {
if (t.vm_key.mode == AlgoVMKey.Mode.Persisted)
t.is_favorite = _favorite_algos_index.ContainsKey(t.vm_key.persisted_id);
}
}
favorite_algos_column_count = value.column_count;
}
@@ -43,6 +43,13 @@ namespace mbts.spark {
public static CustomOrderDefinitionImmutable createi(this IOrderTypeVM vm) =>
new CustomOrderDefinitionImmutable(vm.create());
public static void load_structure(this IOrderTypeVM vm, CustomOrderDefinitionImmutable def) {
var mdef = def.CloneToMutable();
// assign values from vm.definition to mdef (values will be assigned at each common structure-level, e.g. Iceberg->Iceberg->Limit and Iceberg->Iceberg->Lean have 2 common structure-levels)
OrderDataHelper.assign_values_to(vm.definition, ref mdef);
vm.load_from(new CustomOrderDefinitionImmutable(mdef));
}
public static IObservable<CustomOrderDefinitionImmutable> subscribe_definition(this IOrderTypeVM vm) =>
Observable.Create<CustomOrderDefinitionImmutable>(o => {
o.OnNext(vm.definition);
@@ -105,7 +105,6 @@
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="{Binding SelectedItem, RelativeSource={RelativeSource Self}, Converter={StaticResource OrderTypeBrushConverter}}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="CanEditValues" Value="{Binding can_edit_values, FallbackValue={u:True}}"/>
<Setter Property="CanEditStructure" Value="{Binding can_edit_structure, FallbackValue={u:True}}"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
@@ -125,16 +125,6 @@ namespace mbts.ui.spark.algo {
}
#endregion
#region CanEditValues
public static readonly DependencyProperty CanEditValuesProperty =
WPFHelper.create_dp<bool, AlgoPickerNodeView>(nameof(CanEditValues));
public bool CanEditValues {
get => (bool)GetValue(CanEditValuesProperty);
set => SetValue(CanEditValuesProperty, value);
}
#endregion
#region CanEditStructure
public static readonly DependencyProperty CanEditStructureProperty =
WPFHelper.create_dp<bool, AlgoPickerNodeView>(nameof(CanEditStructure));
@@ -241,6 +241,13 @@ namespace mbts.spark.utilities {
}
static class OrderDataHelper {
public delegate void AssignInnerDef(ref CustomOrderDefinition def, CustomOrderDefinition inner_def);
public static readonly (Func<CustomOrderDefinition, CustomOrderDefinition> get_def, Func<CustomOrderDefinitionImmutable, CustomOrderDefinitionImmutable?> get_defi, AssignInnerDef assign)[] inner_order_dels =
new (Func<CustomOrderDefinition, CustomOrderDefinition> get_def, Func<CustomOrderDefinitionImmutable, CustomOrderDefinitionImmutable?> get_defi, AssignInnerDef assign)[] {
(get_child_order, get_child_order, assign_child),
(get_hedge_order, get_hedge_order, assign_hedge)
};
public static class CompareUtils {
public static readonly IEqualityComparer<OrderRecordImmutable> order_record_id_eq_comparer =
EqualityComparer.Create<OrderRecordImmutable, uint>(o => o.Key);
@@ -300,6 +307,59 @@ namespace mbts.spark.utilities {
return new CustomOrderDefinitionImmutable(mutable);
}
public static void assign_values_to(CustomOrderDefinitionImmutable source, ref CustomOrderDefinition target) {
if (target.CustomCase == source.CustomCase) {
switch (target.CustomCase) {
case CustomOrderDefinition.CustomOneofCase.Iceberg:
var iceberg = target.Iceberg;
_assign_iceberg_values(source.Iceberg, ref iceberg);
break;
case CustomOrderDefinition.CustomOneofCase.Stop:
var stop = target.Stop;
_assign_stop_values(source.Stop, ref stop);
break;
case CustomOrderDefinition.CustomOneofCase.StopLimit:
var stop_limit = target.StopLimit;
_assign_stop_limit_values(source.StopLimit, ref stop_limit);
break;
case CustomOrderDefinition.CustomOneofCase.Lean:
var lean = target.Lean;
_assign_lean_values(source.Lean, ref lean);
break;
case CustomOrderDefinition.CustomOneofCase.Join:
var join = target.Join;
_assign_join_values(source.Join, ref join);
break;
case CustomOrderDefinition.CustomOneofCase.Cover:
var cover = target.Cover;
_assign_cover_values(source.Cover, ref cover);
break;
case CustomOrderDefinition.CustomOneofCase.Top:
var top = target.Top;
_assign_top_values(source.Top, ref top);
break;
case CustomOrderDefinition.CustomOneofCase.Offset:
var offset = target.Offset;
_assign_offset_values(source.Offset, ref offset);
break;
case CustomOrderDefinition.CustomOneofCase.Tick:
var tick = target.Tick;
_assign_tick_values(source.Tick, ref tick);
break;
case CustomOrderDefinition.CustomOneofCase.TimeBox:
var time_box = target.TimeBox;
_assign_time_box_values(source.TimeBox, ref time_box);
break;
}
}
foreach ((var get_order, var get_orderi, var assign) in inner_order_dels) {
if (get_order(target) is CustomOrderDefinition tdef) {
if (get_orderi(source) is CustomOrderDefinitionImmutable sdef)
assign_values_to(sdef, ref tdef);
}
}
}
public static bool structure_equals(CustomOrderDefinitionImmutable a, CustomOrderDefinitionImmutable b) =>
a.CustomCase == b.CustomCase &&
EqualityComparer.nullable_equals(get_child_order(a), get_child_order(b), structure_equals) &&
@@ -401,30 +461,52 @@ namespace mbts.spark.utilities {
default: throw new ArgumentException($"OrderType ({nameof(def.CustomCase)}) does not have a hedge.", nameof(def));
}
}
//public static CustomOrderDefinitionImmutable create(AlgoStructureImmutable structure) {
// var rv = mk_root(structure);
// build(ref rv, get_child(structure), get_hedge(structure));
// return rv;
// // local methods
// CustomOrderDefinition mk_root(AlgoStructureImmutable a) => Defaults.CustomOrderDefinition((CustomOrderDefinition.CustomOneofCase)a.Type);
// AlgoStructureImmutable? get_child(AlgoStructureImmutable a) => a.HasChild ? a.Child : (AlgoStructureImmutable?)null;
// AlgoStructureImmutable? get_hedge(AlgoStructureImmutable a) => a.HasHedge ? a.Hedge : (AlgoStructureImmutable?)null;
// void build(ref CustomOrderDefinition def, AlgoStructureImmutable? child, AlgoStructureImmutable? hedge) {
// if (child.HasValue && has_child_order(def.CustomCase)) {
// var child_def = mk_root(child.Value);
// build(ref child_def, get_child(child.Value), get_hedge(child.Value));
// assign_child(ref def, child_def);
// }
// if (hedge.HasValue && has_hedge_order(def.CustomCase)) {
// var hedge_def = mk_root(hedge.Value);
// build(ref hedge_def, get_child(child.Value), get_hedge(child.Value));
// assign_hedge(ref def, hedge_def);
// }
// }
//}
#region Private Members
// assign values
static void _assign_iceberg_values(IcebergOrderDefinitionImmutable source, ref IcebergOrderDefinition target) =>
target.ShowQuantity = source.ShowQuantity;
static void _assign_lean_values(LeanOrderDefinitionImmutable source, ref LeanOrderDefinition target) {
target.CrossThreshold = source.HasCrossThreshold ? source.CrossThreshold.CloneToMutable() : null;
target.MaxChaseTicks = source.MaxChaseTicks;
target.DetachOnToward = source.DetachOnToward;
}
static void _assign_stop_limit_values(StopLimitOrderDefinitionImmutable source, ref StopLimitOrderDefinition target) =>
target.StopPrice = source.StopPrice;
static void _assign_stop_values(StopOrderDefinitionImmutable source, ref StopOrderDefinition target) =>
target.StopPrice = source.StopPrice;
static void _assign_time_box_values(TimeBoxOrderDefinitionImmutable source, ref TimeBoxOrderDefinition target) {
target.Start = source.HasStart ? source.Start.Clone() : null;
target.Stop = source.HasStop ? source.Stop.Clone() : null;
}
static void _assign_offset_values(OffsetOrderDefinitionImmutable source, ref OffsetOrderDefinition target) =>
target.TickOffsetOnDeploy = source.TickOffsetOnDeploy;
static void _assign_tick_values(TickOrderDefinitionImmutable source, ref TickOrderDefinition target) {
target.TickOffsetOnDeploy = source.TickOffsetOnDeploy;
target.CrossThreshold = source.HasCrossThreshold ? source.CrossThreshold.CloneToMutable() : null;
target.MaxChaseTicks = source.MaxChaseTicks;
target.DetachOnToward = source.DetachOnToward;
}
static void _assign_join_values(JoinOrderDefinitionImmutable source, ref JoinOrderDefinition target) =>
target.JoinThreshold = source.HasJoinThreshold ? source.JoinThreshold.CloneToMutable() : null;
static void _assign_cover_values(CoverOrderDefinitionImmutable source, ref CoverOrderDefinition target) =>
target.HedgeTicks = source.HedgeTicks;
static void _assign_trigger_values(TriggerOrderDefinitionImmutable source, ref TriggerOrderDefinition target) {
target.TriggerAction = source.HasTriggerAction ? source.TriggerAction.CloneToMutable() : null;
target.TriggerCondition = source.HasTriggerCondition ? source.TriggerCondition.CloneToMutable() : null;
target.ExitCondition = source.HasExitCondition ? source.ExitCondition.CloneToMutable() : null;
}
static void _assign_top_values(TopOrderDefinitionImmutable source, ref TopOrderDefinition target) {
target.TopThreshold = source.HasTopThreshold ? source.TopThreshold.CloneToMutable() : null;
target.WatchLevelTickOffset = source.WatchLevelTickOffset;
}
// get child
static CustomOrderDefinitionImmutable? _get_iceberg_child(IcebergOrderDefinitionImmutable iceberg) => iceberg.HasChild ? iceberg.Child : (CustomOrderDefinitionImmutable?)null;
static CustomOrderDefinitionImmutable? _get_time_box_child(TimeBoxOrderDefinitionImmutable time_box) => time_box.HasChild ? time_box.Child : (CustomOrderDefinitionImmutable?)null;