SPARK-619 Synthetic Creation Window should not allow OK if the data for a synth isn't there

This commit is contained in:
John Colvin committed 2018-03-07 23:07:18 -05:00
1 parent c910e522a7
commit 7d2f65425b
9 files changed
+165 -39

No files matched your search

@@ -240,6 +240,7 @@
<TextBlock Grid.Column="1" Margin="4,0,0,0" Text="{Binding}"/>
</Grid>
</DataTemplate>
<ControlTemplate x:Key="ExecutionStrategyEditorTemplate" TargetType="usp:ExecutionStrategyEditor">
<Border
BorderBrush="{TemplateBinding BorderBrush}"
@@ -257,25 +258,25 @@
</Grid.RowDefinitions>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="7*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="5*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center" IsEnabled="{TemplateBinding IsNew}">Name</TextBlock>
<TextBox
Grid.Column="1" Margin="6,0,0,0" HorizontalAlignment="Stretch" IsEnabled="{TemplateBinding IsNew}"
Text="{Binding SyntheticName, RelativeSource={RelativeSource TemplatedParent}}"
x:Name="PART_Name_TextBox" Grid.Column="1" Margin="6,0,0,0" HorizontalAlignment="Stretch" IsEnabled="{TemplateBinding IsNew}"
Text="{Binding SyntheticName, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}, ValidatesOnDataErrors=True, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}"
/>
<TextBlock
Grid.Column="2" VerticalAlignment="Center" Margin="6,0,0,0" Text="Ticks" IsEnabled="{TemplateBinding IsNew}"
Visibility="{Binding LegTuples.Count, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource IntNotZeroVisibilityConverter}}"
/>
<ComboBox
x:Name="PART_Tick_ComboBox" Grid.Column="3" Margin="6,0,0,0" IsEditable="True" IsEnabled="{TemplateBinding IsNew}"
x:Name="PART_Tick_ComboBox" Grid.Column="3" Margin="6,0,0,0" IsEditable="True" IsEnabled="{TemplateBinding IsNew}" HorizontalAlignment="Stretch"
Visibility="{Binding LegTuples.Count, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource IntNotZeroVisibilityConverter}}"
Text="{Binding TickFactors, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource TickFactorsTextConverter}, Mode=TwoWay}"
/>
@@ -324,6 +325,14 @@
</c:DataGridEx>
</Grid>
</Border>
<!--<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding ElementName=adornedElement, Path=AdornedElement.(Validation.ValidationAdornerSiteFor).(Validation.HasError)}" Value="true">
<Setter TargetName="ic" Property="ItemsSource" Value="{Binding ElementName=adornedElement, Path=AdornedElement.(Validation.ValidationAdornerSiteFor).(Validation.Errors)}" />
</DataTrigger>
<DataTrigger Binding="{Binding ElementName=adornedElement, Path=AdornedElement.(Validation.ValidationAdornerSiteFor)}" Value="{x:Null}">
<Setter TargetName="ic" Property="ItemsSource" Value="{Binding ElementName=adornedElement, Path=AdornedElement.(Validation.Errors)}" />
</DataTrigger>
</ControlTemplate.Triggers>-->
</ControlTemplate>
<Style TargetType="usp:ExecutionStrategyEditor">
<Setter Property="ParameterCellTemplateConverter" Value="{StaticResource ParameterCellTemplateConverter}"/>
@@ -332,5 +341,6 @@
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Template" Value="{StaticResource ExecutionStrategyEditorTemplate}"/>
<Setter Property="Validation.ErrorTemplate" Value="{x:Null}"/>
</Style>
</ResourceDictionary>
@@ -2,7 +2,6 @@
using bts.spark;
using mbts.spark;
using mbts.ui.controls;
using mbts.ui.utilities;
using mbts.ui.utility;
using mbts.user.settings;
using mbts.utils;
@@ -16,6 +15,7 @@ using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
@@ -141,6 +141,22 @@ namespace mbts.ui.spark {
public mbts.spark.ContractPickerModel ContractPickerModel { get => GetValue(ContractPickerModelProperty) as mbts.spark.ContractPickerModel; set => SetValue(ContractPickerModelProperty, value); }
#endregion
ExecutionStrategyErrorAdorner _error_adorner;
public ExecutionStrategyEditor() {
Loaded += _loaded;
Unloaded += _unloaded;
}
void _unloaded(object sender, RoutedEventArgs e) {
Disposable.dispose(ref _error_adorner);
}
void _loaded(object sender, RoutedEventArgs e) {
Disposable.dispose(ref _error_adorner);
_error_adorner = new ExecutionStrategyErrorAdorner(this);
}
public override void OnApplyTemplate() {
var tick_combo_box = this.assert_template_child<ComboBox>("PART_Tick_ComboBox");
tick_combo_box.ItemsSource = _ticks;
@@ -249,4 +265,55 @@ namespace mbts.ui.spark {
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
throw new NotImplementedException();
}
class ExecutionStrategyErrorAdorner : Adorner, IDisposable {
readonly ExecutionStrategyEditor _editor;
SyntheticEditorVM _vm;
TextBox _name_text_box;
ComboBox _tick_combo_box;
IDisposable _errors_changed_hook;
public ExecutionStrategyErrorAdorner(ExecutionStrategyEditor editor) : base(editor) {
this.attach();
_editor = editor;
_vm = _editor.DataContext as SyntheticEditorVM;
_connect_vm();
_editor.DataContextChanged += (s, e) => _connect_vm();
}
public void Dispose() => this.detach();
TextBox name_text_box => _name_text_box ?? (_name_text_box = _editor.assert_template_child<TextBox>("PART_Name_TextBox"));
ComboBox tick_combo_box => _tick_combo_box ?? (_tick_combo_box = _editor.assert_template_child<ComboBox>("PART_Tick_ComboBox"));
void _connect_vm() {
Disposable.dispose(ref _errors_changed_hook);
if (_editor.DataContext is SyntheticEditorVM vm) {
(_vm = vm).ErrorsChanged += _errors_changed;
_errors_changed_hook = Disposable.Create(() => {
vm.ErrorsChanged -= _errors_changed;
_name_text_box = null;
_tick_combo_box = null;
});
}
}
void _errors_changed(object sender, DataErrorsChangedEventArgs e) =>
InvalidateVisual();
protected override void OnRender(DrawingContext drawing_context) {
const double y_offset = 10;
string leg_count_msg = _vm.GetErrors(nameof(SyntheticEditorVM.leg_count)).Cast<string>().FirstOrDefault();
if (leg_count_msg != null)
this.draw_text_beneath(leg_count_msg, drawing_context, name_text_box, Brushes.Yellow, 0, y_offset);
else {
if (_vm != null && _vm.GetErrors(nameof(SyntheticEditorVM.name)).Cast<string>().Any())
this.draw_border(drawing_context, name_text_box, null, new Pen(Brushes.Red, 1));
if (_vm != null && _vm.GetErrors(nameof(SyntheticEditorVM.tick_factors)).Cast<string>().Any())
this.draw_border(drawing_context, tick_combo_box, null, new Pen(Brushes.Red, 1));
string error_text = string.Join(", ", _vm.AllErrors);
this.draw_text_beneath(error_text, drawing_context, name_text_box, Brushes.OrangeRed, 0, y_offset);
}
}
}
}
@@ -4,6 +4,7 @@ using mbts;
using mbts.spark;
using mbts.ui;
using mbts.ui.spark;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
@@ -25,8 +26,11 @@ namespace bts.shell {
_model = model;
}
static void _show_synthetic_editor(SyntheticEditorVM vm) =>
new SyntheticEditorView { DataContext = vm }.Show(-250, -200, true);
static void _show_synthetic_editor(SyntheticEditorVM vm) {
var v = new SyntheticEditorView { DataContext = vm };
WindowUtilities.listen_for_close_requests(v);
v.Show(-250, -200, true);
}
async void _show_synthetic_create(SecurityCriteria security_criteria) =>
_show_synthetic_create((await security_criteria.securities(_bus)).ToList());
@@ -56,5 +56,11 @@ namespace mbts.spark {
var result = await _service.update_security_metadata_async(new Metadata { SecurityKey = synthetic, Strategy = strategy.CloneToMutable() });
return _error.handle_error(result, "Error saving execution strategy: {0}", r => r.Error, e => e == UpdateResult.Types.Error.Ok);
}
public async Task<bool> verify_name_is_unique(string name) {
var (result, success) = await strategy_tuple.FirstAsyncTask(SparkUtils.DefaultTimeOut);
name = name.Trim().ToLower();
return success && !result.Values.Any(st => st.md.security.Synthetic.Name.Trim().ToLower() == name);
}
}
}
@@ -31,7 +31,7 @@
RemoveLegCommand="{Binding remove_leg}"
ContractPickerModel="{Binding contract_picker_model}"
/>
<c:DialogSkirtOKCancel Grid.Row="1" OKCommand="{Binding commit}"/>
<c:DialogSkirtOKCancel Grid.Row="1" OKCommand="{Binding commit}" CloseOnOK="False"/>
</Grid>
<u:WindowStyle.TitleContentTemplate>
<DataTemplate>
@@ -16,11 +16,12 @@ namespace mbts.spark {
/// <summary>
/// The view model designed to serve as the DataContext for the SyntheticEditorView
/// </summary>
partial class SyntheticEditorVM : ViewModelBaseWithValidation, IDisposable {
partial class SyntheticEditorVM : ViewModelBaseWithValidation, IRequestViewClose, IDisposable {
readonly Security _synthetic;
readonly ExecutionStrategyImmutable _strategy;
bool _set_ticks_automatically;
TickFactors _tick_factors;
/// <summary>
/// Inititalizes a new instance of SyntheticEditorVM class. This constructor may only be used for already-existing synthetic securities (id must be non-zero).
/// </summary>
@@ -55,25 +56,41 @@ namespace mbts.spark {
};
remove_leg = new DelegateCommand<Security>(s => leg_tuples.removeFirst(l => l.leg.Security.Id == s.Id));
commit = new DelegateCommand(async () => {
if (_tick_factors == null || !_tick_factors.is_valid()) {
flash_error(nameof(tick_factors)).ignore();
return;
bool valid = true;
if (string.IsNullOrWhiteSpace(name)) {
flash_error_msg("Please enter a name", nameof(name)).ignore();
valid = false;
}
_synthetic.Synthetic.Legs.Clear();
_synthetic.Synthetic.Legs.AddRange(leg_tuples.Select(l => l.leg).OrderBy(l => l.Security, SecurityHelper.Comparer.Instance));
_synthetic.Symbol = _deduce_symbol(_synthetic);
double tick_frac = _tick_factors.tick_unit / _tick_factors.tick_base;
_synthetic.ContractSpec.LowTick = tick_frac;
_synthetic.ContractSpec.HighTick = tick_frac;
_synthetic.ContractSpec.PriceBreak = double.MaxValue;
TickUtils.add_tick_to_cache(_tick_factors);
uint? id = await model.create_synthetic(_synthetic);
if (id.HasValue && id != 0)
await model.save_strategy(id.Value, create_strategy());
});
else if (!await model.verify_name_is_unique(name)) {
flash_error_msg("Name already taken", nameof(name)).ignore();
valid = false;
}
if (_tick_factors == null || !_tick_factors.is_valid()) {
flash_error_msg("Invalid ticks", nameof(tick_factors)).ignore();
valid = false;
}
if (valid) {
_synthetic.Synthetic.Legs.Clear();
_synthetic.Synthetic.Legs.AddRange(leg_tuples.Select(l => l.leg).OrderBy(l => l.Security, SecurityHelper.Comparer.Instance));
_synthetic.Symbol = _deduce_symbol(_synthetic);
double tick_frac = _tick_factors.tick_unit / _tick_factors.tick_base;
_synthetic.ContractSpec.LowTick = tick_frac;
_synthetic.ContractSpec.HighTick = tick_frac;
_synthetic.ContractSpec.PriceBreak = double.MaxValue;
TickUtils.add_tick_to_cache(_tick_factors);
uint? id = await model.create_synthetic(_synthetic);
if (id.HasValue && id != 0) {
await model.save_strategy(id.Value, create_strategy());
RequestClose?.Invoke(this, new EventArgs());
}
}
}, () => leg_count > 0);
_deduce_ticks();
leg_tuples.CollectionChanged += (s, e) => {
if (_set_ticks_automatically) _deduce_ticks();
commit.RaiseCanExecuteChanged();
if (leg_count < 2) set_error(nameof(leg_count), "Must select 2 or more legs");
else clear_error(nameof(leg_count));
};
}
@@ -112,6 +129,8 @@ namespace mbts.spark {
}.Select(m => new RowVM(m, leg_tuples)).ToList();
}
public event EventHandler RequestClose;
public string title { get; }
public ImageSource icon { get; }
public string name { get => _synthetic.Synthetic.Name; set => _synthetic.Synthetic.Name = value; }
@@ -127,8 +146,9 @@ namespace mbts.spark {
public bool is_new_leg_popup_open { get; set; }
public SyntheticContract.Types.PriceCalc price_calc { get => _synthetic.Synthetic.PriceCalc; set => _synthetic.Synthetic.PriceCalc = value; }
public ObservableCollection<LegSpreaderParamsTuple> leg_tuples { get; }
public int leg_count => leg_tuples.Count;
public IReadOnlyCollection<RowVM> rows { get; }
public ICommand commit { get; }
public IRaiseCanExecuteChangedCommand commit { get; }
public ICommand remove_leg { get; }
public ContractPickerModel contract_picker_model { get; }
+15 -9
View File
@@ -183,16 +183,18 @@ namespace mbts.ui.shell
{
Dictionary<string, string> _errors = new Dictionary<string, string>();
protected void set_error(string property, string message) {
_errors[property] = message;
FireErrorsChanged(property);
protected void set_error(string property, string message, bool ignore_if_already_error = false) {
if (!_errors.ContainsKey(property) || !ignore_if_already_error) {
_errors[property] = message;
FireErrorsChanged(property);
}
}
protected void clear_error(string property) {
if (_errors.ContainsKey(property)) {
_errors.Remove(property);
FireErrorsChanged(property);
}
FireErrorsChanged(property);
}
protected async Task assert_flash_error(bool test, params string[] properties) {
@@ -203,14 +205,17 @@ namespace mbts.ui.shell
}
}
protected async Task flash_error(params string[] properties) {
protected async Task flash_error_msg(string msg, params string[] properties) {
foreach (var prop in properties)
set_error(prop, string.Empty);
set_error(prop, msg);
await Task.Delay(1000);
foreach (var prop in properties)
clear_error(prop);
}
protected async Task flash_error(params string[] properties) =>
await flash_error_msg(string.Empty, properties);
protected IDisposable validation() {
IEnumerable<string> current = _errors.Keys.ToList();
_errors.Clear();
@@ -247,9 +252,10 @@ namespace mbts.ui.shell
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public System.Collections.IEnumerable GetErrors(string propertyName) {
string error;
if (_errors.TryGetValue(propertyName, out error)) {
yield return error;
if (!string.IsNullOrEmpty(propertyName)) {
if (_errors.TryGetValue(propertyName, out string error)) {
yield return error;
}
}
}
@@ -17,7 +17,7 @@ namespace mbts.ui.converters {
}
}
}
return value;
return new TickFactors(-1, -1);
}
}
}
@@ -1,4 +1,6 @@
using System.Windows.Documents;
using mbts.ui.utility.text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
namespace mbts.ui
@@ -13,6 +15,17 @@ namespace mbts.ui
public static void detach(this Adorner adorner) {
var al = AdornerLayer.GetAdornerLayer(adorner.AdornedElement);
if (al != null) al.Remove(adorner);
}
}
public static void draw_border(this Adorner adorner, DrawingContext drawing_context, FrameworkElement element, Brush brush, Pen stroke) {
var tl = element.TranslatePoint(new Point(0, 0), adorner);
drawing_context.DrawRectangle(brush, stroke, new Rect(tl, new Point(tl.X + element.ActualWidth, tl.Y + element.ActualHeight)));
}
public static void draw_text_beneath(this Adorner adorner, string text, DrawingContext drawing_context, FrameworkElement element, Brush foreground, double x_offset, double y_offset) {
var bl = element.TranslatePoint(new Point(0, element.ActualHeight), adorner);
var ft = TextUtils.GetFormattedText(text, FontSizes.Regular, foreground);
drawing_context.DrawText(ft, new Point(bl.X + x_offset, bl.Y + y_offset));
}
}
}