Merge branch 'spark_crypto' of bitbucket.org:bluetradesys/spark into spark_crypto

This commit is contained in:
taha afzal committed 2022-01-11 20:01:03 -05:00
commit d7bfdf4397
186 files changed
+15844 -6355

No files matched your search

@@ -0,0 +1,365 @@
namespace mbts.spark {
using bts.api;
using mbts;
using mbts.analytics;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using ProtoBuf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Input;
class AnalyticsExpirationParametersVM : DisposableViewModelBase {
readonly IBus _bus;
readonly AnalyticsParametersUIModel _model;
readonly ObservableCollection<AnalyticsExpirationParameters> _parameters = new();
bool _auto_copy_rolls_is_checked;
bool _auto_copy_rates_is_checked;
// IRaiseCanExecuteChangedCommand _copy_roll_schedule_to_selection;
// IRaiseCanExecuteChangedCommand _copy_roll_target_to_selection;
// IRaiseCanExecuteChangedCommand _copy_settlement_price_to_selection;
// IRaiseCanExecuteChangedCommand _copy_delta_beta_to_selection;
// IRaiseCanExecuteChangedCommand _copy_vega_beta_to_selection;
// IRaiseCanExecuteChangedCommand _smart_copy_roll_target;
// IRaiseCanExecuteChangedCommand _smart_copy_riskless_rate;
public AnalyticsExpirationParametersVM(IBus bus, AnalyticsParametersUIModel model, StartupData startup_data) {
_bus = bus ?? throw new ArgumentNullException(nameof(bus));
_model = model ?? throw new ArgumentNullException(nameof(model));
non_options_with_empty = new ObservableAggregateCollection<SecurityExpiration>(
new() { SecurityExpiration.empty }, non_options);
if (startup_data != null) {
if (!startup_data.selected_symbols.is_null_or_empty()) {
checked_symbols.AddRange(startup_data.selected_symbols);
}
auto_copy_rolls_is_checked = startup_data.auto_copy_rolls_is_checked;
auto_copy_rates_is_checked = startup_data.auto_copy_rates_is_checked;
}
dialog_skirt_items.Add(new DialogSkirtItem("Commit",
new AsyncCommand(async _ => {
var param_map = await _bus.subscribe(SparkTags.ExpirationParametersInputTag)
.StopAfter(TimeSpan.FromSeconds(30))
.FirstOrDefaultAsync();
if (param_map != null) {
_model.commit(rows.Select(_from_row));
}
})));
dialog_skirt_items.Add(new DialogSkirtItem("Revert", new DelegateCommand(_ => {
foreach (var r in rows) {
r.revert();
}
})));
checked_symbols.CollectionChanged += _on_checked_symbols_changed;
_model.on_expiration_parameters += sync_params;
_dispose = Disposable.Create(
ObservableAutoWrapper.connect(_parameters, rows, _to_row, r => r.Dispose()),
Disposable.Create(() => {
checked_symbols.CollectionChanged -= _on_checked_symbols_changed;
_model.on_expiration_parameters -= sync_params;
_parameters.Clear();
rows.DisposeAll();
}));
init_async().ignore();
async Task init_async() {
var initial_param_map = await _bus.subscribe(SparkTags.ExpirationParametersInputTag).FirstOrDefaultAsync();
if (initial_param_map != null) {
sync_params(initial_param_map);
}
}
void sync_params(AnalyticsExpirationParametersMap param_map) {
_parameters.sync_with(param_map.get_sorted_exps().Select(exp => param_map.get_parameter(exp)));
non_options.sync_with(param_map.get_sorted_exps().Where(exp => exp.security_type != SecurityType.Option));
//this of course assumes rows are sorted by Exp!
rows.GroupBy(r => r.security.expiration.Month).ForEach(exp_group => {
exp_group.ForEach(r => r.is_last_row_of_month_group = false);
exp_group.ElementAt(exp_group.Count() - 1).is_last_row_of_month_group = true;
});
List<string> uniq = rows.Select(x => x.security.symbol).Distinct().ToList();
uniq.Sort();
// the data source for the MSDD (contiains unique symbol names
// and set the initial selection to all
distinct_symbols.sync_with(uniq);
if (checked_symbols.Count == 0) {
// check all the symbols in the first load
checked_symbols.sync_with(uniq);
// the data source for the DataGrid, filtered according to the selected rows in the MSDD
filtered_for_visible_rows.sync_with(rows);
} else {
// the form has just been commited, but rather than sync_with the original row collection,
// which will reset the grid to all symbols, we need to sync_with the checked symbols again to reset
// the red outline of the cell
filtered_for_visible_rows.sync_with(rows.Where(x => checked_symbols.Contains(x.security.symbol)));
}
}
}
public ObservableCollection<SecurityExpiration> non_options { get; } = new();
public ObservableCollection<SecurityExpiration> non_options_with_empty { get; } = new();
public ObservableCollection<object> filtered_for_visible_rows { get; } = new();
public ObservableCollection<object> checked_symbols { get; } = new();
public ObservableCollection<string> distinct_symbols { get; } = new();
public ObservableCollection<ExpParamsRow> rows { get; } = new();
public ObservableCollection<object> selected_rows { get; } = new();
public ObservableCollection<DialogSkirtItem> dialog_skirt_items { get; } = new();
public bool auto_copy_rolls_is_checked {
get => _auto_copy_rolls_is_checked;
set => Set(ref _auto_copy_rolls_is_checked, value);
}
public bool auto_copy_rates_is_checked {
get => _auto_copy_rates_is_checked;
set => Set(ref _auto_copy_rates_is_checked, value);
}
ExpParamsRow _to_row(AnalyticsExpirationParameters exp_params) =>
new(exp_params, this);
AnalyticsExpirationParameters _from_row(ExpParamsRow row) =>
new(row.security, row.driver, row.deliverable.is_empty() ? null : row.deliverable, row.roll_schedule.is_empty() ? null : row.roll_schedule, row.roll_target, row.riskless_rate, row.settlement_price, row.delta_beta, row.vega_beta);
public StartupData get_state() =>
new() {
selected_symbols = checked_symbols.Cast<string>().ToArray(),
auto_copy_rates_is_checked = auto_copy_rates_is_checked,
auto_copy_rolls_is_checked = auto_copy_rolls_is_checked
};
void _on_checked_symbols_changed(object sender, NotifyCollectionChangedEventArgs e) =>
filtered_for_visible_rows.sync_with(rows.Where(x => checked_symbols.Contains(x.security.symbol)));
public class ExpParamsRow : DisposableViewModelBase, AnalyticsExpirationParametersView.IExpParamsRow {
readonly AnalyticsExpirationParameters _original_params;
readonly AnalyticsExpirationParametersVM _owner;
readonly Property<SecurityExpiration> _roll_schedule;
readonly Property<bool> _roll_schedule_dirty;
double _roll_target;
double _riskless_rate;
double _settlement_price;
double _delta_beta;
double _vega_beta;
SecurityExpiration _driver;
SecurityExpiration _deliverable;
bool _is_last_row_of_month_group;
IRaiseCanExecuteChangedCommand _copy_driver_to_selection;
IRaiseCanExecuteChangedCommand _copy_deliverable_to_selection;
readonly ObservantCommand _smart_copy_roll_target_cmd;
readonly ObservantCommand _smart_copy_riskless_rate_cmd;
public ExpParamsRow(AnalyticsExpirationParameters param, AnalyticsExpirationParametersVM owner) {
_original_params = param;
_owner = owner;
security = param.security;
_driver = param.driver_security;
_deliverable = param.deliverable_security;
_roll_schedule = backing(nameof(roll_schedule), param.roll_schedule_expiration);
_roll_schedule_dirty = backing(
nameof(roll_schedule_dirty),
_roll_schedule.observe_current(true)
.Select(rs => !rs.Equals(_original_params.roll_schedule_expiration)));
_roll_target = param.roll_target;
_riskless_rate = param.riskless_rate;
_settlement_price = param.settlement_price;
_delta_beta = param.delta_beta;
_vega_beta = param.vega_beta;
_delta_beta = param.delta_beta;
_vega_beta = param.vega_beta;
_smart_copy_roll_target_cmd = new ObservantCommand(_smart_copy_roll_target);
_smart_copy_riskless_rate_cmd = new ObservantCommand(_smart_copy_riskless_rate);
_dispose = Disposable.Create(
_roll_schedule.observe_current(true)
.CombineLatest(_roll_schedule_dirty.observe_current(true), (rs, rs_dirty) => (rs, rs_dirty))
.Select(tup => !tup.rs.is_empty() && !tup.rs_dirty)
.Subscribe(new CompositeObserver<bool>(_smart_copy_roll_target_cmd, _smart_copy_riskless_rate_cmd)));
}
public SecurityExpiration security { get; }
public SecurityExpiration driver { get => _driver; set => Set(ref _driver, value); }
public SecurityExpiration deliverable { get => _deliverable; set => Set(ref _deliverable, value); }
public SecurityExpiration roll_schedule { get => _roll_schedule.Value; set => _roll_schedule.Value = value; }
public bool is_last_row_of_month_group {
get => _is_last_row_of_month_group;
set => Set(ref _is_last_row_of_month_group, value);
}
public double roll_target {
get => _roll_target;
set => _handle_input(_original_params.roll_target, ref _roll_target, value);
}
public double riskless_rate {
get => _riskless_rate;
set => _handle_input(_original_params.riskless_rate, ref _riskless_rate, value);
}
public double settlement_price {
get => _settlement_price;
set => _handle_input(_original_params.settlement_price, ref _settlement_price, value);
}
public double delta_beta {
get => _delta_beta;
set => _handle_input(_original_params.delta_beta, ref _delta_beta, value);
}
public double vega_beta {
get => _vega_beta;
set => _handle_input(_original_params.vega_beta, ref _vega_beta, value);
}
public bool driver_dirty => !_driver.Equals(_original_params.driver_security);
public bool deliverable_dirty => !_deliverable.Equals(_original_params.deliverable_security);
public bool roll_schedule_dirty => !_roll_schedule.Equals(_original_params.roll_schedule_expiration);
public bool roll_target_dirty => !_roll_target.Equals(_original_params.roll_target);
public bool riskless_rate_dirty => !_riskless_rate.Equals(_original_params.riskless_rate);
public bool settlement_price_dirty => !_settlement_price.Equals(_original_params.settlement_price);
public bool delta_beta_dirty => !_delta_beta.Equals(_original_params.delta_beta);
public bool vega_beta_dirty => !_vega_beta.Equals(_original_params.vega_beta);
public ICommand copy_driver_to_selection_cmd => _copy_driver_to_selection ??= new DelegateCommand(_ => {
foreach (var r in _get_selected_rows()) {
r.driver = driver;
r.RaisePropertyChanged(nameof(r.driver));
}
});
public ICommand copy_deliverable_to_selection_cmd => _copy_deliverable_to_selection ??= new DelegateCommand(_ => {
foreach (var r in _get_selected_rows()) {
r.deliverable = deliverable;
r.RaisePropertyChanged(nameof(r.deliverable));
}
});
public ICommand copy_roll_schedule_to_selection_cmd => new DelegateCommand(_ => {
foreach (var r in _get_selected_rows()) {
r.roll_schedule = roll_schedule;
r.RaisePropertyChanged(nameof(r.roll_schedule));
}
});
public ICommand copy_roll_target_to_selection_cmd => new DelegateCommand(() => {
foreach (var r in _get_selected_rows()) {
r.roll_target = roll_target;
}
});
public ICommand copy_riskless_rate_to_selection_cmd => new DelegateCommand(() => {
foreach (var r in _get_selected_rows()) {
r.riskless_rate = riskless_rate;
}
});
public ICommand copy_settlement_price_to_selection_cmd => new DelegateCommand(() => {
foreach (var r in _get_selected_rows()) {
r.settlement_price = settlement_price;
}
});
public ICommand copy_delta_beta_to_selection_cmd => new DelegateCommand(() => {
foreach (var r in _get_selected_rows()) {
r.delta_beta = delta_beta;
}
});
public ICommand copy_vega_beta_to_selection_cmd => new DelegateCommand(() => {
foreach (var r in _get_selected_rows()) {
r.vega_beta = vega_beta;
}
});
public ICommand smart_copy_roll_target_cmd => _smart_copy_roll_target_cmd;
public ICommand smart_copy_riskless_rate_cmd => _smart_copy_riskless_rate_cmd;
public void revert() {
driver = _original_params.driver_security;
deliverable = _original_params.deliverable_security;
roll_schedule = _original_params.roll_schedule_expiration;
roll_target = _original_params.roll_target;
riskless_rate = _original_params.riskless_rate;
settlement_price = _original_params.settlement_price;
delta_beta = _original_params.delta_beta;
vega_beta = _original_params.vega_beta;
}
void _handle_input(double orig, ref double current, double next, [CallerMemberName] string prop = "") {
if (current.Equals(next)) {
return;
}
bool raise_dirty = current.Equals(orig) != next.Equals(orig);
current = next;
RaisePropertyChanged(prop);
if (raise_dirty) {
RaisePropertyChanged(prop + "_dirty");
}
if (prop == nameof(roll_target) && _smart_copy_roll_target_cmd.CanExecute(null) && _owner.auto_copy_rolls_is_checked) {
_smart_copy_roll_target();
}
if (prop == nameof(riskless_rate) && _smart_copy_riskless_rate_cmd.CanExecute(null) && _owner.auto_copy_rates_is_checked) {
_smart_copy_riskless_rate();
}
}
IEnumerable<ExpParamsRow> _get_selected_rows() =>
_owner.selected_rows.OfType<ExpParamsRow>().ToList();
IEnumerable<ExpParamsRow> _get_smart_copy_roll_target_rows() {
var target_exps = _owner._model.get_smart_copy_roll_exps(_original_params);
var target_rows = _owner.rows.Where(r => target_exps.Contains(r.security));
return target_rows;
}
void _smart_copy_roll_target() {
foreach (var r in _get_smart_copy_roll_target_rows()) {
r.roll_target = roll_target;
}
}
void _smart_copy_riskless_rate() {
foreach (var r in _get_smart_copy_roll_target_rows()) {
r.riskless_rate = riskless_rate;
}
}
}
[ProtoContract]
public class StartupData {
public const int VERSION = 1;
[ProtoMember(10)]
public string[] selected_symbols;
[ProtoMember(20)]
public bool auto_copy_rates_is_checked;
[ProtoMember(30)]
public bool auto_copy_rolls_is_checked;
}
}
}
@@ -0,0 +1,544 @@
<UserControl
x:Class="mbts.ui.shell.AnalyticsExpirationParametersView"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:u="clr-namespace:mbts.ui"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:shell="clr-namespace:mbts.ui.shell"
Width="837"
TextElement.FontSize="11"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300">
<UserControl.Resources>
<cv:DoubleTextConverter x:Key="DoubleTextConverter" />
<cv:DoubleTextConverter
x:Key="RisklessRateConverter"
Multiplier="100" />
<shell:ExpTextConverter
x:Key="ExpirationTextConverter"
ShowSymbol="True"
MapExp="True" />
<DataTemplate x:Key="ExpirationTemplate">
<TextBlock Text="{Binding Converter={StaticResource ExpirationTextConverter}}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger
Property="Text"
Value="None">
<Setter
Property="FontStyle"
Value="Italic" />
<Setter
Property="Foreground"
Value="Gray" />
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</UserControl.Resources>
<Grid>
<Grid.Resources>
<cv:BooleanToVisibilityConverter x:Key="TrueVisibilityConverter" />
<cv:BooleanToVisibilityConverter
x:Key="FalseVisibilityConverter"
VisibilityForFalse="Visible"
VisibilityForTrue="Collapsed" />
<ContextMenu x:Key="DriverContextMenu">
<MenuItem
Header="Copy Driver to Selection"
Command="{Binding copy_driver_to_selection}" />
</ContextMenu>
<ContextMenu x:Key="DeliverableContextMenu">
<MenuItem
Header="Copy Deliverable to Selection"
Command="{Binding copy_deliverable_to_selection}" />
</ContextMenu>
<ContextMenu x:Key="RollScheduleContextMenu">
<MenuItem
Header="Copy Roll Schedule to Selection"
Command="{Binding copy_roll_schedule_to_selection}" />
</ContextMenu>
<ContextMenu x:Key="RollTargetContextMenu">
<MenuItem
Header="Copy Roll Target to Selection"
Command="{Binding copy_roll_target_to_selection}" />
<MenuItem
Header="Smart Copy Roll Target"
Command="{Binding smart_copy_roll_target}" />
</ContextMenu>
<ContextMenu x:Key="RisklessRateContextMenu">
<MenuItem
Header="Copy Riskless Rate to Selection"
Command="{Binding copy_riskless_rate_to_selection}" />
</ContextMenu>
<ContextMenu x:Key="SettlementPriceContextMenu">
<MenuItem
Header="Copy Settlement Price to Selection"
Command="{Binding copy_settlement_price_to_selection}" />
</ContextMenu>
<ContextMenu x:Key="DeltaBetaContextMenu">
<MenuItem
Header="Copy Delta Beta to Selection"
Command="{Binding copy_delta_beta_to_selection}" />
</ContextMenu>
<ContextMenu x:Key="VegaBetaContextMenu">
<MenuItem
Header="Copy Vega Beta to Selection"
Command="{Binding copy_vega_beta_to_selection}" />
</ContextMenu>
</Grid.Resources>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel
Grid.Row="0"
Orientation="Horizontal"
Margin="0,5,0,5">
<c:MultiSelectDropDown
ItemsSource="{Binding distinct_symbols}"
SelectedItems="{Binding checked_symbols}"
HorizontalAlignment="Left"
Margin="5,2,2,2"
TextBlock.Foreground="Black"
HeaderText="Symbols"
ShowSelectAll="True"></c:MultiSelectDropDown>
<WrapPanel>
<TextBlock
Margin="5,5,0,0"
Text="Auto copy rolls:" />
<CheckBox
Margin="5,5,10,0"
IsChecked="{Binding auto_copy_rolls_is_checked}" />
</WrapPanel>
<WrapPanel>
<TextBlock
Margin='0,5,0,0'
Text="Auto copy rates:" />
<CheckBox
Margin="5,5,0,0"
IsChecked="{Binding auto_copy_rates_is_checked}" />
</WrapPanel>
</StackPanel>
<c:DataGridEx
Grid.Row="1"
ItemsSource="{Binding filtered_for_visible_rows}"
AlternatingRowBackground="{u:BTSColor MarketData.driver_background}"
VerticalGridLinesBrush="Gray"
EnableRowVirtualization="False"
EnableColumnVirtualization="False"
CanUserAddRows="False"
AutoGenerateColumns="False"
CanUserReorderColumns="False"
CanUserSortColumns="False"
CanUserDeleteRows="False"
RowHeaderWidth="0"
GridLinesVisibility="Vertical"
SelectionUnit="FullRow"
SelectedUnits="{Binding selected_rows}"
PreviewMouseRightButtonUp="grid_PreviewMouseRightButtonUp">
<DataGrid.Resources>
<Style
TargetType="{x:Type DataGridCell}"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="BorderThickness"
Value="1" />
<Style.Triggers>
<Trigger
Property="IsSelected"
Value="True">
<Setter
Property="Background"
Value="{u:BTSColor Grid.grid_selection_background}" />
<Setter
Property="BorderBrush"
Value="{u:BTSColor Grid.grid_selection_background}" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Triggers>
<Trigger
Property="IsSelected"
Value="true">
<Setter
Property="Background"
Value="{u:BTSColor Grid.grid_selection_background}" />
</Trigger>
<DataTrigger
Binding="{Binding is_last_row_of_month_group}"
Value="True">
<Setter
Property="BorderThickness"
Value="0,0,0,1" />
<Setter
Property="BorderBrush"
Value="Black" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter
Property="Background"
Value="{u:BTSColor Name=header}" />
<Setter
Property="Foreground"
Value="{u:BTSColor Name=header_text}" />
<Setter
Property="HorizontalContentAlignment"
Value="Center" />
<Setter
Property="BorderThickness"
Value="0,0,1,0" />
<Setter
Property="BorderBrush"
Value="Black" />
<Setter
Property="Padding"
Value="3" />
<Setter
Property="MinWidth"
Value="80" />
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTextColumn
Header="Security"
Binding="{Binding security, Converter={StaticResource ExpirationTextConverter}}"
IsReadOnly="True">
<DataGridTextColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="Background"
Value="{u:BTSColor Name=header}" />
<Setter
Property="Foreground"
Value="{u:BTSColor Name=header_text}" />
<Setter
Property="BorderThickness"
Value="0" />
<Setter
Property="VerticalContentAlignment"
Value="Center" />
<Setter
Property="Padding"
Value="3" />
<Style.Triggers>
<DataTrigger
Binding="{Binding security.security_type}"
Value="OPTION">
<Setter
Property="Foreground"
Value="{u:BTSColor Name=header_text}" />
</DataTrigger>
<DataTrigger
Binding="{Binding security.security_type}"
Value="FUTURE">
<Setter
Property="Foreground"
Value="Gold" />
</DataTrigger>
<DataTrigger
Binding="{Binding security.security_type}"
Value="UNSET">
<Setter
Property="Foreground"
Value="PaleGreen" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
<DataGridTemplateColumn
Header="Driver"
MinWidth="105">
<DataGridTemplateColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="ContextMenu"
Value="{StaticResource DriverContextMenu}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding driver_dirty}"
Value="True">
<Setter
Property="BorderBrush"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding DataContext.non_options, RelativeSource={RelativeSource AncestorType=c:DataGridEx}}"
ItemTemplate="{StaticResource ExpirationTemplate}"
SelectedItem="{Binding driver, UpdateSourceTrigger=PropertyChanged}"
Margin="2" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn
Header="Deliverable"
MinWidth="105">
<DataGridTemplateColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="ContextMenu"
Value="{StaticResource DeliverableContextMenu}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding deliverable_dirty}"
Value="True">
<Setter
Property="BorderBrush"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding DataContext.non_options_with_empty, RelativeSource={RelativeSource AncestorType=c:DataGridEx}}"
ItemTemplate="{StaticResource ExpirationTemplate}"
SelectedItem="{Binding deliverable, UpdateSourceTrigger=PropertyChanged}"
Margin="2" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn
Header="Roll Schedule"
MinWidth="105">
<DataGridTemplateColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="ContextMenu"
Value="{StaticResource RollScheduleContextMenu}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding roll_schedule_dirty}"
Value="True">
<Setter
Property="BorderBrush"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox
ItemsSource="{Binding DataContext.non_options_with_empty, RelativeSource={RelativeSource AncestorType=c:DataGridEx}}"
ItemTemplate="{StaticResource ExpirationTemplate}"
SelectedItem="{Binding roll_schedule, UpdateSourceTrigger=PropertyChanged}"
Margin="2" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Roll Target $">
<DataGridTemplateColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="ContextMenu"
Value="{StaticResource RollTargetContextMenu}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding roll_target_dirty}"
Value="True">
<Setter
Property="BorderBrush"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding roll_target, Converter={StaticResource DoubleTextConverter}}"
VerticalAlignment="Center"
Margin="2,0,2,0"
ContextMenu="{StaticResource RollTargetContextMenu}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox
Text="{Binding roll_target, Converter={StaticResource DoubleTextConverter}}"
Margin="2" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Riskless Rate %">
<DataGridTemplateColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="ContextMenu"
Value="{StaticResource RisklessRateContextMenu}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding riskless_rate_dirty}"
Value="True">
<Setter
Property="BorderBrush"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding riskless_rate, Converter={StaticResource RisklessRateConverter}}"
VerticalAlignment="Center"
Margin="2,0,2,0"
ContextMenu="{StaticResource RisklessRateContextMenu}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding riskless_rate, Converter={StaticResource RisklessRateConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Settlement Price $">
<DataGridTemplateColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="ContextMenu"
Value="{StaticResource SettlementPriceContextMenu}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding settlement_price_dirty}"
Value="True">
<Setter
Property="BorderBrush"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding settlement_price, Converter={StaticResource DoubleTextConverter}}"
VerticalAlignment="Center"
Margin="2,0,2,0"
ContextMenu="{StaticResource SettlementPriceContextMenu}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding settlement_price, Converter={StaticResource DoubleTextConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Delta Beta">
<DataGridTemplateColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="ContextMenu"
Value="{StaticResource DeltaBetaContextMenu}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding delta_beta_dirty}"
Value="True">
<Setter
Property="BorderBrush"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding delta_beta, Converter={StaticResource DoubleTextConverter}}"
VerticalAlignment="Center"
Margin="2,0,2,0"
ContextMenu="{StaticResource DeltaBetaContextMenu}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding delta_beta, Converter={StaticResource DoubleTextConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Vega Beta">
<DataGridTemplateColumn.CellStyle>
<Style
TargetType="DataGridCell"
BasedOn="{StaticResource {x:Type DataGridCell}}">
<Setter
Property="ContextMenu"
Value="{StaticResource VegaBetaContextMenu}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding vega_beta_dirty}"
Value="True">
<Setter
Property="BorderBrush"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock
Text="{Binding vega_beta, Converter={StaticResource DoubleTextConverter}}"
VerticalAlignment="Center"
Margin="2,0,2,0"
ContextMenu="{StaticResource VegaBetaContextMenu}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding vega_beta, Converter={StaticResource DoubleTextConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</c:DataGridEx>
<c:DialogSkirt
Grid.Row="2"
Padding="8"
Margin="-3"
RightItems="{Binding dialog_skirt_items}" />
</Grid>
</UserControl>
@@ -0,0 +1,68 @@
namespace mbts.ui.shell {
using bts.api;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
/// <summary>
/// Interaction logic for AnalyticsExpirationParametersView.xaml
/// </summary>
partial class AnalyticsExpirationParametersView : UserControl {
public AnalyticsExpirationParametersView() =>
InitializeComponent();
public interface IExpParamsRow {
ICommand copy_driver_to_selection_cmd { get; }
ICommand copy_deliverable_to_selection_cmd { get; }
ICommand copy_roll_schedule_to_selection_cmd { get; }
ICommand copy_roll_target_to_selection_cmd { get; }
ICommand copy_riskless_rate_to_selection_cmd { get; }
ICommand copy_settlement_price_to_selection_cmd { get; }
ICommand copy_delta_beta_to_selection_cmd { get; }
ICommand copy_vega_beta_to_selection_cmd { get; }
ICommand smart_copy_roll_target_cmd { get; }
}
void grid_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e) {
if (e.OriginalSource is not FrameworkElement el) {
return;
}
var cell = el.find_ancestor_of_type<DataGridCell>();
if (cell?.ContextMenu is not ContextMenu cm || cell.DataContext is not IExpParamsRow row) {
return;
}
cm.DataContext = row;
cm.IsOpen = true;
e.Handled = true;
}
}
class ExpTextConverter : IValueConverter {
public ExpTextConverter() {
NullOrEmptyText = "None";
}
public bool ShowType { get; set; }
public bool ShowSymbol { get; set; }
public bool MapExp { get; set; }
public string NullOrEmptyText { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
var exp = value as SecurityExpiration;
if (exp == null || exp.is_empty()) {
return NullOrEmptyText;
}
return ShowSymbol ?
SecurityFormatter.format_future(exp.symbol, exp.expiration) :
DateFormatter.Format(exp.expiration, DateFormat.MonthCodeLastDigitYear);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
}
@@ -0,0 +1,42 @@
namespace mbts.spark {
using bts.api;
using bts.spark;
using mbts.ui.shell;
using System;
using System.Windows;
class AnalyticsExpirationParametersWindow : SparkWindow<AnalyticsExpirationParametersVM.StartupData> {
const string _window_type = nameof(AnalyticsExpirationParametersWindow);
readonly Lazy<AnalyticsParametersUIModel> _model;
readonly Lazy<AnalyticsExpirationParametersVM> _vm;
public AnalyticsExpirationParametersWindow(
IBus bus, AnalyticsExpirationParametersWindowFactory factory, AnalyticsExpirationParametersVM.StartupData startup_data)
: base("Analytics Exp Params", bus, factory) {
_model = new Lazy<AnalyticsParametersUIModel>(() => new AnalyticsParametersUIModel(_bus));
_vm = new Lazy<AnalyticsExpirationParametersVM>(
() => new AnalyticsExpirationParametersVM(bus, _model.Value, startup_data));
_dispose = Disposable.Create(() => {
if (_vm.IsValueCreated) {
_vm.Value.Dispose();
}
if (_model.IsValueCreated) {
_model.Value.Dispose();
}
});
}
public override string window_type => _window_type;
public override AnalyticsExpirationParametersVM.StartupData SaveState =>
_vm.IsValueCreated ? _vm.Value.get_state() : null;
public override UIElement Content =>
new AnalyticsExpirationParametersView {
DataContext = _vm.Value
};
}
}
@@ -0,0 +1,35 @@
namespace mbts.spark {
using bts.api;
using bts.shell;
using mbts.ui;
using System;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
class AnalyticsExpirationParametersWindowFactory : ShellWindowFactory<AnalyticsExpirationParametersVM.StartupData> {
readonly IBus _bus;
public AnalyticsExpirationParametersWindowFactory(IShellModule module, IBus bus)
: base(module, "Analytics Exp Params") {
_bus = bus;
_dispose = bus.subscribe(SparkTags.show_analytics_exp_params).OnDispatcher().Subscribe(_show);
}
public override Task<IShellWindow> load(AnalyticsExpirationParametersVM.StartupData state) =>
Task.FromResult(_create(state));
void _show(SparkTags.Nothing _) =>
_bus.post(SparkTags.ShowWindow, _create(new AnalyticsExpirationParametersVM.StartupData()));
void _show(SecurityCriteria security_criteria) =>
_bus.post(SparkTags.ShowWindow, _create(new AnalyticsExpirationParametersVM.StartupData {
selected_symbols = (security_criteria?.clauses?.FirstOrDefault())?.symbols ?? Array.Empty<string>()
}));
IShellWindow _create(AnalyticsExpirationParametersVM.StartupData startup_data) =>
new AnalyticsExpirationParametersWindow(_bus, this, startup_data);
}
}
@@ -0,0 +1,40 @@
namespace mbts.spark {
using bts.api;
using mbts;
using mbts.analytics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class AnalyticsParametersUIModel : IDisposable {
AnalyticsExpirationParametersMap _curr_val = null;
readonly IBus _bus;
readonly IDisposable _sub;
public event Action<AnalyticsExpirationParametersMap> on_expiration_parameters;
public AnalyticsParametersUIModel(IBus bus) {
_bus = bus;
_sub = _bus.subscribe(SparkTags.ExpirationParametersInputTag)
.Subscribe(d => on_expiration_parameters?.Invoke(d));
}
public void commit(IEnumerable<AnalyticsExpirationParameters> data) =>
_bus.post(SparkTags.ExpirationParametersCommitTag, data);
public IEnumerable<mbts.SecurityExpiration> get_smart_copy_roll_exps(AnalyticsExpirationParameters source) {
if (_curr_val != null) {
foreach (var kv in _curr_val.exp_map)
if (kv.Value.roll_schedule_expiration.Equals(source.roll_schedule_expiration))
yield return kv.Key;
}
}
public void Dispose() =>
_sub.Dispose();
}
}
@@ -1,18 +1,14 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts.analytics;
using mbts;
using bts.api;
using System.Security.Principal;
using mbts.co2;
namespace mbts.spark {
using DriverMD = Tuple<SecurityImmutable, VolSurfaceBBOUnit>;
// publishes the driver prices for driver securities that drive
// expirations of an option
// Publishes the driver prices for expirations of a single option (this is not AW2 specific)
// f(AnalyticsExpirationParametersMap, SystemContractData) -> OptionDriverPriceMap
// This is constructed by the ResourceAllocator
public class SingleOptionDriverPricePublisher {
private readonly SecurityTuple _sec_tup;
private ThreadedBlackboard _bb;
@@ -21,18 +17,20 @@ namespace mbts.spark {
SparkTags.ExpirationParametersInputTag;
private ITag<SystemContractData> _in_bb_contracts_tag =
SparkTags.SystemContractsTag;
private IDictionary<SecurityExpiration, DriverMD> _last_published_map
= new Dictionary<SecurityExpiration, DriverMD>();
private OptionDriverPriceMap _last_published;
public SingleOptionDriverPricePublisher(SecurityTuple sec_tup,
ThreadedBlackboard bb) {
bts.Log.Gen.info($"SingleOptionDriverPricePublisher initialized st:'{sec_tup}'");
bts.Log.Gen.info($"SingleOptionDriverPricePublisher initialized st:{sec_tup}");
_sec_tup = sec_tup;
_bb = bb;
_last_published = new OptionDriverPriceMap(sec_tup.security_name,
new Dictionary<SecurityExpiration, DriverMD>());
_bb.subscribe(_in_bb_exp_params_tag);
_bb.subscribe(_in_bb_contracts_tag);
_bb.data_callback += _on_bb_data;
_bb.timer_callback += _on_bb_timer;
_compute_and_fire();
}
private void _on_bb_data(object tag, object data) {
@@ -63,8 +61,10 @@ namespace mbts.spark {
res.Add(option_exp, bbo_tup);
}
if (_is_different(res)) {
_last_published_map = res;
bts.Log.Gen.info($"SingleOptionDriverPricePublisher._compute_and_fire sz:'{res.Count()}'");
_last_published = new OptionDriverPriceMap(_sec_tup.security_name, res);
var to_fire = new OptionDriverPriceMap(_sec_tup.security_name, res);
bts.Log.Gen.info("SingleOptionDriverPricePublisher._compute_and_fire \n" +
$"map:{to_fire.log_string()}");
_bb.post(SparkTags.OptionDriverBBOTag(_sec_tup.security_name),
new OptionDriverPriceMap(_sec_tup.security_name, res));
}
@@ -76,7 +76,7 @@ namespace mbts.spark {
return !d1.Item1.Equals(d2.Item1) ||
!d1.Item2.Equals(d2.Item2);
};
new_dic.Difference(_last_published_map, out var ex_left, out var ex_right, out var overlap);
new_dic.Difference(_last_published.exp_price_map, out var ex_left, out var ex_right, out var overlap);
return ex_left.Count() != 0 || ex_right.Count() != 0 ||
overlap.Where(v => is_dmd_diff(v.Value.left, v.Value.right)).Count() > 0;
}
@@ -12,8 +12,8 @@ namespace mbts.spark {
// - f (vs_input, aux_data, securities) -> vs_output
// and publishes it
// Subs :
// 1. Comm VS Input
// 3. VS nonvol Data
// 1. Committed VS Input
// 3. VS Nonvol Data
// Pubs :
// 1. VS Out
public class SingleVolSurfaceCommittedOutputRetriever : IDisposable {
@@ -29,7 +29,7 @@ namespace mbts.spark {
public SingleVolSurfaceCommittedOutputRetriever(int vs_id,
ThreadedBlackboard threaded_bb, IEnumerable<string> symbols) {
bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever cons vs_id:{vs_id}");
bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever cons vs_id:{vs_id} tid:{_tid()}");
_vs_id = vs_id;
_bb = threaded_bb;
_in_bb_vs_input_tag = SparkTags.VolSurfaceCommittedInputTag(vs_id);
@@ -43,13 +43,14 @@ namespace mbts.spark {
_bb.data_callback += _on_bb_data;
_recompute_and_publish();
}
private static int _tid() { return VolSurfaceTroubleshootingFunctions.tid(); }
private void _on_bb_data(object tag, object data) {
if (_in_bb_vs_input_tag.Equals(tag) || _in_bb_nonvol_data_tag.Equals(tag) || _in_vs_standard_time_tag.Equals(tag))
_recompute_and_publish();
if (_in_bb_vs_input_tag.Equals(tag) || _in_bb_nonvol_data_tag.Equals(tag) ||
_in_vs_standard_time_tag.Equals(tag))
_recompute_and_publish(tag);
}
private void _recompute_and_publish() {
private void _recompute_and_publish(object tag = null) {
VolSurfaceInput vs_input = _bb.read_state(_in_bb_vs_input_tag);
VolSurfaceNonVolData vs_nonvol_data = _bb.read_state(_in_bb_nonvol_data_tag);
VolSurfaceStandardTime vs_standard_time = _bb.read_state(_in_vs_standard_time_tag);
@@ -60,7 +61,10 @@ namespace mbts.spark {
vs_nonvol_data.input, vs_nonvol_data.driver_price_map, vs_standard_time);
VolSurfaceOutput vs_output = GeneralVolSurfaceCalculator.compute(vs_input, vs_nonvol_data.contracts, aux_data_map);
_timer.stop();
bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever._recompute_and_publish vs_id:{_vs_id} time:{_timer.lastIntervalTime} msecs");
var tag_str = tag == null ? "Null" : tag.ToString();
bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever._recompute_and_publish " +
$"vs_id:{_vs_id} time:{_timer.lastIntervalTime} ms tag:{tag_str} tid:{_tid()}" +
$"output: {vs_output.log_string()}");
_logger.log(_log_id, _log_id, _timer.lastIntervalTime);
_bb.post(_out_bb_computed_vol_tag, vs_output);
}
@@ -20,10 +20,10 @@ namespace mbts.spark {
private readonly int _volsurface_id;
private readonly ThreadedBlackboard _bb;
private readonly ITag<VolSurfaceInput> _in_bb_committ_tag;
private AnalyticsService _analytics_service;
private readonly AnalyticsService _analytics_service;
private readonly HighPerformanceTimer _timer = new HighPerformanceTimer();
private readonly string _user;
private List<IDisposable> _disposables = new List<IDisposable>();
private readonly List<IDisposable> _disposables = new List<IDisposable>();
private IDictionary<UInt64, VolSurfaceInputSnapshot> _snp_shot_map = new
Dictionary<UInt64, VolSurfaceInputSnapshot>();
@@ -45,12 +45,8 @@ namespace mbts.spark {
}
private void _log_basic_vs_info(VolSurfaceInput vs_inp) {
string exp_str = "expirations: ";
foreach (var kv in vs_inp.surface_parameters.curve_parameters_map) {
exp_str += " " + kv.Item1.to_security_expiration().ToString();
}
bts.Log.Gen.info(String.Format("SingleVolSurfaceGateway vs_id:{0} {1}",
vs_inp.surface_settings.core_settings.vol_surface_id, exp_str));
bts.Log.Gen.info(String.Format("SingleVolSurfaceGateway vs_id:{0} vs:{1}",
vs_inp.surface_settings.core_settings.vol_surface_id, vs_inp.log_string()));
}
private void _on_vss(bts.api.core.Update<VolSurfaceEntryImmutable, UInt64> update) {
@@ -1,57 +1,75 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using bts.api.analytics;
using bts.api;
using mbts.analytics;
namespace mbts.spark {
public class SingleVolSurfaceManager : IDisposable {
private readonly int _vs_id;
private IEnumerable<IDisposable> _resources;
private readonly ITag<int> _in_bb_delete_tag = SparkTags.VolSurfaceDeleteTag;
private readonly ThreadedBlackboard _threaded_bb;
private readonly ThreadedBlackboard _bb;
private readonly AnalyticsService _analytics_service;
private ITag<bool> _vs_activation_tag;
private bool _activated = false;
public SingleVolSurfaceManager(int vs_id, ThreadedBlackboard t_bb,
AnalyticsService analytics_service) {
_threaded_bb = t_bb;
_threaded_bb.subscribe(_in_bb_delete_tag);
_threaded_bb.data_callback += _on_data;
var tid = System.Threading.Thread.CurrentThread.ManagedThreadId;
bts.Log.Ui.info($"SingleVolSurfaceManager.cons vs_id:{vs_id} tid:{tid}");
_vs_id = vs_id;
_bb = t_bb;
_analytics_service = analytics_service;
_vs_activation_tag = SparkTags.VolSurfaceActiveUITag(vs_id);
_bb.subscribe(_vs_activation_tag);
_bb.data_callback += _on_data;
}
private void _spin_resources() {
bts.Log.Ui.info($"SingleVolSurfaceManager._spin_resources vs_id:{_vs_id}");
_resources = new IDisposable[]
{
new SingleVolSurfaceGateway(vs_id, t_bb, analytics_service),
new SingleVolSurfaceTimeSource(vs_id,t_bb),
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, vs_id, t_bb,
syms => new SingleVolSurfaceOptionDriverSource(vs_id, syms, t_bb)),
{
new SingleVolSurfaceGateway(_vs_id, _bb, _analytics_service),
new SingleVolSurfaceTimeSource(_vs_id,_bb),
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, _vs_id, _bb,
syms => new SingleVolSurfaceOptionDriverSource(_vs_id, syms, _bb)),
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined,
vs_id, t_bb, syms => new SingleVolSurfaceNonVolDataSource(vs_id, syms, t_bb)),
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Committed, vs_id, t_bb,
a_syms => new SingleVolSurfaceCommittedOutputRetriever(vs_id, t_bb, a_syms)),
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Candidate, vs_id, t_bb,
a_syms => new SingleVolSurfaceRequestCalculator(vs_id, a_syms, t_bb)),
new SingleVolSurfaceMarketImpliedVolSource(vs_id, t_bb),
new SingleVolSurfaceTheoSource(vs_id, t_bb),
_vs_id, _bb, syms => new SingleVolSurfaceNonVolDataSource(_vs_id, syms, _bb)),
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Committed, _vs_id, _bb,
a_syms => new SingleVolSurfaceCommittedOutputRetriever(_vs_id, _bb, a_syms)),
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, _vs_id, _bb,
a_syms => new SingleVolSurfaceRequestCalculator(_vs_id, a_syms, _bb)),
new SingleVolSurfaceMarketImpliedVolSource(_vs_id, _bb),
new SingleVolSurfaceTheoSource(_vs_id, _bb),
// TODO: suspending heatmaps for now (12/24/21)
// new SingleVolSurfaceHeatmapManager (vs_id, t_bb),
// server work that can optionally be done on the client
new SingleVolSurfaceDataSource (SingleVolSurfaceDataSource.SymbolListType.Committed, vs_id, t_bb,
a_syms => new SingleVolSurfaceClientPrecomputedTheosPublisher (vs_id, t_bb, a_syms)),
};
new SingleVolSurfaceDataSource (SingleVolSurfaceDataSource.SymbolListType.Committed, _vs_id, _bb,
a_syms => new SingleVolSurfaceClientPrecomputedTheosPublisher (_vs_id, _bb, a_syms)),
};
}
private void _on_data(object tag, object data) {
if (_in_bb_delete_tag.Equals(tag))
Dispose();
if (_vs_activation_tag.Equals(tag)) {
if (_activated) {
// TODO: not cleaning up recources
return;
}
bool is_activation_signal = data is Boolean && (Boolean)data;
if (is_activation_signal) {
_activated = true;
_spin_resources();
}
}
}
#region IDisposable
private bool _is_disposed = false;
public void Dispose() {
if (!_is_disposed)
if (!_is_disposed) {
_is_disposed = true;
_resources.ToList().ForEach(d => d.Dispose());
}
}
#endregion
}
@@ -1,8 +1,5 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts.analytics;
using bts.api;
@@ -17,6 +14,7 @@ namespace mbts.spark {
// 3. Driver prices (VolSurfaceOptionDriverTag)
// Publishes :
// 1. VolSurfaceNonVolData which is simply a union of the 3 inputs
// 2. VolSurfaceStrikeMap
public class SingleVolSurfaceNonVolDataSource : IDisposable {
private readonly int _vs_id;
private readonly IEnumerable<string> _option_symbols;
@@ -26,12 +24,9 @@ namespace mbts.spark {
private readonly ITag<IDictionary<mbts.analytics.VolSurfaceExpiration, double>> _in_bb_driver_price_tag;
private readonly ITag<mbts.analytics.VolSurfaceNonVolData> _out_bb_vs_nonvol_data_tag;
private readonly ITag<mbts.analytics.VolSurfaceStrikeMap> _out_bb_vs_contracts_tag;
/// This is the only cached data to avoid computing it
/// when more frequently changing data move around
private IDictionary<VolSurfaceExpiration, IEnumerable<double>> _sec_map =
new Dictionary<VolSurfaceExpiration, IEnumerable<double>>();
public SingleVolSurfaceNonVolDataSource(int vs_id, IEnumerable<string> option_symbols, ThreadedBlackboard bb) {
public SingleVolSurfaceNonVolDataSource(int vs_id, IEnumerable<string> option_symbols,
ThreadedBlackboard bb) {
bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{vs_id}");
_vs_id = vs_id;
_option_symbols = option_symbols;
@@ -45,30 +40,41 @@ namespace mbts.spark {
_bb.subscribe(_in_bb_vs_nonvol_input_tag);
_bb.subscribe(_in_bb_driver_price_tag);
_bb.data_callback += _on_bb_data;
_init();
}
private void _init() {
_publish_vs_strike_map();
_recompute_and_fire();
}
private void _publish_vs_strike_map() {
SystemContractData sc_data = _bb.read_state(_in_bb_contract_data_tag);
if (sc_data != null) {
var k_map = new VolSurfaceStrikeMap(_option_symbols, sc_data);
bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{_vs_id} " +
"publishing strike_map sz:{k_map.strike_map.Count()}");
_bb.post(_out_bb_vs_contracts_tag, new VolSurfaceStrikeMap(_option_symbols, sc_data));
}
}
private void _on_bb_data(object tag, object data) {
if (_in_bb_contract_data_tag.Equals(tag)) {
SystemContractData contract_data = _bb.read_state(_in_bb_contract_data_tag);
_sec_map.Clear();
if (contract_data != null)
foreach (string s in _option_symbols)
foreach (var kv in contract_data.get_option_strikes(s))
_sec_map[new VolSurfaceExpiration() { symbol = s, expiration = kv.Key }] = kv.Value;
bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{_vs_id} publishing strike_map sz:{_sec_map.Count()}");
_bb.post(_out_bb_vs_contracts_tag, new VolSurfaceStrikeMap(_sec_map));
_publish_vs_strike_map();
_recompute_and_fire();
} else if (_in_bb_vs_nonvol_input_tag.Equals(tag) || _in_bb_driver_price_tag.Equals(tag))
_recompute_and_fire();
}
private void _recompute_and_fire() {
SystemContractData sc_data = _bb.read_state(_in_bb_contract_data_tag);
VolSurfaceNonVolInput vs_nonvol_input = _bb.read_state(_in_bb_vs_nonvol_input_tag);
var price_map = _bb.read_state(_in_bb_driver_price_tag);
if (_sec_map != null && vs_nonvol_input != null && price_map != null) {
if (sc_data != null && vs_nonvol_input != null && price_map != null) {
bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{_vs_id} publishing VolSurfaceNonVolData");
_bb.post(_out_bb_vs_nonvol_data_tag,
new VolSurfaceNonVolData(vs_nonvol_input, price_map, _sec_map));
new VolSurfaceNonVolData(vs_nonvol_input, price_map,
new VolSurfaceStrikeMap(_option_symbols, sc_data).strike_map));
}
}
@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts.analytics;
using bts.api;
@@ -11,29 +9,24 @@ namespace mbts.spark {
// Subs :
// 1. Driver Price tag for each option
// Publishes :
// 1. Map of VS Exp vs Driver Price for each Option Exp
// in the VS
// 1. Map of VS Exp vs Driver Price for each Option Exp in the VS
// TODO: VolSurfaceDriverSymbolPriceTag is not being published out (its needed for Slide)
public class SingleVolSurfaceOptionDriverSource : IDisposable {
private readonly int _vs_id;
private readonly ThreadedBlackboard _threaded_bb;
private readonly ITag<IDictionary<mbts.analytics.VolSurfaceExpiration, double>> _out_bb_driver_price_tag;
private readonly ITag<IDictionary<mbts.analytics.VolSurfaceExpiration, double>> _out_bb_driver_symbol_price_tag;
private IDictionary<VolSurfaceExpiration, double> _option_driver_price_map =
new Dictionary<VolSurfaceExpiration, double>();
private bool _option_driver_dirty = false;
private readonly ITag<IDictionary<mbts.analytics.VolSurfaceExpiration, double>>
_out_bb_driver_price_tag;
private bool _option_driver_dirty = true;
private HashSet<ITag<OptionDriverPriceMap>> _option_driver_price_tags =
new HashSet<ITag<OptionDriverPriceMap>>();
public SingleVolSurfaceOptionDriverSource(int vs_id,
IEnumerable<string> option_symbols,
ThreadedBlackboard threaded_bb) {
_vs_id = vs_id;
bts.Log.Gen.info($"SingleVolSurfaceOptionDriverSource cons vs_id:'{vs_id}' syms:'{option_symbols.Count()}'");
bts.Log.Gen.info($"SingleVolSurfaceOptionDriverSource cons vs_id:{vs_id} syms:{option_symbols.Count()}");
_threaded_bb = threaded_bb;
_out_bb_driver_price_tag = SparkTags.VolSurfaceOptionDriverTag(vs_id);
_out_bb_driver_symbol_price_tag = SparkTags.VolSurfaceDriverSymbolPriceTag(vs_id);
foreach (string o in option_symbols) {
var tag = SparkTags.OptionDriverBBOTag(o);
_option_driver_price_tags.Add(tag);
@@ -41,31 +34,40 @@ namespace mbts.spark {
}
_threaded_bb.data_callback += _on_bb_data;
_threaded_bb.timer_callback += _on_timer;
_publish_driver_prices();
}
private IDictionary<VolSurfaceExpiration, double> _get_driver_prices() {
var rv = new Dictionary<VolSurfaceExpiration, double>();
foreach (var tag in _option_driver_price_tags) {
OptionDriverPriceMap price_map = _threaded_bb.read_state(tag);
if (price_map == null) {
continue;
}
foreach (var kv in price_map.exp_price_map) {
Tuple<SecurityImmutable, VolSurfaceBBOUnit> driver_bbo = kv.Value;
rv[new VolSurfaceExpiration(kv.Key)] = driver_bbo.Item2.get_mid_price();
}
}
return rv;
}
private void _publish_driver_prices() {
var map = _get_driver_prices();
_log_output(_vs_id, map);
_threaded_bb.post(_out_bb_driver_price_tag, map);
}
private void _on_bb_data(object tag, object data) {
if (tag != null) {
if (_option_driver_price_tags.Contains(tag)) {
OptionDriverPriceMap price_map = data as OptionDriverPriceMap;
foreach (var kv in price_map.exp_price_map) {
SecurityExpiration option_exp = kv.Key;
Tuple<SecurityImmutable, VolSurfaceBBOUnit> driver_bbo = kv.Value;
_option_driver_price_map[new VolSurfaceExpiration() {
symbol = price_map.option_symbol,
expiration = option_exp.expiration
}] =
driver_bbo.Item2.get_mid_price();
}
_option_driver_dirty = true;
}
if (_option_driver_price_tags.Contains(tag)) {
_option_driver_dirty = true;
}
}
void _log_output() {
string log_txt = String.Format("SingleVolSurfaceOptionDriverSource vs_id:{0} data:",
_vs_id);
foreach (var kv in _option_driver_price_map) {
log_txt += " " + kv.Key + ":" + kv.Value;
static void _log_output(int vs_id, IDictionary<VolSurfaceExpiration, double> d_map) {
string log_txt = $"SingleVolSurfaceOptionDriverSource vs_id:{0} data: ";
foreach (var kv in d_map) {
log_txt += kv.Key + ":" + kv.Value + ",";
}
bts.Log.Gen.info(log_txt);
}
@@ -73,10 +75,7 @@ namespace mbts.spark {
private void _on_timer() {
if (_option_driver_dirty) {
_option_driver_dirty = false;
//bts.Log.Gen.info($"SingleVolSurfaceOptionDriverSource vs_id:{_vs_id} publishing sz:{_option_driver_price_map.Count()}");
_log_output();
_threaded_bb.post(_out_bb_driver_price_tag,
new Dictionary<VolSurfaceExpiration, double>(_option_driver_price_map));
_publish_driver_prices();
}
}
@@ -30,7 +30,8 @@ namespace mbts.spark {
/// data
private VolSurfaceOutput _last_output;
public SingleVolSurfaceRequestCalculator(int vs_id, IEnumerable<string> symbols, ThreadedBlackboard threaded_bb) {
public SingleVolSurfaceRequestCalculator(int vs_id, IEnumerable<string> symbols,
ThreadedBlackboard threaded_bb) {
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator cons vs_id:{vs_id}");
_vs_id = vs_id;
_symbols = new HashSet<string>(symbols);
@@ -70,30 +71,36 @@ namespace mbts.spark {
effective_req = curr_req;
else {
if (_last_output != null)
effective_req = new VolSurfaceCalculationRequest(_last_output.volsurface_input, curr_req.request_id);
effective_req =
new VolSurfaceCalculationRequest(_last_output.volsurface_input, curr_req.request_id);
}
if (effective_req != null) {
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map =
VolSurfaceUtilityFunctions.compute_aux_data(effective_req.volsurface_input,
nonvol_data.input, nonvol_data.driver_price_map, vs_standard_time, true);
IDictionary<VolSurfaceExpiration, VolCurveAction> action_map = _post_process_action(effective_req, aux_data_map);
nonvol_data.input,
nonvol_data.driver_price_map,
vs_standard_time, true);
IDictionary<VolSurfaceExpiration, VolCurveAction> action_map =
_post_process_action(effective_req, aux_data_map);
_last_output = GeneralVolSurfaceCalculator.compute(effective_req.volsurface_input,
nonvol_data.contracts,
aux_data_map,
action_map,
null,
effective_req.cascade_up, effective_req.cascade_down);
effective_req.cascade_up,
effective_req.cascade_down);
_timer.stop();
bts.Log.Gen.info(String.Format("SingleVolSurfaceRequestCalculator. Time to compute vol for {0} exps {1} msecs",
nonvol_data.contracts.Count, _timer.lastIntervalTime));
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator._recompute_and_publish time:" +
$"{_timer.lastIntervalTime} vs_output:{_last_output.log_string()}");
_bb.post(SparkTags.VolSurfaceCalculationResponseTag(_vs_id),
new VolSurfaceCalculationResponse(_last_output, effective_req.request_id));
new VolSurfaceCalculationResponse(_last_output, effective_req.request_id));
}
}
}
/// Computes the impl vol if the action is fit to market
private IDictionary<VolSurfaceExpiration, VolCurveAction> _post_process_action(VolSurfaceCalculationRequest req,
private IDictionary<VolSurfaceExpiration, VolCurveAction> _post_process_action(
VolSurfaceCalculationRequest req,
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map) {
IDictionary<VolSurfaceExpiration, VolCurveAction> rv = req.action_map;
/// TODO : VolCurveAction needs to be structured better. The UI enforces that
@@ -103,7 +110,8 @@ namespace mbts.spark {
VolCurveAction rep_action = rv.ElementAt(0).Value;
if (rep_action.action_type == VolCurveAction.ActionType.FitToMarket) {
IDictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData> impl_vol_map =
_fill_in_implied_vols(req.volsurface_input, req.action_map, aux_data_map, req.cascade_up, req.cascade_down);
_fill_in_implied_vols(req.volsurface_input, req.action_map, aux_data_map,
req.cascade_up, req.cascade_down);
rv = impl_vol_map.ToDictionary(kv => kv.Key, kv => new VolCurveAction(
new VolCurveMarketFitAction(rep_action.market_fit_action.fit_action, kv.Value,
rep_action.market_fit_action.use_weighted_regression)));
@@ -112,29 +120,36 @@ namespace mbts.spark {
return rv;
}
private IDictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData> _fill_in_implied_vols(VolSurfaceInput vs_inp,
private IDictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData> _fill_in_implied_vols(
VolSurfaceInput vs_inp,
IDictionary<VolSurfaceExpiration, VolCurveAction> action_map,
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map,
bool cascade_up, bool cascade_down) {
IDictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData> rv = new Dictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData>();
IDictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData> rv =
new Dictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData>();
VolCurveAction rep_action = action_map.ElementAt(0).Value;
HashSet<VolSurfaceExpiration> master_exps = VolSurfaceUtilityFunctions.get_master_expirations(vs_inp, true);
HashSet<VolSurfaceExpiration> master_exps =
VolSurfaceUtilityFunctions.get_master_expirations(vs_inp, true);
IEnumerable<VolSurfaceExpiration> applicable_exps;
if (cascade_up || cascade_down)
applicable_exps = VolSurfaceUtilityFunctions.get_exp_list_from_cascade(vs_inp.surface_parameters.curve_parameters_map.Select(t => t.Item1),
action_map.Keys, cascade_up, cascade_down);
applicable_exps =
VolSurfaceUtilityFunctions.get_exp_list_from_cascade(
vs_inp.surface_parameters.curve_parameters_map.Select(t => t.Item1),
action_map.Keys, cascade_up, cascade_down);
else
applicable_exps = action_map.Keys;
applicable_exps = applicable_exps.Where(vs_exp => master_exps.Contains(vs_exp));
VolSurfaceEnums.MarketSide impliedvol_side = SingleVolSurfaceMarketImpliedVolSource._get_market_impliedvol_side(_bb, _vs_id);
VolSurfaceEnums.MarketSide impliedvol_side =
SingleVolSurfaceMarketImpliedVolSource._get_market_impliedvol_side(_bb, _vs_id);
foreach (VolSurfaceExpiration vs_exp in applicable_exps) {
VolSurfaceExpiration md_exp;
VolCurveMarketImpliedVolData exp_impl_data =
VolSurfaceCoreFunctions.compute_implied_vols(vs_inp, vs_exp, aux_data_map,
arg_vs_exp => SingleVolSurfaceMarketImpliedVolSource._get_bbo(_bb, arg_vs_exp),
impliedvol_side,
SingleVolSurfaceMarketImpliedVolSource._ignore_market_implied_vol_source_settings(_bb, _vs_id),
SingleVolSurfaceMarketImpliedVolSource._ignore_market_implied_vol_source_settings(
_bb, _vs_id),
out md_exp);
rv[vs_exp] = exp_impl_data;
}
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts.analytics;
@@ -10,7 +6,7 @@ namespace mbts.spark {
public class SingleVolSurfaceTimeSource : IDisposable {
private readonly int _vs_id;
private readonly ThreadedBlackboard _bb;
private TimeSpan _publish_period = TimeSpan.FromMinutes(VolSurfaceConstants.vol_time_sample_mins);
private readonly TimeSpan _publish_period = TimeSpan.FromMinutes(VolSurfaceConstants.vol_time_sample_mins);
private DateTime _last_publish_time = DateTime.MinValue;
public SingleVolSurfaceTimeSource(int vs_id, ThreadedBlackboard bb) {
@@ -35,4 +31,4 @@ namespace mbts.spark {
}
#endregion
}
}
}
@@ -59,17 +59,21 @@ namespace mbts.spark {
private readonly ITag<IReadOnlyDictionary<uint, SecurityMD>> _in_sec_tag = SparkTags.SecuritiesTag;
private readonly ITag<VolSurfaceSettings> _in_bb_create_tag = SparkTags.VolSurfaceCreateTag;
private readonly ITag<int> _in_bb_delete_tag = SparkTags.VolSurfaceDeleteTag;
private readonly ITag<AnalyticsExpirationParametersMap> _in_bb_exp_params_tag = SparkTags.ExpirationParametersInputTag;
private readonly ITag<AnalyticsExpirationParametersMap> _in_bb_exp_params_tag =
SparkTags.ExpirationParametersInputTag;
// state
private SystemContractData _contract_data = null;
private IDictionary<int, SingleVolSurfaceManager> _vs_manager_map = new Dictionary<int, SingleVolSurfaceManager>();
private Queue<mbts.analytics.VolSurfaceSettings> _waiting_creations = new Queue<mbts.analytics.VolSurfaceSettings>();
private IDictionary<int, SingleVolSurfaceManager> _vs_manager_map =
new Dictionary<int, SingleVolSurfaceManager>();
private Queue<mbts.analytics.VolSurfaceSettings> _waiting_creations =
new Queue<mbts.analytics.VolSurfaceSettings>();
private bts.api.IBus _bus;
private List<IDisposable> _subs = new List<IDisposable>();
private HighPerformanceTimer _timer = new HighPerformanceTimer();
public VolSurfaceBlackboardManager(bts.api.IBus bus,
bts.api.analytics.AnalyticsService analytics_service) {
bts.Log.Ui.info("VSBusManager cons tid:{VolSurfaceTroubleshootingFunctions.tid()}");
_bus = bus;
_bb = new ThreadedBlackboard(bus);
_analytics_service = analytics_service;
@@ -122,8 +126,8 @@ namespace mbts.spark {
// (will take care of it later)
foreach (var vs_id in vs_ids) {
if (!_vs_manager_map.ContainsKey(vs_id)) {
_vs_manager_map[vs_id] = new SingleVolSurfaceManager(
vs_id, _bb, _analytics_service);
_vs_manager_map.Add(vs_id, new SingleVolSurfaceManager(
vs_id, _bb, _analytics_service));
}
}
}
@@ -151,8 +155,9 @@ namespace mbts.spark {
_analytics_service.delete_volsurface(vs_id_w);
} catch (Exception ex) {
Log.Gen.error(String.Format("Vol Surface deletion failed with exception:{0}", ex.Message));
_bb.post(SparkTags.MessageDisplayTag, new MessageDisplayData("Vol Surface Deletion",
String.Format("Could not delete Vol Surface, Error : {0}", ex.Message)));
_bb.post(SparkTags.MessageDisplayTag,
new MessageDisplayData("Vol Surface Deletion",
String.Format("Could not delete Vol Surface, Error : {0}", ex.Message)));
}
} else if (_in_bb_exp_params_tag.Equals(tag)) {
AnalyticsExpirationParametersMap exp_param_map = data as AnalyticsExpirationParametersMap;
@@ -0,0 +1,13 @@
namespace mbts.spark {
enum AxisPosition {
None,
TopLeftToRight,
TopRightToLeft,
BottomLeftToRight,
BottomRightToLeft,
LeftTopToBottom,
LeftBottomToTop,
RightTopToBottom,
RightBottomToTop
}
}
@@ -0,0 +1,12 @@
namespace mbts.spark {
enum DateTimeIntervalType {
Auto,
Seconds,
Minutes,
Hours,
Days,
Weeks,
Months,
Years
}
}
+22
View File
@@ -0,0 +1,22 @@
namespace mbts.spark {
using mbts.ui.shell;
/// ** BTSGraphPoint in edge **
/// <summary>
/// Represents a point in a graph
/// </summary>
class GraphPointVM : ViewModelBase {
object _x;
object _y;
public GraphPointVM() { }
public GraphPointVM(object x, object y) {
this.x = x;
this.x = y;
}
public object x { get => _x; set => Set(ref _x, value); }
public object y { get => _y; set => Set(ref _y, value); }
}
}
@@ -0,0 +1,9 @@
namespace mbts.spark {
using System;
using System.Collections.Generic;
interface IVolTermsSeries {
bool is_committed { get; }
void update_points(IReadOnlyDictionary<DateTime, double> vol_map);
}
}
@@ -0,0 +1,36 @@
namespace mbts.spark {
using mbts.ui;
using ProtoBuf;
using System;
[ProtoContract]
class LineSeriesSettings : IEquatable<LineSeriesSettings>, ICloneable {
[ProtoMember(1)]
public LineStyle line_style { get; set; }
[ProtoMember(2)]
public double stroke_thickness { get; set; }
[ProtoMember(3)]
public BTSColor color { get; set; }
public object Clone() =>
new LineSeriesSettings {
line_style = line_style,
stroke_thickness = stroke_thickness,
color = color.clone()
};
public bool Equals(LineSeriesSettings other) =>
other != null &&
line_style == other.line_style &&
stroke_thickness.Equals(other.stroke_thickness) &&
color == other.color;
public override bool Equals(object obj) =>
Equals(obj as LineSeriesSettings);
public override int GetHashCode() =>
GetType().GetHashCode();
}
}
+16
View File
@@ -0,0 +1,16 @@
namespace mbts.spark {
enum LineStyle {
None,
Solid,
Dashed,
Dot,
DashDot,
DashDashDot,
DashDotDot,
DashDashDotDot,
LongDash,
LongDashDot,
LongDashDotDot,
Automatic
};
}
+11
View File
@@ -0,0 +1,11 @@
namespace mbts.spark {
enum MarkerShape {
None,
Circle,
Cross, Diamond,
Plus,
Square,
Star,
Triangle
}
}
@@ -0,0 +1,44 @@
namespace mbts.spark {
using mbts.ui;
using ProtoBuf;
using System;
[ProtoContract]
class ScatterSeriesSettings : IEquatable<ScatterSeriesSettings>, ICloneable {
public ScatterSeriesSettings() { }
public ScatterSeriesSettings(MarkerShape shape, double size, BTSColor color) {
this.shape = shape;
this.size = size;
this.color = color;
}
[ProtoMember(1)]
public MarkerShape shape { get; set; }
[ProtoMember(2)]
public double size { get; set; }
[ProtoMember(3)]
public BTSColor color { get; set; }
public object Clone() =>
new ScatterSeriesSettings {
shape = shape,
size = size,
color = color.clone()
};
public bool Equals(ScatterSeriesSettings other) =>
other != null &&
shape == other.shape &&
size.Equals(other.size) &&
color == other.color;
public override bool Equals(object obj) =>
Equals(obj as ScatterSeriesSettings);
public override int GetHashCode() =>
GetType().GetHashCode();
}
}
@@ -0,0 +1,40 @@
namespace mbts.spark {
using bts.collections;
using mbts.ui;
using System;
using System.Collections.Generic;
using System.Linq;
/// ** VolTermsLineSeries in edge **
/// <summary>
/// Represents a scatter series in a graph
/// </summary>
class VolTermsLineSeriesVM : LineSeriesVM, IVolTermsSeries {
bool _is_committed;
// public VolTermsLineSeriesVM(bool is_committed) {
// this.is_committed = is_committed;
// name = is_committed ? "Committed" : "Candidate";
// is_visible = true;
// color = BTSColors.VolSurfaceGraph.main_curve;
// line_style = is_committed ? LineStyle.Solid : LineStyle.Dashed;
// stroke_thickness = 1.5;
// }
public bool is_committed {
get => _is_committed;
set {
if (Set(ref _is_committed, value)) {
name = value ? "Committed" : "Candidate";
}
}
}
public void update_points(IReadOnlyDictionary<DateTime, double> vol_map) =>
points.SetItems(vol_map
.Where(kv => !double.IsNaN(kv.Value))
.OrderBy(kv => kv.Key)
.Select(kv => new GraphPointVM(OxyPlot.Axes.DateTimeAxis.ToDouble(kv.Key), kv.Value)));
}
}
@@ -0,0 +1,37 @@
namespace mbts.spark {
using bts.collections;
using mbts.ui;
using System;
using System.Collections.Generic;
using System.Linq;
class VolTermsScatterSeriesVM : ScatterSeriesVM, IVolTermsSeries {
bool _is_committed;
// public VolTermsScatterSeriesVM(bool is_committed) {
// this.is_committed = is_committed;
// name = is_committed ? "Committed" : "Candidate";
// is_visible = true;
// marker_color = BTSColors.VolSurfaceGraph.main_curve_atm;
// marker_shape = MarkerShape.Circle;
// marker_size = 3.0;
// }
public bool is_committed {
get => _is_committed;
set {
if (Set(ref _is_committed, value)) {
name = value ? "Committed" : "Candidate";
}
}
}
public void update_points(IReadOnlyDictionary<DateTime, double> vol_map) =>
points.SetItems(vol_map
.Where(kv => !double.IsNaN(kv.Value))
.OrderBy(kv => kv.Key)
.Select(kv => new GraphPointVM(OxyPlot.Axes.DateTimeAxis.ToDouble(kv.Key), kv.Value)));
}
}
@@ -24,6 +24,11 @@ namespace mbts.ui.controls
header_font_weight = System.Drawing.FontStyle.Bold;
wpf_width = Double.NaN;
}
internal BTSTabularGridColumnConfiguration(mbts.ui.settings.GridColumnSettings settings) {
/// TODO (maybe): need to resolve diffs between this class and <see cref="mbts.ui.settings.GridColumnSettings"/>
}
[ProtoMember(1)]
public string name { get; set; }
[ProtoMember(2)]
@@ -10,11 +10,9 @@ using mbts.ui.shell;
using mbts.spark;
using bts.utils;
namespace mbts.ui.controls
{
namespace mbts.ui.controls {
/// Encapsulates the vol data that would show up in the top grid
public class VolSurfaceDisplayGrid : ICloneable, IGridDisplayModel<VolSurfaceDisplayGridExpiration,VolSurfaceDisplayGridColumn>, ICellDataStore<VolSurfaceDisplayGridExpiration, IDataGridDisplayModelColumn, string>
{
public class VolSurfaceDisplayGrid : ICloneable, IGridDisplayModel<VolSurfaceDisplayGridExpiration, VolSurfaceDisplayGridColumn>, ICellDataStore<VolSurfaceDisplayGridExpiration, IDataGridDisplayModelColumn, string> {
private readonly IEnumerable<VolSurfaceDisplayGridExpiration> _ordered_expirations = null;
private readonly IEnumerable<VolSurfaceDisplayGridColumn> _ordered_columns = null;
private readonly IDictionary<string, VolSurfaceDisplayGridColumn> _column_map;
@@ -30,35 +28,36 @@ namespace mbts.ui.controls
}).ToArray());
}
public IDictionary<VolSurfaceDisplayGridExpiration, IDictionary<VolSurfaceDisplayGridColumn, object>> data_map {
get {
return _data_map;
}
}
public VolSurfaceDisplayGrid(IEnumerable<VolSurfaceDisplayGridExpiration> ordered_expirations,
IEnumerable<VolSurfaceDisplayGridColumn> ordered_columns,
IDictionary<VolSurfaceDisplayGridExpiration, IDictionary<VolSurfaceDisplayGridColumn, object>> data)
{
IDictionary<VolSurfaceDisplayGridExpiration, IDictionary<VolSurfaceDisplayGridColumn, object>> data) {
_ordered_expirations = ordered_expirations;
_ordered_columns = ordered_columns;
_data_map = data;
_column_map = ordered_columns.ToDictionary(k => k.unique_col_name, k => k);
}
public object get_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, object default_value)
{
public object get_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, object default_value) {
object rv = default_value;
return get_grid_data(exp, col, out rv) ? rv : default_value;
}
public bool get_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, out object data)
{
public bool get_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, out object data) {
data = null;
IDictionary<VolSurfaceDisplayGridColumn, object> exp_data;
if (_data_map.TryGetValue(exp, out exp_data))
if (exp_data.TryGetValue(col, out data))
return true;
return false;
}
}
public bool copy(VolSurfaceDisplayGridExpiration source_exp, VolSurfaceDisplayGridTextInputColumn source_col,
VolSurfaceDisplayGridExpiration target_exp, VolSurfaceDisplayGridTextInputColumn target_col)
{
VolSurfaceDisplayGridExpiration target_exp, VolSurfaceDisplayGridTextInputColumn target_col) {
object data;
if (get_grid_data(source_exp, source_col, out data))
return set_grid_data(target_exp, target_col, data);
@@ -68,18 +67,16 @@ namespace mbts.ui.controls
#region Comparison Helpers
/// Returns the expiration differences
public static void compare_exps(VolSurfaceDisplayGrid new_grid, VolSurfaceDisplayGrid old_grid,
out IEnumerable<VolSurfaceDisplayGridExpiration> deleted, out IEnumerable<VolSurfaceDisplayGridExpiration> added)
{
out IEnumerable<VolSurfaceDisplayGridExpiration> deleted, out IEnumerable<VolSurfaceDisplayGridExpiration> added) {
HashSet<VolSurfaceDisplayGridExpiration> new_grid_map = new HashSet<VolSurfaceDisplayGridExpiration>(new_grid.get_ordered_expirations()),
old_grid_map = new HashSet<VolSurfaceDisplayGridExpiration>(old_grid.get_ordered_expirations()),
del, add;
CollectionHelper.compare_hashsets(new_grid_map, old_grid_map, out del, out add);
CollectionHelper.compare_hashsets(new_grid_map, old_grid_map, out del, out add);
deleted = del;
added = add;
}
public static bool cols_changed(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2)
{
public static bool cols_changed(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2) {
IEnumerable<VolSurfaceDisplayGridColumn> d1_extra, d2_extra;
compare_cols(d1, d2, out d1_extra, out d2_extra);
return d1_extra.Count() > 0 || d2_extra.Count() > 0;
@@ -88,8 +85,7 @@ namespace mbts.ui.controls
/// Returns the col name differences (it will generally be very rare, but for instance when a point gets added
/// to a polynomial or the spline model, d1 or d2 wont be empty)
public static void compare_cols(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2,
out IEnumerable<VolSurfaceDisplayGridColumn> d1_extra, out IEnumerable<VolSurfaceDisplayGridColumn> d2_extra)
{
out IEnumerable<VolSurfaceDisplayGridColumn> d1_extra, out IEnumerable<VolSurfaceDisplayGridColumn> d2_extra) {
HashSet<VolSurfaceDisplayGridColumn> d1_exp_map = new HashSet<VolSurfaceDisplayGridColumn>(d1.get_ordered_columns()),
d2_exp_map = new HashSet<VolSurfaceDisplayGridColumn>(d2.get_ordered_columns()),
del, add;
@@ -104,12 +100,10 @@ namespace mbts.ui.controls
/// Returns the differernce between two VolSurfaceDisplay's.
/// It only returns the elements that are present in both
/// and are different.
public static IEnumerable<Tuple<VolSurfaceDisplayGridExpiration, VolSurfaceDisplayGridColumn>> compare_data(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2)
{
List<Tuple<VolSurfaceDisplayGridExpiration, VolSurfaceDisplayGridColumn>> rv = new List<Tuple<VolSurfaceDisplayGridExpiration,VolSurfaceDisplayGridColumn>> ();
foreach (VolSurfaceDisplayGridExpiration exp in CollectionHelper.append_arrays (d1.get_ordered_expirations(), d2.get_ordered_expirations()))
foreach (VolSurfaceDisplayGridColumn col in CollectionHelper.append_arrays(d1.get_ordered_columns(), d2.get_ordered_columns()))
{
public static IEnumerable<Tuple<VolSurfaceDisplayGridExpiration, VolSurfaceDisplayGridColumn>> compare_data(VolSurfaceDisplayGrid d1, VolSurfaceDisplayGrid d2) {
List<Tuple<VolSurfaceDisplayGridExpiration, VolSurfaceDisplayGridColumn>> rv = new List<Tuple<VolSurfaceDisplayGridExpiration, VolSurfaceDisplayGridColumn>>();
foreach (VolSurfaceDisplayGridExpiration exp in CollectionHelper.append_arrays(d1.get_ordered_expirations(), d2.get_ordered_expirations()))
foreach (VolSurfaceDisplayGridColumn col in CollectionHelper.append_arrays(d1.get_ordered_columns(), d2.get_ordered_columns())) {
object d1_data, d2_data;
if (d1.get_grid_data(exp, col, out d1_data) && d2.get_grid_data(exp, col, out d2_data) && d1 != d2)
rv.Add(Tuple.Create(exp, col));
@@ -119,11 +113,10 @@ namespace mbts.ui.controls
#endregion
#region ICloneable
public object Clone()
{
Dictionary<VolSurfaceDisplayGridExpiration, IDictionary<VolSurfaceDisplayGridColumn, object>> data = new Dictionary<VolSurfaceDisplayGridExpiration,IDictionary<VolSurfaceDisplayGridColumn,object>> ();
public object Clone() {
Dictionary<VolSurfaceDisplayGridExpiration, IDictionary<VolSurfaceDisplayGridColumn, object>> data = new Dictionary<VolSurfaceDisplayGridExpiration, IDictionary<VolSurfaceDisplayGridColumn, object>>();
foreach (KeyValuePair<VolSurfaceDisplayGridExpiration, IDictionary<VolSurfaceDisplayGridColumn, object>> p in _data_map)
data.Add (p.Key, new Dictionary<VolSurfaceDisplayGridColumn, object> (p.Value));
data.Add(p.Key, new Dictionary<VolSurfaceDisplayGridColumn, object>(p.Value));
return new VolSurfaceDisplayGrid(new List<VolSurfaceDisplayGridExpiration>(_ordered_expirations),
new List<VolSurfaceDisplayGridColumn>(_ordered_columns),
data);
@@ -137,12 +130,10 @@ namespace mbts.ui.controls
#endregion
#region ICellDataStore
public string read(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col)
{
public string read(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col) {
VolSurfaceDisplayGridColumn grid_col = col as VolSurfaceDisplayGridColumn;
grid_col = grid_col != null ? (_column_map.TryGetValue(grid_col.unique_col_name, out grid_col) ? grid_col : null) : null;
if (grid_col != null)
{
if (grid_col != null) {
object value;
if (get_grid_data(row, grid_col, out value))
return grid_col.format(value);
@@ -150,29 +141,24 @@ namespace mbts.ui.controls
return string.Empty;
}
public bool write(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, string value)
{
public bool write(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, string value) {
VolSurfaceDisplayGridTextInputColumn grid_col = col as VolSurfaceDisplayGridTextInputColumn;
return grid_col != null ? set_grid_data(row, grid_col, grid_col.parse(value)) : false;
}
public object get_display_info(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col)
{
public object get_display_info(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col) {
return null; // ??
//return read(row, col);
}
public void handle_tick(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, TickDirection tick, out string new_value)
{
public void handle_tick(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, TickDirection tick, out string new_value) {
VolSurfaceDisplayGridColumn mapped_col = col as VolSurfaceDisplayGridColumn;
mapped_col = mapped_col != null ? (_column_map.TryGetValue(mapped_col.unique_col_name, out mapped_col) ? mapped_col : null) : null;
VolSurfaceDisplayGridTextInputColumn grid_col = mapped_col as VolSurfaceDisplayGridTextInputColumn;
new_value = String.Empty;
if (grid_col != null)
{
new_value = String.Empty;
if (grid_col != null) {
object data;
if (get_grid_data(row, grid_col, out data))
{
if (get_grid_data(row, grid_col, out data)) {
data = grid_col.tick_move(data, tick == TickDirection.UP);
new_value = grid_col.format(data);
set_grid_data(row, grid_col, data);
@@ -180,29 +166,49 @@ namespace mbts.ui.controls
}
}
public bool can_tick(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, TickDirection tick)
{
public bool can_tick(VolSurfaceDisplayGridExpiration row, IDataGridDisplayModelColumn col, TickDirection tick) {
return true;
}
#endregion
internal void set_grid_data_text(VolSurfaceDisplayGridExpiration exp, string col_name, string formatted_data)
{
internal void set_grid_data_text(VolSurfaceDisplayGridExpiration exp, string col_name, string formatted_data) {
VolSurfaceDisplayGridColumn grid_col;
if (_column_map.TryGetValue(col_name, out grid_col))
write(exp, grid_col, formatted_data);
}
internal bool set_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, object data)
{
internal bool set_grid_data(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn col, object data) {
IDictionary<VolSurfaceDisplayGridColumn, object> exp_data;
if (_data_map.TryGetValue(exp, out exp_data))
if (exp_data.ContainsKey(col))
{
if (exp_data.ContainsKey(col)) {
exp_data[col] = data;
return true;
}
return false;
}
// internal string log_string {
// get {
// Func<string, string> trim_leading_comma = (s) => {
// if (!s.IsNullOrEmpty() && s.EndsWith(",")) {
// return s.Remove(s.Length - 1, 1);
// }
// return s;
// };
// Func<IDictionary<VolSurfaceDisplayGridColumn, object>, string> log_exp = (map) => {
// string rv = String.Empty;
// foreach (var kv in map) {
// string val_string = kv.Value == null ? "Null" : kv.Value.ToString();
// rv += $"{kv.Key.display_name}:{val_string},";
// }
// return trim_leading_comma(rv);
// };
// string rv = String.Empty;
// foreach (var kv in _data_map) {
// rv += $"Exp:{kv.Key.expiration.ToShortDateString()} Data:{log_exp(kv.Value)},";
// }
// return trim_leading_comma(rv);
// }
// }
}
}
@@ -4,28 +4,22 @@ using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.ui.controls
{
public class VolSurfaceDisplayUtilities
{
public static double parse_double(object obj)
{
namespace mbts.ui.controls {
class VolSurfaceDisplayUtilities {
public static double parse_double(object obj) {
obj = obj ?? Double.NaN;
double rv = obj is Double ? (double)obj : (Double.TryParse(obj.ToString(), out rv) ? rv : Double.NaN);
return rv;
}
public static bool parse_boolean(object obj, bool def_value)
{
public static bool parse_boolean(object obj, bool def_value) {
bool rv;
rv = Boolean.TryParse(obj == null ? String.Empty : obj.ToString(), out rv) ? rv : def_value;
return rv;
}
public static Func<string, object> get_parse_double(double multiplier)
{
return (text) =>
{
public static Func<string, object> get_parse_double(double multiplier) {
return (text) => {
double rv = Double.NaN;
rv = Double.TryParse(text, out rv) ? rv : Double.NaN;
rv /= multiplier;
@@ -33,45 +27,35 @@ namespace mbts.ui.controls
};
}
public static Func<object, string> get_double_tostring(double tick_base, double tick_interval, double multiplier)
{
return (data) =>
{
if (data != null && data is double)
{
public static Func<object, string> get_double_tostring(double tick_base, double tick_interval, double multiplier) {
return (data) => {
if (data != null && data is double) {
double d_data = (double)data;
d_data *= multiplier;
return Double.IsNaN(d_data) ? String.Empty : _to_string(d_data, tick_base, tick_interval);
}
else
} else
return String.Empty;
};
}
public static Func<object, bool, object> get_double_tickmove(double tick_base, double tick_move, double multiplier)
{
return (data, is_up) =>
{
if (data != null && data is double)
{
public static Func<object, bool, object> get_double_tickmove(double tick_base, double tick_move, double multiplier) {
return (data, is_up) => {
if (data != null && data is double) {
double d_data = (double)data;
d_data *= multiplier;
d_data = is_up ? d_data + (tick_move / tick_base) : d_data - (tick_move / tick_base);
d_data /= multiplier;
return d_data;
}
else
} else
return data;
};
}
public static VolSurfaceDisplayGridColumn get_double_output_col(string group, string name, string display_name,
double tick_base, double tick_interval, double multiplier,
VolSurfaceMacroGridSettings grid_settings)
{
VolSurfaceMacroGridSettings grid_settings) {
BTSTabularGridCellConfiguration col_config = _get_col_config(name, grid_settings);
if (col_config != null)
{
if (col_config != null) {
_assign(col_config.tick_base, ref tick_base);
_assign(col_config.tick_interval, ref tick_interval);
_assign(col_config.multiplier, ref multiplier);
@@ -79,15 +63,13 @@ namespace mbts.ui.controls
return new VolSurfaceDisplayGridTextOutputColumn(group, name, display_name, null,
get_double_tostring(tick_base, tick_interval, multiplier),
get_parse_double(multiplier));
}
}
public static VolSurfaceDisplayGridColumn get_double_input_col(string group, string name, string display_name,
double tick_base, double tick_interval, double tick_move, double multiplier,
VolSurfaceMacroGridSettings grid_settings)
{
VolSurfaceMacroGridSettings grid_settings) {
BTSTabularGridCellConfiguration col_config = _get_col_config(name, grid_settings);
if (col_config != null)
{
if (col_config != null) {
_assign(col_config.tick_base, ref tick_base);
_assign(col_config.tick_interval, ref tick_interval);
_assign(col_config.tick_move, ref tick_move);
@@ -99,20 +81,17 @@ namespace mbts.ui.controls
get_double_tickmove(tick_base, tick_move, multiplier));
}
private static BTSTabularGridCellConfiguration _get_col_config(string col_name, VolSurfaceMacroGridSettings grid_setting)
{
return grid_setting != null ? grid_setting.get_col_setting(col_name) : null;
private static BTSTabularGridCellConfiguration _get_col_config(string col_name, VolSurfaceMacroGridSettings grid_setting) {
return grid_setting != null ? grid_setting.get_cell_conf(col_name) : null;
}
private static string _to_string (double d, double tick_base, double tick_interval)
{
return d.ToString();
private static string _to_string(double d, double tick_base, double tick_interval) {
return d.ToString();
// TODO
// return TickConverter2.to_tick(d, new TickConverter2.TickTypeInfo(tick_base == 100.0, (int)tick_base, tick_interval, false));
}
private static void _assign(double d, ref double v)
{
private static void _assign(double d, ref double v) {
if (_is_valid(d)) v = d;
}
@@ -1,34 +1,43 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts;
using mbts.ui.controls;
using mbts.ui.shell;
namespace mbts.ui.controls {
using System;
using System.Collections.Generic;
using System.Linq;
namespace mbts.ui.controls
{
using mbts.ui.settings;
using mbts.ui.shell;
[ProtoBuf.ProtoContract()]
public class VolSurfaceMacroGridSettings : ICloneable
{
[ProtoBuf.ProtoMember(1)]
public BTSTabularGridConfiguration configuration { get; set; }
using ProtoBuf;
public object Clone() {
return ProtoBufSerializationHelper.clone_protobuf(this);
[ProtoContract]
class VolSurfaceMacroGridSettings : ICloneable {
public static VolSurfaceMacroGridSettings Default =>
new() {
configuration = new GridSettings()
};
[ProtoMember(1)]
public GridSettings configuration { get; set; }
/// This should be the same size as <see cref="GridSettings.columns"/>;
/// the cell configurations are associated with the
/// <see cref="GridColumnSettings"/> in the same corresponding index.
[ProtoMember(2)]
public List<BTSTabularGridCellConfiguration> cell_settings { get; } = new List<BTSTabularGridCellConfiguration>();
public GridColumnSettings get_col_setting(string col_name) =>
GridSettingsHelper.try_find_column(configuration.columns, col_name, out var res) ? res : null;
public BTSTabularGridCellConfiguration get_cell_conf(string col_name) {
if (cell_settings.Count != configuration.columns.Count) {
throw new InvalidOperationException(
$"{nameof(cell_settings)} doesn't have the same number of " +
$"elements as {nameof(configuration)}.${nameof(GridSettings.columns)}");
}
return GridSettingsHelper.try_find_column(configuration.columns, col_name, out var _, out var idx) ?
cell_settings[idx] : null;
}
private IDictionary<string, BTSTabularGridCellConfiguration> _col_setting_map = null;
public BTSTabularGridCellConfiguration get_col_setting(string col_name)
{
if (_col_setting_map == null)
_col_setting_map = configuration != null ? configuration.column_configurations.ToDictionary(c => c.name, c => c.cell_configuration) : new Dictionary<string, BTSTabularGridCellConfiguration>();
BTSTabularGridCellConfiguration rv = _col_setting_map.TryGetValue(col_name, out rv) ? rv : null;
return rv;
}
public object Clone() =>
ProtoBufSerializationHelper.clone_protobuf(this);
}
}
}
@@ -1,17 +1,17 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts.analytics;
using bts.api;
namespace mbts.spark {
// All driver prices for an option symbol
public class OptionDriverPriceMap {
public readonly String option_symbol = null;
public readonly IDictionary<SecurityExpiration, Tuple<SecurityImmutable, VolSurfaceBBOUnit>> exp_price_map = null;
public readonly IDictionary<SecurityExpiration, Tuple<SecurityImmutable, VolSurfaceBBOUnit>>
exp_price_map = null;
public OptionDriverPriceMap(string option_symbol_a,
IDictionary<SecurityExpiration, Tuple<SecurityImmutable, VolSurfaceBBOUnit>> exp_price_map_a) {
IDictionary<SecurityExpiration, Tuple<SecurityImmutable, VolSurfaceBBOUnit>>
exp_price_map_a) {
option_symbol = option_symbol_a;
exp_price_map = exp_price_map_a;
}
@@ -167,6 +167,11 @@ namespace mbts.spark {
.ToDictionary(kv => kv.Key.expiration, kv => kv.Value.Select(k => k.strike));
}
public IDictionary<SecurityExpiration, IEnumerable<double>> get_option_strikes(HashSet<string> option_names) {
return strike_map.Where(kv => option_names.Contains(kv.Key.symbol))
.ToDictionary(kv => kv.Key, kv => kv.Value.Select(k => k.strike));
}
public Nullable<UInt32> get_exp_sec_id(SecurityExpiration sec_exp) {
UInt32 rv;
if (exp_map.TryGetValue(sec_exp, out rv)) {
@@ -21,14 +21,16 @@ namespace mbts.spark {
/// </summary>
public class ThreadedBlackboard {
private IBus _bus;
//public delegate void OnBBData(object tag, object data);
private List<IDisposable> _subs = new List<IDisposable>();
private HashSet<object> _tag_map = new HashSet<object>();
public event Action<object, object> data_callback = (t, v) => { };
public event Action timer_callback = () => { };
private IDictionary<object, object> _cache = new
Dictionary<object, object>();
private static int _tid() {return VolSurfaceTroubleshootingFunctions.tid();}
public ThreadedBlackboard(IBus bus) {
bts.Log.Ui.info($"ThreadedBlackBoard.cons tid:{ _tid()}");
_bus = bus;
subscribe(SparkTags.SparkTimer);
System.Threading.Thread timer_thread = new System.Threading.Thread(() => {
@@ -46,20 +48,40 @@ namespace mbts.spark {
#region Templatized sub/write
public void subscribe<T>(ITag<T> tag) {
if (_tag_map.Contains(tag)) {
return;
}
_tag_map.Add(tag);
bts.Log.Ui.info($"ThreadedBlackBoard.subscribe tag:{tag} tid:{ _tid()}");
var observable = _bus.subscribe(tag).OnDispatcher().Subscribe(
data => _on_bus_data(tag, data));
_subs.Add(observable);
}
private static string _data_string<T>(T data) {
string rv = "Null";
try {
rv = data.ToString();
} catch (Exception ex) {
bts.Log.Ui.error($"ThreadedBlackBoard data:Null ex:{ex.Message}");
}
return rv;
}
public void post<T>(ITag<T> tag, T data, bool block_until_written = false) {
bts.Log.Ui.info($"ThreadedBlackBoard.post tag:{tag} data:{_data_string(data)} " +
$"tid:{_tid()}");
_cache[tag] = data;
_bus.post(tag, data);
}
private void _on_bus_data<T>(ITag<T> tag, T data) {
_cache[tag] = data;
if (tag == SparkTags.SparkTimer) {
timer_callback();
return;
}
bts.Log.Ui.info($"ThreadedBlackBoard._on_bus_data tag:{tag} data:{_data_string(data)} " +
$"tid:{_tid()}");
data_callback(tag, data);
}
#endregion
@@ -0,0 +1,109 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using mbts;
using mbts.analytics;
using mbts.ui.controls;
using mbts.ui.shell;
using mbts.spark;
using bts.utils;
using bts.api;
namespace mbts.spark {
/// This contains the list of global values for the vol
/// surface (whereas VolSurfaceDisplayGrid has exp keyed
/// values)
public static class VolSurfaceTroubleshootingFunctions {
public static string log_string(this VolSurfaceInput vs_inp) {
string rv = "Null";
if (vs_inp.surface_parameters != null && vs_inp.surface_parameters.curve_parameters_map != null) {
rv = String.Empty;
foreach (var kv in vs_inp.surface_parameters.curve_parameters_map) {
var exp = kv.Item1;
var exp_data = kv.Item2;
double atm_vol = VolSurfaceDataFunctions.get_atm_vol(vs_inp.surface_settings, exp_data);
rv += $"exp:{exp.expiration.ToShortDateString()} atm_vol:{atm_vol} \n";
}
}
return rv;
}
public static string log_string(this VolSurfaceOutput vs_out) {
if (vs_out == null) {
return "Null";
}
var vs_inp = vs_out.volsurface_input;
string rv = "vs_inp:" + vs_inp == null ? "Null" : vs_inp.log_string() + "\n";
rv += "vs_output:" + "\n";
if (vs_out.exp_output_map != null) {
foreach (var exp_kv in vs_out.exp_output_map) {
var exp = exp_kv.Key;
var exp_output = exp_kv.Value;
foreach (var vol in exp_output.strike_vol_map) {
rv += $"{exp},{vol.Key}:{vol.Value}" + ",";
}
rv += "\n";
}
}
return rv;
}
private static string _trim_leading_char(string s, char c) {
if (!s.IsNullOrEmpty() && s.EndsWith(c)) {
return s.Remove(s.Length - 1, 1);
}
return s;
}
internal static string log_string(this VolSurfaceDisplayModel.DisplayModelData dm_data) {
string rv = String.Empty;
string global_grid_str = dm_data.global_grid == null ? "Null" : dm_data.global_grid.log_string();
rv += $"global_grid: {global_grid_str} \n";
string exp_grid_str = dm_data.exp_grid == null ? "Null" : dm_data.exp_grid.log_string();
rv += $"exp_grid: {exp_grid_str} \n";
return rv;
}
public static string log_string(this VolSurfaceDisplayGlobalGrid ggrid) {
string rv = String.Empty;
foreach (var col in ggrid.get_ordered_columns()) {
object col_data = null;
ggrid.get_grid_data(col, out col_data);
string col_data_str = col_data == null ? "Null" : col_data.ToString();
rv += $"{col.display_name}:{col_data_str} ";
}
return rv;
}
internal static string log_string(this VolSurfaceDisplayGrid dgrid) {
Func<IDictionary<VolSurfaceDisplayGridColumn, object>, string> log_exp = (map) => {
string rv = String.Empty;
foreach (var kv in map) {
string val_string = kv.Value == null ? "Null" : kv.Value.ToString();
rv += $"{kv.Key.display_name}:{val_string},";
}
return _trim_leading_char(rv, ',');
};
string rv = String.Empty;
foreach (var kv in dgrid.data_map) {
rv += $"Exp:{kv.Key.expiration.ToShortDateString()} Data:{log_exp(kv.Value)},";
}
return _trim_leading_char(rv, ',');
}
internal static string log_string(this OptionDriverPriceMap map) {
string rv = String.Empty;
foreach (var kv in map.exp_price_map) {
var t = kv.Value;
rv += $"{kv.Key.ToString()}:{t.Item1.Id},{t.Item2.get_mid_price()},";
}
return _trim_leading_char(rv, ',');
}
internal static int tid() {
return System.Threading.Thread.CurrentThread.ManagedThreadId;
}
}
}
@@ -17,7 +17,7 @@ namespace mbts.ui.controls
return rv;
}
}
public class DiagnosticsUIAdapter : IReadWriteGridAdapter
class DiagnosticsUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Diagnostics";
private readonly VolSurfaceDisplayGridColumn _atm_straddle_col, _rr_col, _strangle_col, _put_bf_col, _call_bf_col,
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class DriverUIAdapter : IReadWriteGridAdapter
class DriverUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Driver";
private readonly VolSurfaceDisplayGridColumn _fwd_col, _ref_fwd_col, _live_driver_col, _driver_override_col;
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class DualQuadraticModelUIAdapter : IReadWriteGridAdapter
class DualQuadraticModelUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Main Curve";
private readonly VolSurfaceDisplayGridColumn _put_wing_strike_col, _put_slope_col, _put_curvature_col,
@@ -99,4 +99,4 @@ namespace mbts.ui.controls
};
}
}
}
}
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class ExplicitSlopeWingUIAdapter : IReadWriteGridAdapter
class ExplicitSlopeWingUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Wings";
private VolSurfaceDisplayGridColumn _p_wing_slope, _c_wing_slope, _p_wing_decay, _c_wing_decay;
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class ImplicitSlopeWingUIAdapter : IReadWriteGridAdapter
class ImplicitSlopeWingUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Wings";
private VolSurfaceDisplayGridColumn _p_wing_max, _c_wing_max;
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class MiscColsUIAdapter : IReadWriteGridAdapter
class MiscColsUIAdapter : IReadWriteGridAdapter
{
private const string _group = "General";
private readonly VolSurfaceDisplayGridColumn _time_shift_col, _biz_time_output_col, _vol_time_years_output_col, _vol_time_days_per_year,
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class ParabolicVolPathUIAdapter : IReadWriteGridAdapter
class ParabolicVolPathUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Vol Path";
private readonly VolSurfaceDisplayGridColumn _down_market_move, _down_market_vol_move, _up_market_move, _up_market_vol_move, _max_vol_increase, _max_vol_decrease;
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class PolynomialModelUIAdapter : IReadWriteGridAdapter
class PolynomialModelUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Main Curve";
private readonly List<Tuple<VolSurfaceDisplayGridColumn, VolSurfaceDisplayGridColumn, VolSurfaceDisplayGridColumn>> _put_cols, _call_cols;
@@ -130,4 +130,4 @@ namespace mbts.ui.controls
return rv;
}
}
}
}
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class SplineModelUIAdapter : IReadWriteGridAdapter
class SplineModelUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Main Curve";
private readonly List<Tuple<VolSurfaceDisplayGridColumn, VolSurfaceDisplayGridColumn, VolSurfaceDisplayGridColumn>> _put_cols, _call_cols;
@@ -123,4 +123,4 @@ namespace mbts.ui.controls
return rv;
}
}
}
}
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class StrikeConversionUIAdapter : IReadWriteGridAdapter
class StrikeConversionUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Strike Dynamics";
private readonly VolSurfaceDisplayGridColumn _conv_fwd_slider_col, _conv_vol_slider_col, _conv_fwd_col, _conv_vol_col;
@@ -8,7 +8,7 @@ using mbts.spark;
namespace mbts.ui.controls
{
public class TwoWaySlopeVolPathUIAdapter : IReadWriteGridAdapter
class TwoWaySlopeVolPathUIAdapter : IReadWriteGridAdapter
{
private const string _group = "Vol Path";
private readonly VolSurfaceDisplayGridColumn _down_slope_col, _up_slope_col, _max_vol_inc_col, _max_vol_dec_col, _joint_speed_col;
@@ -11,7 +11,7 @@ using bts;
namespace mbts.ui.controls
{
public class VolSurfaceUIAdapter
class VolSurfaceUIAdapter
{
private class MyComparerWrapper<T> : IComparer<T>
{
@@ -150,4 +150,4 @@ namespace mbts.ui.controls
return rv;
}
}
}
}
@@ -0,0 +1,153 @@
using mbts.ui;
using mbts.ui.controls.graph;
using mbts.ui.shell;
using ProtoBuf;
using System;
using System.Collections.Generic;
namespace mbts.spark {
[ProtoContract]
class VolSurfaceGraphSettings : IEquatable<VolSurfaceGraphSettings>, ICloneable {
public static VolSurfaceGraphSettings get_default() {
return new VolSurfaceGraphSettings {
put_control_points = new ScatterSeriesSettings {
color = BTSColors.VolSurfaceGraph.put_special,
shape = MarkerShape.Circle,
size = 3.0
},
atm = new ScatterSeriesSettings {
shape = MarkerShape.Diamond,
size = 4.5,
color = BTSColors.VolSurfaceGraph.main_curve_atm
},
call_control_points = new ScatterSeriesSettings {
color = BTSColors.VolSurfaceGraph.call_special,
shape = MarkerShape.Circle,
size = 3.0
},
put_wing = new LineSeriesSettings {
color = BTSColors.VolSurfaceGraph.wing,
stroke_thickness = 1.5
},
inner_curve = new LineSeriesSettings {
color = BTSColors.VolSurfaceGraph.main_curve,
stroke_thickness = 1.5
},
call_wing = new LineSeriesSettings {
color = BTSColors.VolSurfaceGraph.wing,
stroke_thickness = 1.5
},
implied_puts = new ScatterSeriesSettings {
shape = MarkerShape.Circle,
size = 1.5,
color = BTSColors.VolSurfaceGraph.implied_put
},
implied_atm = new ScatterSeriesSettings {
shape = MarkerShape.Cross,
size = 4.5,
color = BTSColors.VolSurfaceGraph.implied_atm
},
implied_calls = new ScatterSeriesSettings {
shape = MarkerShape.Circle,
size = 1.5,
color = BTSColors.VolSurfaceGraph.implied_call
},
vol_path = get_default_vol_path_settings(),
exp_bounds = new ExpGraphBounds[0]
};
}
public static LineSeriesSettings get_default_vol_path_settings() {
return new LineSeriesSettings {
color = BTSColors.VolSurfaceGraph.vol_path,
stroke_thickness = 1.5
};
}
[ProtoMember(1)]
public ScatterSeriesSettings call_control_points;
[ProtoMember(2)]
public ScatterSeriesSettings put_control_points;
[ProtoMember(3)]
public LineSeriesSettings put_wing;
[ProtoMember(4)]
public LineSeriesSettings inner_curve;
[ProtoMember(5)]
public LineSeriesSettings call_wing;
[ProtoMember(6)]
public ScatterSeriesSettings implied_puts;
[ProtoMember(7)]
public ScatterSeriesSettings implied_calls;
[ProtoMember(8)]
public ScatterSeriesSettings atm;
[ProtoMember(9)]
public ScatterSeriesSettings implied_atm;
[ProtoMember(10)]
public LineSeriesSettings vol_path;
[ProtoMember(11)]
public ExpGraphBounds[] exp_bounds;
//private LineSeriesSettings _vol_path;
//public LineSeriesSettings vol_path {
// get {
// return _vol_path ?? (_vol_path = new LineSeriesSettings {
// color = BTSColors.VolSurfaceGraph.vol_path,
// thickness = 1.5
// });
// }
//}
public object Clone() =>
ProtoBufSerializationHelper.clone_protobuf(this);
public bool Equals(VolSurfaceGraphSettings other) =>
other != null &&
call_control_points.safe_equals(other.call_control_points) &&
call_wing.safe_equals(other.call_wing) &&
implied_calls.safe_equals(other.implied_calls) &&
put_control_points.safe_equals(other.put_control_points) &&
put_wing.safe_equals(other.put_wing) &&
implied_puts.safe_equals(other.implied_puts) &&
inner_curve.safe_equals(other.inner_curve) &&
atm.safe_equals(other.atm) &&
implied_atm.safe_equals(other.implied_atm) &&
vol_path.safe_equals(other.vol_path) &&
exp_bounds.safe_sequence_equals(other.exp_bounds);
public override bool Equals(object obj) =>
Equals(obj as VolSurfaceGraphSettings);
public override int GetHashCode() =>
GetType().GetHashCode();
}
[ProtoContract]
class ExpGraphBounds : IEquatable<ExpGraphBounds> {
[ProtoMember(1)]
public SecurityExpirationProto exp { get; set; }
[ProtoMember(2)]
public AxisBounds x_bounds { get; set; }
[ProtoMember(3)]
public AxisBounds y_bounds { get; set; }
public bool Equals(ExpGraphBounds other) =>
other != null &&
x_bounds.safe_equals(other.x_bounds) &&
y_bounds.safe_equals(other.y_bounds);
public override bool Equals(object obj) =>
Equals(obj as ExpGraphBounds);
public override int GetHashCode() =>
GetType().GetHashCode();
}
}
@@ -0,0 +1,46 @@
namespace mbts.spark {
using mbts.analytics;
using ProtoBuf;
using System.Collections.Generic;
[ProtoContract]
class VolSurfaceWindowSettings {
public static int version => 1;
[ProtoMember(1)]
public int id { get; set; }
[ProtoMember(2)]
public ui.controls.graph.BTSGraphAxis vol_curve_x_axis { get; set; }
[ProtoMember(3)]
public ui.controls.graph.BTSGraphAxis vol_curve_y_axis { get; set; }
[ProtoMember(4)]
public List<VolSurfaceExpiration> vol_curve_visible_series { get; set; }
[ProtoMember(5)]
public List<VolSurfaceExpiration> hidden_exps { get; set; }
[ProtoMember(6)]
public bool show_mkt_implied_vol { get; set; }
[ProtoMember(7)]
public VolSurfaceGraphSettings vol_curve_graph_settings { get; set; }
[ProtoMember(8)]
public ui.controls.VolSurfaceMacroGridSettings macro_grid_settings { get; set; }
public bool Equals(VolSurfaceWindowSettings other) =>
other != null &&
id == other.id &&
vol_curve_x_axis.safe_equals(other.vol_curve_x_axis) &&
vol_curve_y_axis.safe_equals(other.vol_curve_y_axis) &&
vol_curve_visible_series.safe_sequence_equals(other.vol_curve_visible_series) &&
hidden_exps.safe_sequence_equals(other.hidden_exps) &&
show_mkt_implied_vol == other.show_mkt_implied_vol &&
vol_curve_graph_settings.safe_equals(other.vol_curve_graph_settings);
}
}
@@ -0,0 +1,129 @@
<UserControl
x:Class="mbts.ui.controls.VolSurfaceMacroControlView"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:controls="clr-namespace:mbts.ui.controls"
xmlns:converters="clr-namespace:mbts.ui.converters">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<StackPanel.Resources>
<Style
TargetType="Button"
BasedOn="{StaticResource ResourceKey={x:Type Button}}">
<Setter
Property="Margin"
Value="5" />
<Setter
Property="HorizontalAlignment"
Value="Stretch" />
</Style>
<Style
TargetType="controls:TickUpDown"
BasedOn="{StaticResource {x:Type controls:TickUpDown}}">
<Setter
Property="Margin"
Value="5" />
<Setter
Property="VerticalAlignment"
Value="Center" />
</Style>
</StackPanel.Resources>
<GroupBox
Header="Cascade"
Padding="4">
<Grid HorizontalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<CheckBox
IsChecked="{Binding cascade_up}"
IsEnabled="{Binding can_cascade}">Up</CheckBox>
<CheckBox
Grid.Column="1"
HorizontalAlignment="Left"
Margin="8,0,0,0"
IsChecked="{Binding cascade_down}"
IsEnabled="{Binding can_cascade}">Down</CheckBox>
</Grid>
</GroupBox>
<Button
Content="Rebuild"
Command="{Binding rebuild}" />
<controls:TickUpDown
Content="Put Rotation"
TickCommand="{Binding put_rotation}"
TickUpParameter="true"
TickDownParameter="false" />
<controls:TickUpDown
Content="Call Rotation"
TickCommand="{Binding call_rotation}"
TickUpParameter="true"
TickDownParameter="false" />
<controls:TickUpDown
Content="Risk Reversal"
TickCommand="{Binding full_rotation}"
TickUpParameter="true"
TickDownParameter="false" />
<controls:TickUpDown
Content="Strangle"
TickCommand="{Binding strangle}"
TickUpParameter="true"
TickDownParameter="false" />
<controls:TickUpDown
Grid.Row="1"
Content="ATM Move"
TickCommand="{Binding atm_shift}"
TickUpParameter="true"
TickDownParameter="false" />
<GroupBox Header="Fit To Market">
<StackPanel>
<ComboBox
Margin="5"
SelectedIndex="0"
IsEnabled="False"
x:Name="_a">
<ComboBoxItem>Live</ComboBoxItem>
<ComboBoxItem>Settlement</ComboBoxItem>
</ComboBox>
<ComboBox
Margin="5"
SelectedIndex="0"
IsEnabled="{Binding can_execute_commands}"
x:Name="_b">
<ComboBoxItem>ATM Only</ComboBoxItem>
<ComboBoxItem>All</ComboBoxItem>
</ComboBox>
<CheckBox
Content="Weight Reg. Fit"
Margin="5"
IsChecked="{Binding use_weighted_regression_fit}" />
<Button
Content="Fit"
Command="{Binding fit_to_market}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource TupleConverter}">
<Binding
ElementName="_a"
Path="SelectedIndex" />
<Binding
ElementName="_b"
Path="SelectedIndex" />
</MultiBinding>
</Button.CommandParameter>
</Button>
</StackPanel>
</GroupBox>
<controls:TickUpDown
Content="Global Vol Shift"
TickCommand="{Binding vol_shift}"
TickUpParameter="true"
TickDownParameter="false"
Visibility="Collapsed" />
</StackPanel>
</ScrollViewer>
</UserControl>
@@ -0,0 +1,8 @@
namespace mbts.ui.controls {
using System.Windows.Controls;
partial class VolSurfaceMacroControlView : UserControl {
public VolSurfaceMacroControlView() =>
InitializeComponent();
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace mbts.ui.shell {
partial class VolSurfaceSettingsEditor : Window {
public VolSurfaceSettingsEditor() =>
InitializeComponent();
}
}
@@ -0,0 +1,146 @@
<UserControl
x:Class="mbts.ui.shell.VolSurfaceShellModuleContent"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:mbts.ui.controls"
x:Name="me"
MinWidth="250">
<UserControl.Resources>
<Style
x:Key="CommonList"
TargetType="{x:Type ListBox}">
<Setter
Property="HorizontalContentAlignment"
Value="Stretch" />
<Setter
Property="Background"
Value="Transparent" />
<Setter
Property="BorderThickness"
Value="0" />
</Style>
</UserControl.Resources>
<Grid Margin="8">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button
Style="{DynamicResource StartMenuButton}"
Content="Analytics Expiration Parameters"
Command="{Binding launch_analytics_expiration_parameters_editor}"
Padding="4" />
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Rectangle
Margin="5,1,5,0"
Fill="{DynamicResource StartMenuMouseOverBackground}"
HorizontalAlignment="Stretch"
Height="1" />
<c:HelpButton
Grid.Column="2"
ManPage="AW2"
ToolTip="Click Here for help" />
</Grid>
<Expander
Grid.Row="2"
Margin="0,3,0,0"
Header="Current Vol Surfaces"
IsExpanded="True">
<ScrollViewer
MaxHeight="520"
VerticalScrollBarVisibility="Auto">
<ListBox
ItemsSource="{Binding current_vol_surfaces}"
Style="{StaticResource CommonList}"
Grid.IsSharedSizeScope="True"
ItemTemplate="{StaticResource ShellLaunchWithDeleteItemTemplate}" />
</ScrollViewer>
</Expander>
<GroupBox
Grid.Row="3"
Header="New Vol Surface">
<StackPanel>
<Grid HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ItemsControl
Grid.Row="1"
ItemsSource="{Binding option_driver_groups_vm.driver_groups}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<GroupBox Header="{Binding Key.symbol}">
<ItemsControl ItemsSource="{Binding Value}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel
IsItemsHost="True"
Orientation="Vertical"
FlowDirection="LeftToRight"
MaxHeight="60" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox
Content="{Binding symbol}"
IsChecked="{Binding is_selected}"
Margin="5" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</GroupBox>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Grid
Grid.Row="2"
HorizontalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock
Grid.Column="1"
HorizontalAlignment="Center"
Text="Select a name"
Foreground="Red"
Visibility="{Binding absent_name_message_visibility}" />
<TextBlock
Grid.Row="1"
Text="Name"
Margin="4,0,4,0"
VerticalAlignment="Center" />
<TextBox
Grid.Row="1"
Grid.Column="1"
HorizontalAlignment="Stretch"
Margin="4"
Text="{Binding new_vol_surface_name, UpdateSourceTrigger=PropertyChanged}" />
<Button
Grid.Row="1"
Grid.Column="2"
MinWidth="60"
Margin="4"
IsDefault="True"
Command="{Binding create_new_vol_surface}">Create</Button>
</Grid>
</Grid>
</StackPanel>
</GroupBox>
</Grid>
</UserControl>
@@ -0,0 +1,11 @@
namespace mbts.ui.shell {
using System.Windows.Controls;
/// <summary>
/// Interaction logic for VolSurfaceShellModuleContent.xaml
/// </summary>
partial class VolSurfaceShellModuleContent : UserControl {
public VolSurfaceShellModuleContent() =>
InitializeComponent();
}
}
@@ -0,0 +1,111 @@
<UserControl
x:Class="mbts.ui.shell.VolSurfaceTimeDecayEditor"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:s="clr-namespace:mbts.ui.shell">
<Grid>
<Grid.RowDefinitions>
<!--ITEMS-->
<RowDefinition Height="*" />
<!--SPACING-->
<RowDefinition Height="12" />
<!--ADD NEW ITEM CONTROLS-->
<RowDefinition Height="40" />
</Grid.RowDefinitions>
<ItemsControl
Grid.IsSharedSizeScope="True"
Margin="4"
ItemsSource="{Binding time_decay_items}">
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter
Property="Margin"
Value="0,3,0,0" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition
Width="Auto"
SharedSizeGroup="actual_time_col" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button
Command="{Binding DataContext.remove_item, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}"
Style="{StaticResource RoundCloseButton}" />
<TextBlock Grid.Column="1">
<TextBlock.Inlines>
<Run Text="At" />
<Run
Text="{Binding actual_time, StringFormat=t, Mode=OneTime}"
FontWeight="Bold" />
</TextBlock.Inlines>
</TextBlock>
<TextBlock
Grid.Column="2"
Margin="2,0,0,0">vol clock is at hour</TextBlock>
<TextBox
Grid.Column="3"
Margin="3,0,3,0"
Width="40"
Text="{Binding decay_hours, Converter={StaticResource DoubleTextConverter}}"
u:TextBoxBehavior.TraverseOnEnter="True"
Loaded="decay_hours_Loaded" />
<TextBlock Grid.Column="4">/24</TextBlock>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Grid
Grid.Row="2"
Background="{x:Static u:BTSColors.dialog_skirt_brush}">
<Grid.ColumnDefinitions>
<!--PAD LEFT-->
<ColumnDefinition Width="12" />
<!--ADD ITEM BUTTON-->
<ColumnDefinition Width="Auto" />
<!--SPACING-->
<ColumnDefinition Width="8" />
<!--TIME PICKER-->
<ColumnDefinition Width="80" />
<!--PAD RIGHT-->
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Button
x:Name="add_item_button"
Grid.Column="1"
Command="{Binding add_item}"
Style="{StaticResource CommonButton}">
+
</Button>
<c:DateTimePicker
x:Name="time_picker"
Grid.Column="3"
Background="White"
Width="80"
TimeTuple="{Binding new_actual_time}"
KeyDown="time_picker_KeyDown">
<Validation.ErrorTemplate>
<ControlTemplate>
<Rectangle
Width="80"
Height="24"
Stroke="Red"
Fill="Blue"
StrokeThickness="1"
Opacity="1" />
</ControlTemplate>
</Validation.ErrorTemplate>
</c:DateTimePicker>
</Grid>
</Grid>
</UserControl>
@@ -0,0 +1,33 @@
using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
namespace mbts.ui.shell {
/// <summary>
/// Interaction logic for VolSurfaceTimeDecayEditor.xaml
/// </summary>
partial class VolSurfaceTimeDecayEditor : UserControl {
public VolSurfaceTimeDecayEditor() =>
InitializeComponent();
void decay_hours_Loaded(object sender, System.Windows.RoutedEventArgs e) {
var tb = (TextBox)sender;
tb.Focus();
Keyboard.Focus(tb);
}
void time_picker_KeyDown(object sender, KeyEventArgs e) {
if (e.Key == Key.Enter) {
e.Handled = true;
add_item_button.Focus();
ICommand command = add_item_button.Command;
if (command != null) {
object parameter = add_item_button.CommandParameter;
if (add_item_button.Command.CanExecute(parameter))
add_item_button.Command.Execute(parameter);
}
}
}
}
}
@@ -0,0 +1,649 @@
<UserControl
x:Class="mbts.ui.shell.VolSurfaceView2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:shell="clr-namespace:mbts.ui.shell"
xmlns:graph="clr-namespace:mbts.ui.controls.graph"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
Background="{StaticResource CommonBackground}"
TextElement.FontSize="10">
<UserControl.Resources>
<Style
x:Key="commit_style"
TargetType="Button"
BasedOn="{StaticResource ResourceKey={x:Type Button}}">
<Style.Triggers>
<DataTrigger
Binding="{Binding is_dirty}"
Value="true">
<Setter
Property="Foreground"
Value="{u:BTSColor Name=UI.alternate_text}" />
<Setter
Property="Background"
Value="{u:BTSColor Name=UI.warning}" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style TargetType="TextBlock">
<Setter
Property="HorizontalAlignment"
Value="Center" />
<Setter
Property="VerticalAlignment"
Value="Center" />
</Style>
<Style
x:Key="VolTimeTimePickerStyle"
TargetType="ComboBox"
BasedOn="{StaticResource {x:Type ComboBox}}">
<Setter
Property="MinWidth"
Value="60" />
<Setter
Property="IsEditable"
Value="True" />
<Setter
Property="ItemStringFormat"
Value="t" />
<Setter
Property="ItemsSource"
Value="{x:Static c:DateTimePicker.CandidateTimesEvery15Min}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding time_mode}"
Value="AutoDecay">
<Setter
Property="IsEnabled"
Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style
x:Key="VolTimeDateTextStyle"
TargetType="TextBox">
<Setter
Property="MinWidth"
Value="55" />
<Setter
Property="BorderBrush"
Value="Transparent" />
<Setter
Property="u:TextBoxBehavior.CommitOnEnter"
Value="True" />
<Style.Triggers>
<DataTrigger
Binding="{Binding time_mode}"
Value="AutoDecay">
<Setter
Property="IsEnabled"
Value="False" />
</DataTrigger>
<EventTrigger RoutedEvent="MouseEnter">
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetProperty="BorderBrush.Color"
To="{StaticResource Button.MouseOver.BorderColor}"
Duration="0:0:0.3" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
<EventTrigger RoutedEvent="MouseLeave">
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetProperty="BorderBrush.Color"
To="Transparent"
Duration="0:0:0.4" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Style.Triggers>
</Style>
<Style
x:Key="VolTimePopupButtonStyle"
TargetType="ToggleButton">
<Setter
Property="Focusable"
Value="False" />
<Setter
Property="ClickMode"
Value="Press" />
<Setter
Property="IsThreeState"
Value="False" />
<Setter
Property="Padding"
Value="5,2" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ToggleButton">
<Border
x:Name="border"
Padding="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalAlignment}">
<ContentPresenter x:Name="contentPresenter" />
</Border>
<ControlTemplate.Triggers>
<Trigger
Property="IsMouseOver"
Value="True">
<Setter
Property="Background"
TargetName="border"
Value="#FFBEE6FD" />
<Setter
Property="BorderBrush"
TargetName="border"
Value="#FF3C7FB1" />
</Trigger>
<Trigger
Property="IsPressed"
Value="True">
<Setter
Property="Background"
TargetName="border"
Value="#FFC4E5F6" />
<Setter
Property="BorderBrush"
TargetName="border"
Value="#FF2C628B" />
</Trigger>
<Trigger
Property="ToggleButton.IsChecked"
Value="True">
<Setter
Property="Background"
TargetName="border"
Value="#FFBCDDEE" />
<Setter
Property="BorderBrush"
TargetName="border"
Value="#FF245A83" />
</Trigger>
<Trigger
Property="IsEnabled"
Value="False">
<Setter
Property="Background"
TargetName="border"
Value="#FFF4F4F4" />
<Setter
Property="BorderBrush"
TargetName="border"
Value="#FFADB2B5" />
<Setter
Property="TextElement.Foreground"
TargetName="contentPresenter"
Value="#FF838383" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="Content">
<Setter.Value>
<Image
Source="{x:Static u:Icons.Date}"
Width="19"
Height="19" />
</Setter.Value>
</Setter>
</Style>
<Style
x:Key="VolTimePopupContentStyle"
TargetType="ContentControl">
<Setter
Property="Content"
Value="{Binding}" />
<Style.Triggers>
<DataTrigger
Binding="{Binding time_mode}"
Value="AutoDecay">
<Setter
Property="Content"
Value="{Binding decay_editor}" />
</DataTrigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition Height="Auto" />
<RowDefinition Height="2*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<c:DIYGrid
x:Name="macro_grid"
Grid.Row="0"
Grid.ColumnSpan="3"
DataContext="{Binding grid}"
FrozenColumnCount="{Binding frozen_columns}"
SuperHeaders="{Binding super_headers}"
Columns="{Binding columns}"
Rows="{Binding visible_rows}"
RowTemplate="{Binding row_template}">
<c:DIYGrid.Resources>
<ContextMenu x:Key="context_menu">
<MenuItem Header="Settings">
<MenuItem.Icon>
<Image
Height="16"
Margin="2"
HorizontalAlignment="Left"
VerticalAlignment="Center"
Source="/bts_uicore;component/images/icons/Admin.png"
RenderOptions.BitmapScalingMode="HighQuality"
SnapsToDevicePixels="True" />
</MenuItem.Icon>
<MenuItem
Header="Vol Surface Settings"
Command="{Binding main_settings_command}" />
<MenuItem
Header="Vol Surface Advanced Settings"
Command="{Binding advanced_settings_command}" />
<Separator />
<MenuItem
Header="Grid Settings"
Command="{Binding grid_settings_command}" />
<MenuItem
Header="Graph Settings"
Command="{Binding graph_settings_command}" />
</MenuItem>
<Separator />
<MenuItem Header="Copy...">
<MenuItem.ItemsSource>
<x:ArrayExtension Type="sys:Object">
<MenuItem
Header="{Binding column_name}"
HeaderStringFormat="Copy '{0}' to Selected Expirations"
Command="{Binding copy_to_selection_command}"
CommandParameter="Column" />
<MenuItem
Header="{Binding group_name}"
HeaderStringFormat="Copy '{0}' to Selected Expirations"
Command="{Binding copy_to_selection_command}"
CommandParameter="Group" />
<MenuItem
Header="{Binding expiration_name}"
HeaderStringFormat="Copy '{0}' to Selected Expirations"
Command="{Binding copy_to_selection_command}"
CommandParameter="All" />
<Separator />
<MenuItem
Header="{Binding column_name}"
HeaderStringFormat="Copy '{0}' to Master Expirations"
Command="{Binding copy_to_masters_command}"
CommandParameter="Column" />
<MenuItem
Header="{Binding group_name}"
HeaderStringFormat="Copy '{0}' to Master Expirations"
Command="{Binding copy_to_masters_command}"
CommandParameter="Group" />
<MenuItem
Header="{Binding expiration_name}"
HeaderStringFormat="Copy '{0}' to Master Expirations"
Command="{Binding copy_to_masters_command}"
CommandParameter="All" />
<Separator />
<MenuItem
Header="{Binding column_name}"
HeaderStringFormat="Copy '{0}' to All Expirations"
Command="{Binding copy_to_all_command}"
CommandParameter="Column" />
<MenuItem
Header="{Binding group_name}"
HeaderStringFormat="Copy '{0}' to All Expirations"
Command="{Binding copy_to_all_command}"
CommandParameter="Group" />
<MenuItem
Header="{Binding expiration_name}"
HeaderStringFormat="Copy '{0}' to All Expirations"
Command="{Binding copy_to_all_command}"
CommandParameter="All" />
<Separator />
<MenuItem
Header="Copy All To Clipboard"
Command="{Binding copy_all_to_clipboard_command}" />
</x:ArrayExtension>
</MenuItem.ItemsSource>
</MenuItem>
<Separator />
<MenuItem Header="Shift...">
<MenuItem.ItemsSource>
<x:ArrayExtension Type="sys:Object">
<MenuItem
Header="{Binding column_name}"
HeaderStringFormat="Shift '{0}' for Selected Expirations"
Command="{Binding shift_selection_command}" />
<MenuItem
Header="{Binding column_name}"
HeaderStringFormat="Shift '{0}' for Master Expirations"
Command="{Binding shift_masters_command}" />
<MenuItem
Header="{Binding column_name}"
HeaderStringFormat="Shift '{0}' for All Expirations"
Command="{Binding shift_all_command}" />
</x:ArrayExtension>
</MenuItem.ItemsSource>
</MenuItem>
<Separator />
<MenuItem
Header="Revert"
Command="{Binding revert_command}"
IsEnabled="{Binding is_input_cell}" />
<Separator />
<MenuItem Header="Clear...">
<MenuItem.ItemsSource>
<x:ArrayExtension Type="sys:Object">
<MenuItem
Header="{Binding column_name}"
HeaderStringFormat="Clear '{0}'"
Command="{Binding clear_command}"
CommandParameter="Column"
IsEnabled="{Binding is_input_cell}" />
<MenuItem
Header="{Binding group_name}"
HeaderStringFormat="Clear '{0}'"
Command="{Binding clear_command}"
CommandParameter="Group" />
<MenuItem
Header="{Binding expiration_name}"
HeaderStringFormat="Clear '{0}'"
Command="{Binding clear_command}"
CommandParameter="All" />
</x:ArrayExtension>
</MenuItem.ItemsSource>
</MenuItem>
<Separator />
<MenuItem
Header="Sync Slave Ref Fwd's To Master"
Command="{Binding smart_copy_rolls_rates_command}" />
<Separator />
<MenuItem
Header="Symbols"
ItemsSource="{Binding symbols}"
IsEnabled="{Binding parent.symbol_filter_enabled}">
<MenuItem.ItemContainerStyle>
<Style
TargetType="MenuItem"
BasedOn="{StaticResource ThreeStateMenuItem}">
<Setter
Property="Header"
Value="{Binding symbol}" />
<Setter
Property="IsCheckable"
Value="True" />
<Setter
Property="c:MenuItemEx.IsChecked"
Value="{Binding visible}" />
<Setter
Property="StaysOpenOnClick"
Value="True" />
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
<MenuItem
Header="Import CSV..."
Command="{Binding import_csv_command}" />
</ContextMenu>
</c:DIYGrid.Resources>
</c:DIYGrid>
<GridSplitter
Grid.Row="1"
Grid.ColumnSpan="2"
Height="3"
HorizontalAlignment="Stretch"
ResizeDirection="Rows" />
<StackPanel
Grid.Row="2"
Width="112">
<Button
Content="Commit"
HorizontalAlignment="Center"
Command="{Binding commit_command}"
Grid.Column="6"
Width="60"
Margin="5"
Style="{StaticResource commit_style}" />
<c:VolSurfaceMacroControlView
Grid.Row="2"
Margin="3"
DataContext="{Binding macro_actions}"
Width="112"
IsEnabled="{Binding DataContext.any_masters_selected, ElementName=macro_grid}" />
</StackPanel>
<AdornerDecorator
Grid.Row="2"
Grid.Column="1">
<Grid x:Name="adorned_grid">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TabControl>
<TabItem
Header="Vol Curve"
DataContext="{Binding vol_curve_vm}"
x:Name="vol_curve_tab">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<graph:BTSOxyGraph
DataContext="{Binding graph_vm, Mode=OneWay}"
UserCanToggleLegendVisibility="False">
<graph:BTSOxyGraph.AdditionalContent>
<Grid
VerticalAlignment="Top"
Margin="40,20,33,3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding DataContext.ignore_implied_vol_settings, RelativeSource={RelativeSource AncestorType=shell:VolSurfaceView2}}">Ignore Market Implied Vol Settings</CheckBox>
<StackPanel
Grid.Column="1"
Orientation="Horizontal">
<TextBlock>Implied Vol</TextBlock>
<ComboBox
Width="55"
Margin="8,0,0,0"
SelectedItem="{Binding implied_vol_market_side}"
ItemsSource="{Binding market_sides}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger
Property="Text"
Value="None">
<Setter
Property="Foreground"
Value="Gray" />
<Setter
Property="FontStyle"
Value="Italic" />
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
<CheckBox
Grid.Column="2"
Margin="12,0,0,0"
IsChecked="{Binding show_vol_path}">Show Vol Path</CheckBox>
</Grid>
</graph:BTSOxyGraph.AdditionalContent>
</graph:BTSOxyGraph>
</Grid>
</TabItem>
<TabItem
Header="Terms"
DataContext="{Binding vol_terms_vm}">
<graph:BTSOxyGraph DataContext="{Binding graph_vm, Mode=OneWay}" UserCanToggleLegendVisibility="False">
<graph:BTSOxyGraph.AdditionalContent>
<StackPanel
VerticalAlignment="Top"
Orientation="Horizontal">
<c:ComboCheckBox
Grid.IsSharedSizeScope="True"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Margin="8"
Height="25"
HeaderContent="Symbols"
ItemsSource="{Binding symbols}"
SelectedItems="{Binding selected_symbols}" />
<CheckBox
VerticalAlignment="Center"
Margin="8"
IsChecked="{Binding show_day_numbers}">Show Day Numbers</CheckBox>
</StackPanel>
</graph:BTSOxyGraph.AdditionalContent>
</graph:BTSOxyGraph>
</TabItem>
</TabControl>
<!-- Bottom row controls -->
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<!-- Date/Time -->
<ColumnDefinition Width="Auto" />
<!-- Details -->
<ColumnDefinition Width="Auto" />
<!-- Summary -->
<ColumnDefinition Width="Auto" />
<!-- gap -->
<ColumnDefinition Width="*" />
<!-- Previous states combo + Button -->
<ColumnDefinition Width="Auto" />
<!-- Revert -->
<ColumnDefinition Width="Auto" />
<!-- Commit -->
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Border
BorderBrush="{u:BTSColor UI.danger}"
DataContext="{Binding globals}"
Margin="-2.5,5,0,5"
Padding="0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ComboBox
Text="{Binding time, ValidatesOnExceptions=True}"
Style="{StaticResource VolTimeTimePickerStyle}" />
<Border
Grid.Column="1"
Background="White"
BorderBrush="{x:Static SystemColors.ActiveBorderBrush}"
BorderThickness="1">
<StackPanel Orientation="Horizontal">
<TextBox
Margin="3,3,0,3"
Text="{Binding date, StringFormat=d, ValidatesOnExceptions=True}"
Style="{StaticResource VolTimeDateTextStyle}" />
<ToggleButton
x:Name="vol_time_popup_button"
IsChecked="{Binding vol_time_popup_open}"
Style="{StaticResource VolTimePopupButtonStyle}"
Loaded="vol_time_popup_button_Loaded" />
</StackPanel>
</Border>
</Grid>
<Border.Style>
<Style TargetType="Border">
<Setter
Property="BorderThickness"
Value="0" />
<Setter
Property="Padding"
Value="3" />
<Style.Triggers>
<DataTrigger
Binding="{Binding is_date_committed}"
Value="false">
<Setter
Property="BorderThickness"
Value="1" />
<Setter
Property="Padding"
Value="2" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
</Border>
<Button
Content="Details"
Grid.Column="1"
Command="{Binding details_command}"
Width="60"
Margin="5" />
<Button
Content="Heatmap"
Grid.Column="2"
Command="{Binding summary_command}"
Width="60"
Margin="5" />
<StackPanel Grid.Column="4" Orientation="Horizontal">
<ComboBox
ItemsSource="{Binding previous_states}"
SelectedItem="{Binding selected_previous_state}"
VerticalAlignment="Center"
Margin="5"
MinWidth="150" />
<Button
Content="Load"
Command="{Binding load_previous_command}"
Width="60"
Margin="0,5,5,5" />
</StackPanel>
<Button
Content="Revert"
Command="{Binding revert_command}"
Grid.Column="5"
Width="60"
Margin="5" />
<Button
Content="Commit"
Command="{Binding commit_command}"
Grid.Column="6"
Width="60"
Margin="5"
Style="{StaticResource commit_style}" />
</Grid>
</Grid>
</AdornerDecorator>
</Grid>
</UserControl>
@@ -0,0 +1,76 @@
using mbts.ui.controls;
using mbts.ui.controls.adorners;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
namespace mbts.ui.shell {
public partial class VolSurfaceView2 : UserControl {
PopupAdorner _time_editor_popup;
public VolSurfaceView2() =>
InitializeComponent();
public const string TimeDecayTemplateKey = "Decay";
private void vol_time_popup_button_Loaded(object sender, RoutedEventArgs e) {
// don't initialize more than once
if (_time_editor_popup != null) return;
var adorner_layer = AdornerLayer.GetAdornerLayer(adorned_grid);
_time_editor_popup = new PopupAdorner(adorned_grid, vol_time_popup_button, _get_time_editor_control(), HorizontalPosition.Left, VerticalPosition.Top, 0.5 * ((ToggleButton)sender).ActualWidth, 0d) { IsHitTestVisible = true };
_time_editor_popup.SetBinding(PopupAdorner.DataContextProperty, "globals");
_time_editor_popup.SetBinding(PopupAdorner.IsOpenProperty, new Binding("vol_time_popup_open") { Mode = BindingMode.TwoWay });
_time_editor_popup.Opened += _time_editor_popup_Opened;
_time_editor_popup.Closed += _time_editor_popup_Closed;
adorner_layer.Add(_time_editor_popup);
}
private void _time_editor_popup_Opened(object sender, RoutedEventArgs e) {
PreviewMouseDown += PreviewMouseDown_close_time_editor_handler;
PreviewKeyDown += PreviewKeyDown_close_time_editor_handler;
}
private void _time_editor_popup_Closed(object sender, RoutedEventArgs e) {
PreviewMouseDown -= PreviewMouseDown_close_time_editor_handler;
PreviewKeyDown -= PreviewKeyDown_close_time_editor_handler;
}
private void PreviewMouseDown_close_time_editor_handler(object sender, MouseButtonEventArgs e) {
if (_time_editor_popup != null && !_time_editor_popup.IsMouseOver && !vol_time_popup_button.IsMouseOver)
_time_editor_popup.IsOpen = false;
}
private void PreviewKeyDown_close_time_editor_handler(object sender, KeyEventArgs e) {
if (e.Key == Key.Escape && _time_editor_popup != null)
_time_editor_popup.IsOpen = false;
}
private ContentControl _get_time_editor_control() {
var decay_editor_factory = new FrameworkElementFactory(typeof(VolSurfaceTimeDecayEditor));
decay_editor_factory.SetValue(VolSurfaceTimeDecayEditor.MinHeightProperty, 170d);
decay_editor_factory.SetValue(VolSurfaceTimeDecayEditor.MinWidthProperty, 230d);
decay_editor_factory.SetValue(VolSurfaceTimeDecayEditor.BackgroundProperty, Brushes.White);
decay_editor_factory.SetValue(VolSurfaceTimeDecayEditor.BorderBrushProperty, SystemColors.ActiveBorderBrush);
decay_editor_factory.SetValue(VolSurfaceTimeDecayEditor.BorderThicknessProperty, new Thickness(1));
var template_map = new DataTemplateMap();
var manual_editor_factory = new FrameworkElementFactory(typeof(Calendar));
manual_editor_factory.AddHandler(Calendar.LostMouseCaptureEvent, new MouseEventHandler(Calendar_LostMouseCapture));
manual_editor_factory.SetBinding(Calendar.SelectedDateProperty, new Binding("date"));
template_map.DefaultTemplate = new DataTemplate { VisualTree = manual_editor_factory };
template_map.KeyValues.Add(new DataTemplateKeyValue { Key = TimeDecayTemplateKey, Value = new DataTemplate { VisualTree = decay_editor_factory } });
return new ContentControl { Style = (Style)Resources["VolTimePopupContentStyle"], ContentTemplateSelector = template_map };
}
private void Calendar_LostMouseCapture(object sender, MouseEventArgs e) {
_time_editor_popup.IsOpen = false;
}
}
}
@@ -0,0 +1,36 @@
namespace mbts.spark {
using mbts.ui;
using mbts.ui.shell;
using System;
using System.Windows.Input;
public class AlgoMenuItemVM : ViewModelBase {
public readonly int id;
readonly Action<int, string> _launch;
readonly Action<int, string> _delete;
string _name;
public AlgoMenuItemVM(int id, string name, Action<int, string> launch, Action<int, string> delete) {
this.id = id;
_name = name;
_launch = launch;
_delete = delete;
}
public string name {
get => _name;
set => Set(ref _name, value);
}
public virtual ICommand launch => new DelegateCommand(_ => _launch(id, _name));
public ICommand delete => new DelegateCommand(_ => _delete(id, _name));
public override bool Equals(object obj) =>
(obj as AlgoMenuItemVM)?.id == id;
public override int GetHashCode() =>
id;
}
}
@@ -0,0 +1,118 @@
using bts.collections;
using bts.utils;
using mbts;
using mbts.analytics;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
namespace mbts.spark {
public interface IExpirationBasedRow {
VolSurfaceDisplayGridExpiration expiration { get; }
}
abstract class ExpSelectionGridVM<TRow> : ViewModelBase, IDisposable where TRow : IExpirationBasedRow {
protected VolSurfaceDisplayModel _model;
protected VolSurfaceEventDemux _demux;
readonly IDisposable _exps_changed_subscription;
readonly List<VolSurfaceExpiration> _hidden_exps = new();
public ExpSelectionGridVM(VolSurfaceDisplayModel model, IEnumerable<VolSurfaceExpiration> hidden_expirations, object startup_data = null) {
_model = model;
_demux = new VolSurfaceEventDemux(model);
_hidden_exps = hidden_expirations.ToList();
visible_rows = new ObservableCollection<object>();
visible_rows.CollectionChanged += _visible_rows_changed;
var expirations = new ObservableCollection<VolSurfaceDisplayGridExpiration>();
_initialize(startup_data);
_demux.on_expirations_change += update_exps;
rows = new ObservableAutoWrapper<TRow, VolSurfaceDisplayGridExpiration>(expirations, _row_from_exp);
update_exps(_model.get_ordered_expirations(), new List<VolSurfaceDisplayGridExpiration>());
_exps_changed_subscription = Disposable.Create(() => _demux.on_expirations_change -= update_exps);
void update_exps(
IEnumerable<VolSurfaceDisplayGridExpiration> added,
IEnumerable<VolSurfaceDisplayGridExpiration> removed) {
expirations.sync_with(_model.get_ordered_expirations());
if (added.Any() && !removed.Any()) {
visible_rows.sync_with(rows.Where(r => !_hidden_exps.Contains(r.expiration.ToVSExp())).Cast<object>());
} else {
var vs_exps = expirations.Select(exp => exp.ToVSExp());
var vs_adds = added.Select(exp => exp.ToVSExp());
var vs_removes = removed.Select(exp => exp.ToVSExp());
var true_removed = removed.Where(rmv => !vs_adds.Contains(rmv.ToVSExp()));
var true_added = added.Where(add => !vs_removes.Contains(add.ToVSExp()));
var changed_calc_modes = added.Where(add => vs_removes.Contains(add.ToVSExp()));
foreach (var tr in true_removed) {
int index = visible_rows.Cast<IExpirationBasedRow>().Select(r => r.expiration).indexOf(tr);
if (index >= 0 && index < visible_rows.Count) {
visible_rows.RemoveAt(index);
}
}
foreach (var ta in true_added) {
if (_hidden_exps.Contains(ta.ToVSExp()) ||
!rows.TryGetFirst(r => r.expiration.expiration == ta.expiration, out var row)) {
continue;
}
visible_rows.InsertSorted(row,
Comparer<IExpirationBasedRow>.Create(
(r1, r2) => r1.expiration.CompareTo(r2.expiration))
.wrap<IExpirationBasedRow, object>());
}
foreach (var ccm in changed_calc_modes) {
int index = visible_rows
.Cast<IExpirationBasedRow>()
.Select(r => r.expiration.ToVSExp())
.indexOf(ccm.ToVSExp());
if (index < 0 || index >= visible_rows.Count) {
continue;
}
visible_rows.RemoveAt(index);
if (rows.TryGetFirst(r => r.expiration.Equals(ccm), out var row)) {
visible_rows.Insert(index, row);
}
}
}
}
}
public ObservableCollection<object> visible_rows { get; set; }
public ObservableAutoWrapper<TRow, VolSurfaceDisplayGridExpiration> rows { get; set; }
public List<VolSurfaceExpiration> get_hidden_exps() { return _hidden_exps; }
public virtual void Dispose() {
_exps_changed_subscription.Dispose();
visible_rows.CollectionChanged -= _visible_rows_changed;
Disposable.dispose(ref _model);
}
protected abstract TRow _row_from_exp(VolSurfaceDisplayGridExpiration exp);
protected virtual void _initialize(object startup_data) { }
void _visible_rows_changed(object sender, NotifyCollectionChangedEventArgs e) {
if (e.Action == NotifyCollectionChangedAction.Remove) {
foreach (IExpirationBasedRow row in e.OldItems)
if (!_hidden_exps.Contains(row.expiration.ToVSExp()))
_hidden_exps.Add(row.expiration.ToVSExp());
} else if (e.Action == NotifyCollectionChangedAction.Add)
foreach (IExpirationBasedRow row in e.NewItems)
if (_hidden_exps.Contains(row.expiration.ToVSExp()))
_hidden_exps.Remove(row.expiration.ToVSExp());
}
}
}
@@ -0,0 +1,102 @@
namespace mbts.spark {
using bts.collections;
using mbts.ui.controls.graph;
using System;
using System.Collections.Generic;
static class VolSurfaceGraphSeriesHelper {
static string _graph_point_format => BTSOxyGraph.get_oxy_plot_point_tracker_string_format(2, false, 2, true);
public static IEnumerable<SeriesVM> get_implied_vol_series(
VolSurfaceDisplayGridExpiration exp, VolSurfaceGraphSettings settings, bool is_visible) {
yield return _get_scatter_series(VolSurfaceGraphSeriesType.ImpliedVolPuts, exp, settings.implied_puts, is_visible);
yield return _get_scatter_series(VolSurfaceGraphSeriesType.ImpliedVolATM, exp, settings.implied_atm, is_visible);
yield return _get_scatter_series(VolSurfaceGraphSeriesType.ImpliedVolCalls, exp, settings.implied_calls, is_visible);
}
public static IEnumerable<SeriesVM> get_vol_path_series(
VolSurfaceDisplayGridExpiration exp, VolSurfaceGraphSettings settings, bool is_visible) {
yield return _get_line_series(VolSurfaceGraphSeriesType.CommittedVolPath, exp, settings.vol_path, is_visible);
yield return _get_line_series(VolSurfaceGraphSeriesType.CandidateVolPath, exp, settings.vol_path, is_visible);
}
public static IEnumerable<SeriesVM> get_all_core_series(
VolSurfaceDisplayGridExpiration exp, VolSurfaceGraphSettings settings) {
// Committed
yield return _get_line_series(VolSurfaceGraphSeriesType.CommittedPutWing, exp, settings.put_wing);
yield return _get_line_series(VolSurfaceGraphSeriesType.CommittedInnerCurve, exp, settings.inner_curve);
yield return _get_line_series(VolSurfaceGraphSeriesType.CommittedCallWing, exp, settings.call_wing);
yield return _get_scatter_series(VolSurfaceGraphSeriesType.CommittedSpecialCalls, exp, settings.call_control_points);
yield return _get_scatter_series(VolSurfaceGraphSeriesType.CommittedSpecialPuts, exp, settings.put_control_points);
// Candidate
yield return _get_line_series(VolSurfaceGraphSeriesType.CandidatePutWing, exp, settings.put_wing);
yield return _get_line_series(VolSurfaceGraphSeriesType.CandidateInnerCurve, exp, settings.inner_curve);
yield return _get_line_series(VolSurfaceGraphSeriesType.CandidateCallWing, exp, settings.call_wing);
yield return _get_scatter_series(VolSurfaceGraphSeriesType.CandidateSpecialCalls, exp, settings.call_control_points);
yield return _get_scatter_series(VolSurfaceGraphSeriesType.CandidateSpecialPuts, exp, settings.put_control_points);
// ATMS
yield return new ScatterSeriesVM {
args = VolSurfaceGraphSeriesType.CommittedATM,
settings = settings.atm,
point_string_format = _graph_point_format
};
yield return new ScatterSeriesVM {
args = VolSurfaceGraphSeriesType.CandidateATM,
settings = settings.atm,
point_string_format = _graph_point_format
};
}
public static void remove_vol_path_series(SeriesSetVM series_set) =>
series_set.series.RemoveWhere(s =>
VolSurfaceGraphSeriesType.CommittedVolPath.Equals(s.args) ||
VolSurfaceGraphSeriesType.CandidateVolPath.Equals(s.args));
static string _get_series_name(VolSurfaceGraphSeriesType series_type, VolSurfaceDisplayGridExpiration exp) =>
series_type switch {
VolSurfaceGraphSeriesType.CommittedPutWing => $"{exp} Committed Put Wing",
VolSurfaceGraphSeriesType.CommittedInnerCurve => $"{exp} Committed",
VolSurfaceGraphSeriesType.CommittedCallWing => $"{exp} Committed Call Wing",
VolSurfaceGraphSeriesType.CommittedSpecialCalls => $"{exp} Committed Special Call Points",
VolSurfaceGraphSeriesType.CommittedSpecialPuts => $"{exp} Committed Special Put Points",
VolSurfaceGraphSeriesType.CommittedVolPath => $"{exp} Committed Vol Path",
VolSurfaceGraphSeriesType.CommittedATM => $"{exp} ATM",
VolSurfaceGraphSeriesType.CandidatePutWing => $"{exp} Candidate Put Wing",
VolSurfaceGraphSeriesType.CandidateInnerCurve => $"{exp} Candidate",
VolSurfaceGraphSeriesType.CandidateCallWing => $"{exp} Candidate Call Wing",
VolSurfaceGraphSeriesType.CandidateSpecialCalls => $"{exp} Candidate Special Call Points",
VolSurfaceGraphSeriesType.CandidateSpecialPuts => $"{exp} Candidate Special Put Points",
VolSurfaceGraphSeriesType.CandidateVolPath => $"{exp} Candidate Vol Path",
VolSurfaceGraphSeriesType.CandidateATM => $"{exp} ATM",
VolSurfaceGraphSeriesType.ImpliedVolPuts => $"{exp} Implied Vol Puts",
VolSurfaceGraphSeriesType.ImpliedVolATM => $"{exp} Implied Vol ATM",
VolSurfaceGraphSeriesType.ImpliedVolCalls => $"{exp} Implied Vol Calls",
_ => throw new ArgumentException("Unexpected series type", nameof(series_type))
};
static LineSeriesVM _get_line_series(
VolSurfaceGraphSeriesType type, VolSurfaceDisplayGridExpiration exp, LineSeriesSettings settings, bool is_visible = true) =>
new() {
args = type,
name = _get_series_name(type, exp),
color = settings.color,
line_style = type.is_committed() ? LineStyle.Solid : LineStyle.Dashed,
stroke_thickness = settings.stroke_thickness,
point_string_format = _graph_point_format
};
static ScatterSeriesVM _get_scatter_series(
VolSurfaceGraphSeriesType type, VolSurfaceDisplayGridExpiration exp, ScatterSeriesSettings settings, bool is_visible = true) =>
new() {
args = type,
name = _get_series_name(type, exp),
settings = settings,
is_visible = is_visible,
point_string_format = _graph_point_format
};
}
}
@@ -0,0 +1,25 @@
namespace mbts.spark {
enum VolSurfaceGraphSeriesType {
CandidatePutWing,
CandidateInnerCurve,
CandidateCallWing,
CandidateSpecialPuts,
CandidateSpecialCalls,
CandidateControlPoints,
CandidateVolPath,
CandidateATM,
CommittedPutWing,
CommittedInnerCurve,
CommittedCallWing,
CommittedSpecialPuts,
CommittedSpecialCalls,
CommittedControlPoints,
CommittedVolPath,
CommittedATM,
ImpliedVolPuts,
ImpliedVolATM,
ImpliedVolCalls
}
}
@@ -0,0 +1,388 @@
using mbts;
using mbts.analytics;
using mbts.spark.VolSurface;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.controls.graph;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Media;
using System.Collections;
using bts.api;
using bts;
using bts.collections;
namespace mbts.spark {
class VolSurfaceGraphVM : DisposableViewModelBase {
readonly VolSurfaceDisplayModel _model;
readonly VolSurfaceEventDemux _demux;
readonly Action<bool, VolSurfaceDisplayGridExpiration> _publish_show_implied_vol;
readonly LinearAxisVM _x_axis = new();
readonly LinearAxisVM _y_axis = new();
readonly Dictionary<SecurityExpiration, ExpGraphBounds> _expiration_graph_bounds;
readonly VolSurfaceGraphSettings _settings;
readonly ObservableCollection<VolSurfaceDisplayGridExpiration> _expirations = new();
VolSurfaceExpiration _md_exp;
VolSurfaceDisplayGridExpiration _expiration;
VolSurfaceDisplayGridExpiration _earliest_selected_expiration;
object _implied_vol_market_side = ImpliedVolHelper.None;
bool _show_vol_path;
public VolSurfaceGraphVM(VolSurfaceDisplayModel model, VolSurfaceEventDemux demux, VolSurfaceWindowSettings startup_data,
Action<bool, VolSurfaceDisplayGridExpiration> publish_show_implied_vol) {
_model = model;
_demux = demux;
_publish_show_implied_vol = publish_show_implied_vol;
if (startup_data.vol_curve_x_axis == null) {
var x_axis = BTSOxyGraphAxisDouble.Default;
x_axis.name = "Strike";
x_axis.major_grid_line_color = BTSColors.Graph.grid_line;
x_axis.minimum = 0;
x_axis.maximum = 2000;
x_axis.axis_title_distance = 7;
startup_data.vol_curve_x_axis = x_axis;
}
if (startup_data.vol_curve_y_axis == null) {
var y_axis = BTSOxyGraphAxisDouble.Default;
y_axis.name = "Volatility";
y_axis.major_grid_line_color = BTSColors.Graph.grid_line;
y_axis.position = AxisPosition.LeftBottomToTop;
y_axis.minimum = 0;
y_axis.maximum = 1;
y_axis.axis_title_distance = 7;
startup_data.vol_curve_y_axis = y_axis;
}
startup_data.vol_curve_y_axis.label_formatter = vol => vol.ToString("P0");
startup_data.vol_curve_visible_series ??= new List<VolSurfaceExpiration>();
startup_data.vol_curve_graph_settings ??= VolSurfaceGraphSettings.get_default();
//_show_mkt_implied_vol = startup_data.show_mkt_implied_vol;
_settings = startup_data.vol_curve_graph_settings;
_settings.vol_path ??= VolSurfaceGraphSettings.get_default_vol_path_settings();
_settings.exp_bounds ??= Array.Empty<ExpGraphBounds>();
_expiration_graph_bounds = _settings.exp_bounds.ToDictionary(_get_security_exp, egb => egb);
settings_command = new DialogCommand(() => {
if (_model.get_active_settings() is not VolSurfaceSettings vss) {
return null;
}
// return new VolSurfaceGraphSettingsEditor {
// DataContext = new VolSurfaceGraphSettingsEditorVM(vss.core_settings.vol_surface_name, ProtoBufSerializationHelper.clone_protobuf(_settings), settings => {
// _settings = settings;
// _recreate_series();
// })
// };
return null;
});
graph_vm = new BTSGraphVM {
plot_area_background = Colors.Transparent,
background = Colors.Transparent,
plot_margins = new System.Windows.Thickness(40, 35, 35, 35)
};
_x_axis.settings = startup_data.vol_curve_x_axis as BTSGraphAxisDouble;
graph_vm.axes.Add(_x_axis);
_y_axis.settings = startup_data.vol_curve_y_axis as BTSGraphAxisDouble;
graph_vm.axes.Add(_y_axis);
_expirations = new ObservableCollection<VolSurfaceDisplayGridExpiration>(_model.get_ordered_expirations());
_model.on_graph_change += _on_graph_tick;
_demux.on_expirations_change += _expirations_changed;
_dispose = Disposable.Create(ObservableAutoWrapper.connect(_expirations, graph_vm.series, _series_from_expiration),
Disposable.Create(() => {
_model.on_graph_change -= _on_graph_tick;
_demux.on_expirations_change -= _expirations_changed;
settings_command.Dispose();
}));
}
public BTSGraphVM graph_vm { get; private set; }
public bool show_implied_vol { get { return !_implied_vol_market_side.Equals(ImpliedVolHelper.None); } }
public IEnumerable market_sides { get { return ImpliedVolHelper.Items; } }
public object implied_vol_market_side { get { return _implied_vol_market_side; } set { using (_change_implied_vol_market_side()) _implied_vol_market_side = value; } }
public bool show_vol_path { get { return _show_vol_path; } set { _show_vol_path = value; _show_vol_path_changed(); } }
public IDialogCommand settings_command { get; private set; }
public VolSurfaceDisplayGridExpiration earliest_selected_expiration { get; set; }
public void set_visible_expiration(VolSurfaceDisplayGridExpiration expiration) {
_earliest_selected_expiration = expiration;
_save_visible_exp_graph_bounds();
_expiration = expiration;
_md_exp = null;
_update(expiration);
graph_vm.title = _get_title();
}
public (BTSGraphAxis x_axis, BTSGraphAxis y_axis) get_graph_axes() =>
(graph_vm.axes.ElementAt(0).settings, graph_vm.axes.ElementAt(1).settings);
public IEnumerable<VolSurfaceExpiration> get_visible_series() {
if (_earliest_selected_expiration != null) {
yield return _earliest_selected_expiration.ToVSExp();
}
}
public VolSurfaceGraphSettings get_settings() {
_save_visible_exp_graph_bounds();
_settings.exp_bounds = _expiration_graph_bounds.Values.ToArray();
return _settings;
}
static SecurityExpiration _get_security_exp(ExpGraphBounds egb) =>
egb == null ? SecurityExpiration.empty : new SecurityExpiration(
Venue.Unset, Security.ContractOneofCase.Option, egb.exp.security.security_name, DateTime.FromOADate(egb.exp.expiration_oa_date));
static (double call_wing_start, double put_wing_start) _get_actual_wing_starts(VolCurveDisplayGraph disp_graph) =>
disp_graph.all_points.Select(p => p.Item1).MinMax() ?? (double.NaN, double.NaN);
void _expirations_changed(IEnumerable<VolSurfaceDisplayGridExpiration> added, IEnumerable<VolSurfaceDisplayGridExpiration> removed) {
_expirations.sync_with(_model.get_ordered_expirations());
_update();
}
void _on_graph_tick() {
if (_expirations.Count != _model.get_ordered_expirations().Count())
_expirations.sync_with(_model.get_ordered_expirations());
_update();
if (_expiration != null) {
var md_exp = _model.get_market_implied_vol_source(_expiration);
if (_md_exp != md_exp) {
_md_exp = md_exp;
graph_vm.title = _get_title();
}
}
}
SeriesSetVM _series_from_expiration(VolSurfaceDisplayGridExpiration exp) {
var exp_ss = new SeriesSetVM {
args = exp,
name = exp.ToString()
};
exp_ss.series.AddRange(VolSurfaceGraphSeriesHelper.get_all_core_series(exp, _settings));
if (show_implied_vol) {
exp_ss.series.AddRange(VolSurfaceGraphSeriesHelper.get_implied_vol_series(exp, _settings, false));
}
if (_show_vol_path) {
exp_ss.series.AddRange(VolSurfaceGraphSeriesHelper.get_vol_path_series(exp, _settings, false));
}
exp_ss.is_visible = exp.Equals(_earliest_selected_expiration);
return exp_ss;
}
IEnumerable<GraphPointVM> _get_points(VolSurfaceDisplayGridExpiration exp, VolSurfaceGraphSeriesType type) {
if (type == VolSurfaceGraphSeriesType.CandidateCallWing
|| type == VolSurfaceGraphSeriesType.CandidatePutWing
|| type == VolSurfaceGraphSeriesType.CandidateInnerCurve
|| type == VolSurfaceGraphSeriesType.CandidateControlPoints
|| type == VolSurfaceGraphSeriesType.CandidateSpecialCalls
|| type == VolSurfaceGraphSeriesType.CandidateSpecialPuts
|| type == VolSurfaceGraphSeriesType.CandidateATM) {
var disp_graph = _model.get_candidate_exp_vol_graph(exp);
if (disp_graph != null) {
var (real_put_wing_start, real_call_wing_start) = _get_actual_wing_starts(disp_graph);
return type switch {
VolSurfaceGraphSeriesType.CandidateCallWing => disp_graph.all_points
.Where(t => t.Item1 >= real_call_wing_start)
.Select(t => new GraphPointVM(t.Item1, t.Item2))
.ToList(),
VolSurfaceGraphSeriesType.CandidatePutWing => disp_graph.all_points
.Where(t => t.Item1 <= real_put_wing_start)
.Select(t => new GraphPointVM(t.Item1, t.Item2))
.ToList(),
VolSurfaceGraphSeriesType.CandidateInnerCurve => disp_graph.all_points
.Where(t => t.Item1 >= real_put_wing_start && t.Item1 <= real_call_wing_start)
.Select(t => new GraphPointVM(t.Item1, t.Item2))
.ToList(),
VolSurfaceGraphSeriesType.CandidateControlPoints => Enumerable.Empty<GraphPointVM>(),
VolSurfaceGraphSeriesType.CandidateSpecialCalls => disp_graph.special_call_points
.Select(t => new GraphPointVM(t.Item1, t.Item2))
.ToList(),
VolSurfaceGraphSeriesType.CandidateSpecialPuts => disp_graph.special_put_points
.Select(t => new GraphPointVM(t.Item1, t.Item2))
.ToList(),
VolSurfaceGraphSeriesType.CandidateATM => new GraphPointVM[] {
new(disp_graph.atm_point.Item1, disp_graph.atm_point.Item2)
},
_ => Enumerable.Empty<GraphPointVM>(),
};
}
}
if (type == VolSurfaceGraphSeriesType.CommittedCallWing
|| type == VolSurfaceGraphSeriesType.CommittedPutWing
|| type == VolSurfaceGraphSeriesType.CommittedInnerCurve
|| type == VolSurfaceGraphSeriesType.CommittedControlPoints
|| type == VolSurfaceGraphSeriesType.CommittedSpecialCalls
|| type == VolSurfaceGraphSeriesType.CommittedSpecialPuts
|| type == VolSurfaceGraphSeriesType.CommittedATM) {
var disp_graph = _model.get_committed_exp_vol_graph(exp);
if (disp_graph != null) {
var (real_put_wing_start, real_call_wing_start) = _get_actual_wing_starts(disp_graph);
return type switch {
VolSurfaceGraphSeriesType.CommittedCallWing => disp_graph.all_points
.Where(t => t.Item1 >= real_call_wing_start)
.Select(t => new GraphPointVM(t.Item1, t.Item2))
.ToList(),
VolSurfaceGraphSeriesType.CommittedPutWing => disp_graph.all_points
.Where(t => t.Item1 <= real_put_wing_start)
.Select(t => new GraphPointVM(t.Item1, t.Item2))
.ToList(),
VolSurfaceGraphSeriesType.CommittedInnerCurve => disp_graph.all_points
.Where(t => t.Item1 >= real_put_wing_start && t.Item1 <= real_call_wing_start)
.Select(t => new GraphPointVM(t.Item1, t.Item2))
.ToList(),
VolSurfaceGraphSeriesType.CommittedControlPoints => Enumerable.Empty<GraphPointVM>(),
VolSurfaceGraphSeriesType.CommittedSpecialCalls => disp_graph.special_call_points
.Select(t => new GraphPointVM(t.Item1, t.Item2)).ToList(),
VolSurfaceGraphSeriesType.CommittedSpecialPuts => disp_graph.special_put_points
.Select(t => new GraphPointVM(t.Item1, t.Item2)).ToList(),
VolSurfaceGraphSeriesType.CommittedATM => new GraphPointVM[] {
new(disp_graph.atm_point.Item1, disp_graph.atm_point.Item2)
},
_ => Enumerable.Empty<GraphPointVM>(),
};
}
}
if (type == VolSurfaceGraphSeriesType.ImpliedVolATM
|| type == VolSurfaceGraphSeriesType.ImpliedVolCalls
|| type == VolSurfaceGraphSeriesType.ImpliedVolPuts) {
var implied_vol_data = _model.get_market_market_implied_vols(exp);
if (implied_vol_data != null) {
switch (type) {
case VolSurfaceGraphSeriesType.ImpliedVolATM: return new GraphPointVM[] { new(implied_vol_data.atm_strike, implied_vol_data.atm_vol) };
case VolSurfaceGraphSeriesType.ImpliedVolCalls: return implied_vol_data.call_rawk_vols.Select(kvp => new GraphPointVM(kvp.Key, kvp.Value)).ToList();
case VolSurfaceGraphSeriesType.ImpliedVolPuts: return implied_vol_data.put_rawk_vols.Select(kvp => new GraphPointVM(kvp.Key, kvp.Value)).ToList();
}
}
}
if (type == VolSurfaceGraphSeriesType.CommittedVolPath) {
return _model.get_committed_volpath(exp).Select(tup => new GraphPointVM(tup.Item1, tup.Item2));
}
if (type == VolSurfaceGraphSeriesType.CandidateVolPath) {
return _model.get_candidate_volpath(exp).Select(tup => new GraphPointVM(tup.Item1, tup.Item2));
}
return Enumerable.Empty<GraphPointVM>();
}
string _get_title() {
if (_expiration is null) {
return string.Empty;
}
if (show_implied_vol && _md_exp != null && _md_exp.symbol != _expiration.symbol) {
var suffix = _md_exp.expiration == _expiration.expiration ? _md_exp.symbol :
new VolSurfaceDisplayGridExpiration(
_md_exp.symbol, _md_exp.expiration, VolSurfaceEnums.VolSurfaceExpirationCalculationMethod.Master)
.ToString();
return $"{_expiration} ({suffix})";
}
return _expiration.ToString();
}
void _save_visible_exp_graph_bounds() {
foreach (var vsd_exp in graph_vm.series_sets.Where(s => s.is_visible).Select(s => (VolSurfaceDisplayGridExpiration)s.args)) {
var sec_exp = vsd_exp.ToSecurityExp();
_expiration_graph_bounds[sec_exp] = new ExpGraphBounds {
exp = new SecurityExpirationProto { security = sec_exp.security_tuple, expiration_oa_date = sec_exp.expiration.ToOADate() },
x_bounds = new AxisBounds { min = _x_axis.minimum, max = _x_axis.maximum },
y_bounds = new AxisBounds { min = _y_axis.minimum, max = _y_axis.maximum }
};
}
}
void _update(VolSurfaceDisplayGridExpiration exp_to_make_visible = null) {
if (exp_to_make_visible != null) {
foreach (var ss in graph_vm.series_sets) {
if (ss.is_visible != exp_to_make_visible.Equals(ss.args)) {
ss.is_visible = !ss.is_visible;
}
}
if (_expiration_graph_bounds.TryGetValue(exp_to_make_visible.ToSecurityExp(), out var egb)) {
_x_axis.minimum = egb.x_bounds.min;
_x_axis.maximum = egb.x_bounds.max;
_y_axis.minimum = egb.y_bounds.min;
_y_axis.maximum = egb.y_bounds.max;
graph_vm.reset_all_axes();
}
}
foreach (var ssvm in graph_vm.series_sets.Where(ss => ss.is_visible)) {
foreach (var svm in ssvm.series) {
svm.points.SetItems(_get_points((VolSurfaceDisplayGridExpiration)ssvm.args, (VolSurfaceGraphSeriesType)svm.args));
// s.points = _get_points((VolSurfaceDisplayGridExpiration)series_set.args, (VolSurfaceGraphSeriesType)s.args));
}
}
// .ForEach(series_set => series_set.series.ForEach(s => s.points = _get_points((VolSurfaceDisplayGridExpiration)series_set.args, (VolSurfaceGraphSeriesType)s.args)));
}
IDisposable _change_implied_vol_market_side() {
bool prev_show = show_implied_vol;
return Disposable.Create(() => {
bool show = show_implied_vol;
if (show != prev_show) {
_publish_show_implied_vol(show, _earliest_selected_expiration);
if (show) {
foreach (var ss in graph_vm.series_sets) {
foreach (var implied_series in VolSurfaceGraphSeriesHelper.get_implied_vol_series((VolSurfaceDisplayGridExpiration)ss.args, _settings, ss.is_visible)) {
ss.series.Insert(0, implied_series);
}
}
} else {
foreach (var ss in graph_vm.series_sets) {
var implied_vol_puts = ss.series.FirstOrDefault(s => s.args.Equals(VolSurfaceGraphSeriesType.ImpliedVolPuts));
ss.series.Remove(implied_vol_puts);
var implied_vol_atm = ss.series.FirstOrDefault(s => s.args.Equals(VolSurfaceGraphSeriesType.ImpliedVolATM));
ss.series.Remove(implied_vol_atm);
var implied_vol_calls = ss.series.FirstOrDefault(s => s.args.Equals(VolSurfaceGraphSeriesType.ImpliedVolCalls));
ss.series.Remove(implied_vol_calls);
}
}
_update();
graph_vm.replot();
}
if (show) {
_model.set_impliedvol_market_side((VolSurfaceEnums.MarketSide)_implied_vol_market_side);
}
});
}
void _show_vol_path_changed() {
if (_show_vol_path) {
foreach (var ss in graph_vm.series_sets) {
if (ss.args is not VolSurfaceDisplayGridExpiration dg_exp) {
throw new InvalidOperationException();
}
foreach (var vps in VolSurfaceGraphSeriesHelper.get_vol_path_series(dg_exp, _settings, ss.is_visible)) {
ss.series.Insert(0, vps);
}
}
} else {
foreach (var ss in graph_vm.series_sets) {
VolSurfaceGraphSeriesHelper.remove_vol_path_series(ss);
}
}
_update();
graph_vm.replot();
}
static class ImpliedVolHelper {
public const string None = "None";
public static IEnumerable Items {
get {
yield return None;
foreach (var side in EnumHelper.get_values<VolSurfaceEnums.MarketSide>()) {
yield return side;
}
}
}
}
}
}
@@ -0,0 +1,200 @@
namespace mbts.spark {
using mbts.spark.VolSurface;
using mbts.ui;
using mbts.ui.controls;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
class VolSurfaceRowControl : DIYGrid.RowBase {
readonly double _padding = 5.0;
readonly Pen _dirty_pen = new(Brushes.Red, 1.0);
readonly Pen _selection_pen = new(Brushes.Black, 1.0) { DashStyle = DashStyles.Dot };
VolSurfaceRowContext _row;
FormattedText _exp_text;
public VolSurfaceRowControl() {
DataContextChanged += on_data_context_changed;
Loaded += on_loaded;
void on_loaded(object sender, RoutedEventArgs e) =>
ContextMenu = TryFindResource("context_menu") as ContextMenu;
void on_data_context_changed(object sender, DependencyPropertyChangedEventArgs e) {
if (e.OldValue is VolSurfaceRowContext oldrow) {
oldrow.invalidated -= InvalidateVisual;
}
_row = e.NewValue as VolSurfaceRowContext;
if (_row != null) {
_row.invalidated += InvalidateVisual;
}
}
}
//private static int _render_count = 0;
protected override void OnRender(DrawingContext dc) {
if (_grid == null) return;
// Fill with transparent for hit testing
dc.DrawRectangle(Brushes.Transparent, null, new Rect(0, 0, _column_geometry.Sum(g => g.width), RenderSize.Height));
string last_group = "";
foreach (var cell in _column_geometry) {
// Render collapsed columns
if (cell.column.is_collapsed) {
dc.DrawRectangle(BTSColors.AW2.collapsed, null, new Rect(cell.left, 0, cell.width, Height));
continue;
}
var column = (VolSurfaceSimplifiedColumn)cell.column;
VolSurfaceCellState celldata;
// Get the cell text
if (column.type == VolSurfaceSimplifiedColumnType.RowHeader) {
// Fill in this one
dc.DrawRectangle(BTSColors.header, null, new Rect(cell.left, 0, cell.width, Height));
var exp = _row.expiration;
_exp_text ??= format_text(exp.ToString(), exp.is_slave ? Brushes.LightGray : Brushes.White);
celldata = new VolSurfaceCellState() { text = _exp_text };
} else if (column.type == VolSurfaceSimplifiedColumnType.ReadOnly) {
celldata = _row.get_value(column.volsurface_column, format(Brushes.Blue), _ => null);
} else {
celldata = _row.get_value(column.volsurface_column, format(Brushes.Black), format(Brushes.DarkGray));
}
// If the cell is partly hidden clip the draw
if (cell.is_partially_obscured) {
dc.PushClip(new RectangleGeometry(
new Rect(cell.left, 0, cell.width, Height)));
}
// draw text centered vertially
double total_width = _padding + celldata.text.Width;
double pad_top = (Height - celldata.text.Height) / 2.0;
dc.DrawText(celldata.text, new Point(cell.unclipped_left + _padding, pad_top));
if (celldata.committed_text != null) {
pad_top = (Height - celldata.committed_text.Height) / 2.0;
dc.DrawText(celldata.committed_text, new Point(cell.unclipped_left + total_width, pad_top));
total_width += celldata.committed_text.Width;
}
// draw grid lines
double line_width; Brush fill;
if (last_group == cell.group) {
line_width = 1;
fill = _grid.VerticalGridLineBrush;
} else {
line_width = 2;
fill = _grid.VerticalGroupSeparatorBrush;
}
dc.DrawRectangle(fill, null, new Rect(cell.left - line_width, 0, line_width, Height));
var cell_border_rect = new Rect(cell.unclipped_left + 1, 0, Math.Max(0, cell.width - (line_width * 2)), Height - 1);
// draw dirty rect
if (celldata.is_dirty) {
dc.DrawRectangle(null, _dirty_pen, cell_border_rect);
}
// Draw selection
if (_selected_cell == DIYGrid.RowUtils.column_index(_column_geometry, cell) && column.type != VolSurfaceSimplifiedColumnType.ReadWriteTick) {
dc.DrawRectangle(null, _selection_pen, cell_border_rect);
}
if (cell.is_partially_obscured) { dc.Pop(); }
total_width += _padding;//right padding
if (!celldata.is_dirty && column.type == VolSurfaceSimplifiedColumnType.ReadWriteTick) total_width += 22; // size of buttons on a tickupdown
if (total_width > cell.width) {
Dispatcher.BeginInvoke(((Action)(() => cell.column.Width = total_width)));
}
last_group = cell.group;
}
if (_selected_cell.HasValue) {
var tud = _grid.get_edit_control<TickUpDown>();
if (tud.Visibility == Visibility.Visible) {
var position = _column_geometry[_selected_cell.Value];
PositionControlOver(tud, position);
}
}
}
protected FormattedText format_text(string text, Brush brush) =>
new(text, CultureInfo.CurrentCulture, FlowDirection.LeftToRight, ui.utility.text.TextUtils.StandardTypeface, FontSizes.Regular, brush, ui.dpi.HighDpiExtensions.dpi_ratio);
Func<string, FormattedText> format(Brush brush) =>
str => format_text(str, brush);
protected override void OnClick(DIYGrid.ColumnGeometry column) { }
protected override void OnFocusMove(DIYGrid.ColumnGeometry? new_column) {
if (new_column != null) {
_enable_edit(new_column.Value);
}
InvalidateVisual();
}
async void _enable_edit(DIYGrid.ColumnGeometry column) {
await Task.Yield();
var col = (VolSurfaceSimplifiedColumn)column.column;
var edit_control = _grid.get_edit_control<TickUpDown>();
if (col.type == VolSurfaceSimplifiedColumnType.ReadWriteTick) {
edit_control.set_current_if_changed<object>(DataContextProperty, _row.get_edit_context(col.volsurface_column));
PositionControlOver(edit_control, column);
if (edit_control.Content is TextBox fe) {
await Task.Yield();
fe.Focus();
fe.SelectAll();
}
} else {
edit_control.set_current_if_changed<object>(DataContextProperty, null);
edit_control.set_current_if_changed(VisibilityProperty, Visibility.Collapsed);
this.find_ancestor_of_type<ListBoxItem>()?.Focus();
}
}
protected override void OnMouseRightButtonUp(MouseButtonEventArgs e) {
var cell = DIYGrid.RowUtils.column_at(_column_geometry, e.GetPosition(this));
if (ContextMenu != null) {
if (cell.HasValue && DIYGrid.RowUtils.column_index(_column_geometry, cell.Value) > (_grid.FrozenColumnCount - 1)) {
ContextMenu.DataContext = _row.get_context_menu_context((VolSurfaceSimplifiedColumn)cell.Value.column, cell.Value.super_column);
} else {
e.Handled = true;
ContextMenu.DataContext = null;
}
}
base.OnMouseRightButtonDown(e);
}
protected FrameworkElement PositionControlOver(FrameworkElement control, DIYGrid.ColumnGeometry column) {
//Point visible_left = TranslatePoint(new Point(column.left, 0), _grid);
Point actual_left = TranslatePoint(new Point(column.unclipped_left, 0), _grid);
// Use the margin to position the control
control.Margin = new Thickness(actual_left.X + 1, actual_left.Y + 1, 0, 0);
control.Width = Math.Max(column.width - 2, 0);
control.Height = Height;
if (column.is_partially_obscured) {
var clipped_width = column.left - column.unclipped_left;
control.Clip = new RectangleGeometry(
// Rect is in the coordinate space of the edit control
new Rect(
clipped_width,
0,
column.width - clipped_width,
Height));
} else {
control.Clip = null;
}
control.set_current_if_changed(VisibilityProperty, Visibility.Visible);
control.Focus();
return control;
}
}
}
@@ -0,0 +1,349 @@
using mbts;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace mbts.spark.VolSurface {
public struct VolSurfaceCellState {
public bool is_dirty => committed_text != null;
public FormattedText text;
public FormattedText committed_text;
}
class VolSurfaceRowContext : ViewModelBase, ISelectable, IFormatCellsToClipboard, DIYGrid.IRowVM {
readonly VolSurfaceSimplifiedGridVM _parent;
readonly VolSurfaceDisplayGridExpiration _exp;
readonly Dictionary<string, VolSurfaceCellState> _text_cache = new();
bool _is_selected;
public VolSurfaceRowContext(VolSurfaceSimplifiedGridVM parent, VolSurfaceDisplayGridExpiration exp) {
_parent = parent;
_exp = exp;
}
public event Action<bool> is_selected_changed;
public event Action invalidated;
public VolSurfaceDisplayGridExpiration expiration => _exp;
public bool is_selected {
get => _is_selected;
set {
if (_is_selected != value) {
_is_selected = value;
is_selected_changed?.Invoke(value);
_parent.signal_selection_changed();
}
}
}
public void invalidate() {
// todo: only clear changed values in cache
_text_cache.Clear();
raise_invalidated();
}
public VolSurfaceCellState get_value(
VolSurfaceDisplayGridColumn column,
Func<string, FormattedText> format_active,
Func<string, FormattedText> format_committed) {
// This class owns the cache of formatted values but does not need
// access to font information so it accepts a format function from
// the View layer We could have designed this function to return a
// base string instead of a FormattedText object but it would have
// required the caller to have a second level of cache with a second
// dictionary
if (_text_cache.TryGetValue(column.unique_col_name, out var value)) {
return value;
}
string current_value = _parent.current_grid.read(_exp, column);
value.text = format_active(current_value);
if (_parent.is_dirty) {
string committed_value = _parent.committed_grid.read(_exp, column);
// Only show this if its different from candidate
if (committed_value != current_value) {
value.committed_text = current_value == committed_value ? null : format_committed(" (" + committed_value + ")");
}
}
_text_cache[column.unique_col_name] = value;
return value;
}
public override string ToString() =>
_exp.ToString();
public string[] get_cell_clipboard_strings() =>
new[] { _exp.ToString() }.Concat(
_parent.columns.OfType<VolSurfaceSimplifiedColumn>()
.Skip(1)
.Select(c => _parent.current_grid.read(_exp, c.volsurface_column)))
.ToArray();
public void raise_invalidated() =>
invalidated?.Invoke();
internal EditContext get_edit_context(VolSurfaceDisplayGridColumn column) =>
new(_parent, _exp, column);
internal MenuContext get_context_menu_context(VolSurfaceSimplifiedColumn column, DIYGridSuperHeader header) =>
new(_parent, _exp, column, header);
internal class EditContext : ViewModelBase {
readonly VolSurfaceDisplayGridColumn _col;
readonly VolSurfaceDisplayGridExpiration _exp;
readonly VolSurfaceSimplifiedGridVM _parent;
string _current_value;
int _tick_count;
public EditContext(VolSurfaceSimplifiedGridVM grid, VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn column) {
_parent = grid;
_exp = exp;
_col = column;
_current_value = _parent.current_grid.read(_exp, _col);
}
public string value {
get => _current_value;
set {
if (_current_value == value) {
return;
}
var grid = _parent.current_grid;
if (grid.write(_exp, _col, value)) {
_commit(grid);
}
}
}
public ICommand tick_up => new DelegateCommand(_ => _tick(TickDirection.UP), _ => _can_tick(TickDirection.UP));
public ICommand tick_down => new DelegateCommand(_ => _tick(TickDirection.DOWN), _ => _can_tick(TickDirection.DOWN));
void _commit(VolSurfaceDisplayGrid grid) =>
_parent.model.set_candidate_grid(grid);
async void _enqueue_commit(VolSurfaceDisplayGrid grid) {
_tick_count++;
var my_count = _tick_count;
grid = (VolSurfaceDisplayGrid)grid.Clone();
await Task.Delay(250);
if (my_count == _tick_count) {
_commit(grid);
}
}
bool _can_tick(TickDirection dir) =>
_parent.current_grid.can_tick(_exp, _col, dir);
void _tick(TickDirection dir) {
if (!_can_tick(dir)) {
return;
}
// Intentionally mutate the parent grid.
// It might get overwritten but this increases the chances that a fast navigation will capture our latest value
var grid = _parent.current_grid;
// Write the current value to the grid before ticking up
// This ensures that even if the grid has changed
// the user's input value is respected
grid.write(_exp, _col, _current_value);
grid.handle_tick(_exp, _col, dir, out _current_value);
_enqueue_commit(grid);
RaisePropertyChanged("value");
}
}
internal class MenuContext {
readonly VolSurfaceSimplifiedColumn _col;
readonly DIYGridSuperHeader _supercol;
readonly VolSurfaceDisplayGridExpiration _row;
readonly VolSurfaceSimplifiedGridVM _parent;
ICommand _revert_command;
ICommand _shift_selection_command;
ICommand _shift_masters_command;
ICommand _shift_all_command;
ICommand _clear_command;
ICommand _copy_to_selection_command;
ICommand _copy_to_masters_command;
ICommand _copy_to_all_command;
ICommand _copy_all_to_clipboard_command;
ICommand _smart_copy_rolls_rates_command;
ICommand _import_csv_command;
public MenuContext(
VolSurfaceSimplifiedGridVM parent,
VolSurfaceDisplayGridExpiration exp,
VolSurfaceSimplifiedColumn col,
DIYGridSuperHeader supercol) {
_parent = parent;
_col = col;
_supercol = supercol;
_row = exp;
}
public string column_name => _col.volsurface_column.display_name;
public string group_name => _supercol.FullHeader;
public string expiration_name => _row.ToString();
public class SymbolFilter {
readonly MenuContext _context;
bool? _visible;
public SymbolFilter(MenuContext context, string symbol, int count, int visible_count) {
_context = context;
this.symbol = symbol;
if (count == visible_count) {
_visible = true;
} else if (visible_count == 0) {
_visible = false;
} else {
_visible = null;
}
}
public string symbol { get; private set; }
public bool? visible {
get => _visible;
set {
_visible = value;
if (value == true) {
_context._show_symbol(symbol);
} else if (value == false) {
_context._hide_symbol(symbol);
}
}
}
}
public IEnumerable<SymbolFilter> symbols {
get {
var visible_exps = _parent.visible_rows
.Cast<VolSurfaceRowContext>()
.GroupBy(r => r._exp.symbol)
.ToDictionary(g => g.Key);
var result = _parent.rows
.GroupBy(r => r._exp.symbol)
.OrderBy(g => g.Key)
.Select(g => new SymbolFilter(this, g.Key, g.Count(), visible_exps.ContainsKey(g.Key) ? visible_exps[g.Key].Count() : 0));
return result;
}
}
public bool is_input_cell => _col.type == VolSurfaceSimplifiedColumnType.ReadWriteTick;
public ICommand main_settings_command => _parent.main_settings_command;
public ICommand advanced_settings_command => _parent.advanced_settings_command;
public ICommand grid_settings_command => _parent.grid_settings_command;
public ICommand graph_settings_command => _parent.graph_settings_command;
public ICommand revert_command =>
_revert_command ??= new DelegateCommand(_ => {
_parent.current_grid.write(_row, _col.volsurface_column,
_parent.committed_grid.read(_row, _col.volsurface_column));
_parent.model.set_candidate_grid(_parent.current_grid);
});
public ICommand shift_selection_command =>
_shift_selection_command ??= new DelegateCommand(() => {
if (_col.volsurface_column is VolSurfaceDisplayGridTextInputColumn col) {
_parent.shift_selection(col);
}
}, () => _col.volsurface_column is VolSurfaceDisplayGridTextInputColumn);
public ICommand shift_masters_command =>
_shift_masters_command ??= new DelegateCommand(() => {
if (_col.volsurface_column is VolSurfaceDisplayGridTextInputColumn col) {
_parent.shift_masters(col);
}
}, () => _col.volsurface_column is VolSurfaceDisplayGridTextInputColumn);
public ICommand shift_all_command =>
_shift_all_command ??= new DelegateCommand(() => {
if (_col.volsurface_column is VolSurfaceDisplayGridTextInputColumn col) {
_parent.shift_all(col);
}
}, () => _col.volsurface_column is VolSurfaceDisplayGridTextInputColumn);
public ICommand clear_command =>
_clear_command ??= new DelegateCommand<string>(where => {
if (Enum.TryParse(where, out GridColumnSet gc)) {
_parent.clear(_col.volsurface_column, gc);
}
},
_has_editable_cells);
public ICommand copy_to_selection_command =>
_copy_to_selection_command ??= new DelegateCommand<string>(where => {
if (Enum.TryParse(where, out GridColumnSet gc)) {
_parent.copy_to_selection(_row, _col.volsurface_column, gc);
}
},
_has_editable_cells);
public ICommand copy_to_masters_command =>
_copy_to_masters_command ??= new DelegateCommand<string>(where => {
if (Enum.TryParse(where, out GridColumnSet gc)) {
_parent.copy_to_masters(_row, _col.volsurface_column, gc);
}
},
_has_editable_cells);
public ICommand copy_to_all_command =>
_copy_to_all_command ??= new DelegateCommand<string>(where => {
if (Enum.TryParse(where, out GridColumnSet gc)) {
_parent.copy_to_all(_row, _col.volsurface_column, gc);
}
},
_has_editable_cells);
public ICommand copy_all_to_clipboard_command =>
_copy_all_to_clipboard_command ??= new DelegateCommand(() => {
string clipboard_text = ClipboardHelper.GetExcelFormattedText(
_parent.visible_rows
.OfType<VolSurfaceRowContext>()
.Select(r => r.get_cell_clipboard_strings())
.Where(cells => cells != null));
if (!clipboard_text.is_null_or_empty()) {
ClipboardHelper.CopyTextToClipboard(clipboard_text);
}
});
public ICommand smart_copy_rolls_rates_command =>
_smart_copy_rolls_rates_command ??= new DelegateCommand(_ => _parent.model.sync_slave_ref_forwards(_row.ToVSExp()));
public ICommand import_csv_command =>
_import_csv_command ??= FileDialogCommand.open_file(
_parent.model.import_csv_file,
() => _parent.model.csv_importing_enabled(),
null);
bool _has_editable_cells(string where) =>
!Enum.TryParse(where, out GridColumnSet gc) ||
gc == GridColumnSet.Column || _col.volsurface_column is not VolSurfaceDisplayGridTextOutputColumn;
void _hide_symbol(string symbol) {
_parent.visible_rows.RemoveAll(s => ((VolSurfaceRowContext)s).expiration.symbol == symbol);
_parent.signal_selection_changed();
}
void _show_symbol(string symbol) {
// Insert items from rows to visible_Rows that have symbol=true in sorted order
// do this by making the desired collection and then leveraging sync_with
var visible = new HashSet<VolSurfaceDisplayGridExpiration>(_parent.visible_rows.Cast<VolSurfaceRowContext>().Select(row => row.expiration));
var desired = _parent.rows.Where(row => row.expiration.symbol == symbol || visible.Contains(row.expiration));
_parent.visible_rows.sync_with(desired);
}
}
}
}
@@ -0,0 +1,372 @@
// using mbts;
// using mbts.ui;
// using mbts.ui.controls;
// using mbts.ui.dpi;
// using mbts.ui.utility.text;
// using System;
// using System.Collections.Generic;
// using System.Diagnostics;
// using System.Globalization;
// using System.Linq;
// using System.Text;
// using System.Threading.Tasks;
// using System.Windows;
// using System.Windows.Controls;
// using System.Windows.Input;
// using System.Windows.Media;
// namespace mbts.spark.VolSurface {
// class VolSurfaceRowControl : DIYGrid.HighPerformanceRow<VolSurfaceRowContext> {
// FormattedText _exp_text;
// readonly double _padding = 5.0;
// readonly Pen _dirty_pen = new Pen(Brushes.Red, 1.0);
// readonly Pen _selection_pen = new Pen(Brushes.Black, 1.0) { DashStyle = DashStyles.Dot };
// TickUpDown _cell_editor_backing;
// TickUpDown _cell_editor => _cell_editor_backing ??= new ();
// int? _selected_cell;
// public VolSurfaceRowControl() {
// Loaded += (s, e) => ContextMenu = TryFindResource("context_menu") as ContextMenu;
// GotKeyboardFocus += (s, e) => {
// if (e.OriginalSource is not FrameworkElement el) {
// return;
// }
// var cell_tl = el.TranslatePoint(new Point(0, 0), this);
// _on_focus_move(DIYGrid.RowUtils.column_at(_column_layout, cell_tl));
// };
// }
// int? _column_index(DIYGrid.ColumnGeometry col) =>
// _column_layout.TryGetFirst(c => c.Equals(col), out var _, out var idx) ? idx : null;
// //private static int _render_count = 0;
// protected override void OnRender(DrawingContext dc) {
// // Fill with transparent for hit testing
// dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)), null, new Rect(0, 0, _column_layout.Sum(c => c.width), RenderSize.Height));
// string last_group = "";
// foreach (var cell in _column_layout) {
// // Render collapsed columns
// if (cell.column.is_collapsed) {
// dc.DrawRectangle(BTSColors.AW2.collapsed, null, new Rect(cell.left, 0, cell.width, Height));
// continue;
// }
// var column = (VolSurfaceSimplifiedColumn)cell.column;
// VolSurfaceCellState celldata;
// // Get the cell text
// if (column.type == VolSurfaceSimplifiedColumnType.RowHeader) {
// // Fill in this one
// dc.DrawRectangle(BTSColors.header, null, new Rect(cell.left, 0, cell.width, Height));
// var exp = _row.expiration;
// if (_exp_text == null) {
// _exp_text = format_text(exp.ToString(), exp.is_slave ? Brushes.LightGray : Brushes.White);
// }
// celldata = new VolSurfaceCellState() {
// text = _exp_text
// };
// } else if (column.type == VolSurfaceSimplifiedColumnType.ReadOnly) {
// celldata = _row.get_value(column.volsurface_column, format(Brushes.Blue), _ => null);
// } else {
// celldata = _row.get_value(column.volsurface_column, format(Brushes.Black), format(Brushes.DarkGray));
// }
// // If the cell is partly hidden clip the draw
// if (cell.is_partially_obscured) {
// dc.PushClip(new RectangleGeometry(
// new Rect(cell.left, 0, cell.width, Height)));
// }
// // draw text centered vertially
// double total_width = _padding + celldata.text.Width;
// double pad_top = (Height - celldata.text.Height) / 2.0;
// dc.DrawText(celldata.text, new Point(cell.unclipped_left + _padding, pad_top));
// if (celldata.committed_text != null) {
// pad_top = (Height - celldata.committed_text.Height) / 2.0;
// dc.DrawText(celldata.committed_text, new Point(cell.unclipped_left + total_width, pad_top));
// total_width += celldata.committed_text.Width;
// }
// // draw grid lines
// double line_width; Brush fill;
// if (last_group == cell.group) { line_width = 1; fill = _grid.VerticalGridLineBrush; } else { line_width = 2; fill = _grid.VerticalGroupSeparatorBrush; }
// dc.DrawRectangle(fill, null, new Rect(cell.left - line_width, 0, line_width, Height));
// Rect cell_border_rect = new Rect(cell.unclipped_left + 1, 0, Math.Max(0, cell.width - (line_width * 2)), Height - 1);
// // draw dirty rect
// if (celldata.is_dirty) {
// dc.DrawRectangle(null, _dirty_pen, cell_border_rect);
// }
// // Draw selection
// if (_selected_cell == _column_index(cell) && column.type != VolSurfaceSimplifiedColumnType.ReadWriteTick) {
// dc.DrawRectangle(null, _selection_pen, cell_border_rect);
// }
// if (cell.is_partially_obscured) { dc.Pop(); }
// total_width += _padding;//right padding
// if (!celldata.is_dirty && column.type == VolSurfaceSimplifiedColumnType.ReadWriteTick) total_width += 22; // size of buttons on a tickupdown
// if (total_width > cell.width) {
// Dispatcher.BeginInvoke(((Action)(() => cell.column.Width = total_width)));
// }
// last_group = cell.group;
// }
// if (_selected_cell != NO_CELL) {
// if (_cell_editor.Visibility == Visibility.Visible) {
// var position = _column_geometry[_selected_cell];
// PositionControlOver(tud, position);
// }
// }
// //++_render_count;
// //dc.DrawText(
// // format_text(_render_count.ToString(), Brushes.Black),
// // new Point(0, 0));
// }
// Func<string, FormattedText> format(Brush brush) =>
// str => format_text(str, brush);
// void _on_focus_move(DIYGrid.ColumnGeometry? new_column) {
// if (new_column != null) {
// enable_edit(new_column.Value);
// }
// InvalidateVisual();
// }
// private async void enable_edit(DIYGrid.ColumnGeometry column) {
// await Task.Yield();
// var col = (VolSurfaceSimplifiedColumn)column.column;
// var tud = _grid.get_edit_control<TickUpDown>();
// if (col.type == VolSurfaceSimplifiedColumnType.ReadWriteTick) {
// tud.DataContext = _row.get_edit_context(col.volsurface_column);
// PositionControlOver(tud, column);
// var fe = tud.Content as TextBox;
// if (fe != null) {
// await Task.Yield();
// fe.Focus();
// fe.SelectAll();
// }
// } else {
// tud.DataContext = null;
// tud.Visibility = Visibility.Collapsed;
// var item = this.find_ancestor_of_type<ListBoxItem>();
// if (item != null) {
// item.Focus();
// }
// }
// }
// protected override void OnMouseRightButtonUp(MouseButtonEventArgs e) {
// // _grid.column
// var cell = DIYGrid.RowUtils.column_at(_column_layout, e.GetPosition(this));
// if (ContextMenu != null) {
// if (cell.HasValue && DIYGrid.RowUtils.column_index(_column_layout, cell.Value) > (_grid.FrozenColumnCount - 1)) {
// ContextMenu.DataContext = _row.get_context_menu_context((VolSurfaceSimplifiedColumn)cell.Value.column, cell.Value.super_column);
// } else {
// e.Handled = true;
// ContextMenu.DataContext = null;
// }
// }
// base.OnMouseRightButtonDown(e);
// }
// FormattedText format_text(string content, Brush fg) {
// var ft = new FormattedText(content, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
// TextUtils.StandardTypeface, FontSizes.Regular, Brushes.Black, HighDpiExtensions.dpi_ratio);
// return ft;
// }
// }
// }
// using mbts;
// using mbts.ui;
// using mbts.ui.controls;
// using mbts.ui.dpi;
// using mbts.ui.utility.text;
// using System;
// using System.Collections.Generic;
// using System.Diagnostics;
// using System.Globalization;
// using System.Linq;
// using System.Text;
// using System.Threading.Tasks;
// using System.Windows;
// using System.Windows.Controls;
// using System.Windows.Input;
// using System.Windows.Media;
// namespace mbts.spark.VolSurface {
// class VolSurfaceRowControl : DIYGrid.RowBase {
// VolSurfaceRowContext _row;
// FormattedText _exp_text;
// readonly double _padding = 5.0;
// readonly Pen _dirty_pen = new Pen(Brushes.Red, 1.0);
// readonly Pen _selection_pen = new Pen(Brushes.Black, 1.0) { DashStyle = DashStyles.Dot };
// public VolSurfaceRowControl() {
// DataContextChanged += OnDataContextChanged;
// Loaded += OnLoaded;
// }
// #region SelectedCell
// public static readonly DependencyProperty SelectedCellProperty =
// WPFHelper.create_dp<object, VolSurfaceRowControl>(nameof(SelectedCell));
// public object SelectedCell {
// get => GetValue(SelectedCellProperty);
// set => SetValue(SelectedCellProperty, value);
// }
// #endregion
// void OnLoaded(object sender, RoutedEventArgs e) {
// ContextMenu = TryFindResource("context_menu") as ContextMenu;
// }
// void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
// var oldrow = e.OldValue as VolSurfaceRowContext;
// if (oldrow != null) {
// oldrow.on_invalidate -= InvalidateVisual;
// }
// _row = DataContext as VolSurfaceRowContext;
// _row.on_invalidate += InvalidateVisual;
// }
// //private static int _render_count = 0;
// protected override void OnRender(DrawingContext dc) {
// if (_grid == null) return;
// // Fill with transparent for hit testing
// dc.DrawRectangle(new SolidColorBrush(Color.FromArgb(0, 0, 0, 0)), null, new Rect(0, 0, _column_geometry.Sum(g => g.width), RenderSize.Height));
// string last_group = "";
// foreach (var cell in _column_geometry) {
// // Render collapsed columns
// if (cell.column.is_collapsed) {
// dc.DrawRectangle(BTSColors.AW2.collapsed, null, new Rect(cell.left, 0, cell.width, Height));
// continue;
// }
// var column = (VolSurfaceSimplifiedColumn)cell.column;
// VolSurfaceCellState celldata;
// // Get the cell text
// if (column.type == VolSurfaceSimplifiedColumnType.RowHeader) {
// // Fill in this one
// dc.DrawRectangle(BTSColors.header, null, new Rect(cell.left, 0, cell.width, Height));
// var exp = _row.expiration;
// if (_exp_text == null) {
// _exp_text = format_text(exp.ToString(), exp.is_slave ? Brushes.LightGray : Brushes.White);
// }
// celldata = new VolSurfaceCellState() { text = _exp_text };
// } else if (column.type == VolSurfaceSimplifiedColumnType.ReadOnly) {
// celldata = _row.get_value(column.volsurface_column, format(Brushes.Blue), _ => null);
// } else {
// celldata = _row.get_value(column.volsurface_column, format(Brushes.Black), format(Brushes.DarkGray));
// }
// // If the cell is partly hidden clip the draw
// if (cell.is_partially_obscured) {
// dc.PushClip(new RectangleGeometry(
// new Rect(cell.left, 0, cell.width, Height)));
// }
// // draw text centered vertially
// double total_width = _padding + celldata.text.Width;
// double pad_top = (Height - celldata.text.Height) / 2.0;
// dc.DrawText(celldata.text, new Point(cell.unclipped_left + _padding, pad_top));
// if (celldata.committed_text != null) {
// pad_top = (Height - celldata.committed_text.Height) / 2.0;
// dc.DrawText(celldata.committed_text, new Point(cell.unclipped_left + total_width, pad_top));
// total_width += celldata.committed_text.Width;
// }
// // draw grid lines
// double line_width; Brush fill;
// if (last_group == cell.group) { line_width = 1; fill = _grid.VerticalGridLineBrush; } else { line_width = 2; fill = _grid.VerticalGroupSeparatorBrush; }
// dc.DrawRectangle(fill, null, new Rect(cell.left - line_width, 0, line_width, Height));
// Rect cell_border_rect = new Rect(cell.unclipped_left + 1, 0, Math.Max(0, cell.width - (line_width * 2)), Height - 1);
// // draw dirty rect
// if (celldata.is_dirty) {
// dc.DrawRectangle(null, _dirty_pen, cell_border_rect);
// }
// // Draw selection
// if (_selected_cell == column_index(cell) && column.type != VolSurfaceSimplifiedColumnType.ReadWriteTick) {
// dc.DrawRectangle(null, _selection_pen, cell_border_rect);
// }
// if (cell.is_partially_obscured) { dc.Pop(); }
// total_width += _padding;//right padding
// if (!celldata.is_dirty && column.type == VolSurfaceSimplifiedColumnType.ReadWriteTick) total_width += 22; // size of buttons on a tickupdown
// if (total_width > cell.width) {
// Dispatcher.BeginInvoke(((Action)(() => cell.column.Width = total_width)));
// }
// last_group = cell.group;
// }
// //++_render_count;
// //dc.DrawText(
// // format_text(_render_count.ToString(), Brushes.Black),
// // new Point(0, 0));
// }
// private Func<string, FormattedText> format(Brush brush) {
// return str => format_text(str, brush);
// }
// protected override void OnClick(DIYGrid.ColumnGeometry column) {
// }
// protected override void OnFocusMove(DIYGrid.ColumnGeometry? new_column) {
// if (new_column != null) enable_edit(new_column.Value);
// InvalidateVisual();
// }
// private async void enable_edit(DIYGrid.ColumnGeometry column) {
// await Task.Yield();
// var col = (VolSurfaceSimplifiedColumn)column.column;
// var tud = _grid.get_edit_control<TickUpDown>();
// if (col.type == VolSurfaceSimplifiedColumnType.ReadWriteTick) {
// tud.DataContext = _row.get_edit_context(col.volsurface_column);
// PositionControlOver(tud, column);
// var fe = tud.Content as TextBox;
// if (fe != null) {
// await Task.Yield();
// fe.Focus();
// fe.SelectAll();
// }
// } else {
// tud.DataContext = null;
// tud.Visibility = Visibility.Collapsed;
// var item = this.find_ancestor_of_type<ListBoxItem>();
// if (item != null) {
// item.Focus();
// }
// }
// }
// protected override void OnMouseRightButtonUp(MouseButtonEventArgs e) {
// var cell = column_at(e.GetPosition(this));
// if (ContextMenu != null) {
// if (cell.HasValue && column_index(cell.Value) > (_grid.FrozenColumnCount - 1)) {
// ContextMenu.DataContext = _row.get_context_menu_context((VolSurfaceSimplifiedColumn)cell.Value.column, cell.Value.super_column);
// } else {
// e.Handled = true;
// ContextMenu.DataContext = null;
// }
// }
// base.OnMouseRightButtonDown(e);
// }
// FormattedText format_text(string content, Brush fg) {
// var ft = new FormattedText(content, CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
// TextUtils.StandardTypeface, FontSizes.Regular, Brushes.Black, HighDpiExtensions.dpi_ratio);
// return ft;
// }
// }
// }
@@ -0,0 +1,6 @@
namespace mbts.ui.shell {
using mbts.spark.VolSurface;
using mbts.ui.controls;
class VolSurfaceRowView : DIYGrid.HighPerformanceRow<VolSurfaceRowContext> { }
}
@@ -0,0 +1,350 @@
using mbts;
using mbts.collections;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.converters;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using mbts.analytics;
using System.Diagnostics;
using bts;
using System.Windows.Controls;
namespace mbts.spark.VolSurface {
enum VolSurfaceSimplifiedColumnType {
RowHeader,
ReadOnly,
ReadWriteTick
}
class VolSurfaceSimplifiedColumn : DIYGrid.FrameworkElementColumnBase<string> {
public VolSurfaceSimplifiedColumn(VolSurfaceSimplifiedColumnType type, string header, VolSurfaceDisplayGridColumn c)
: base(c?.unique_col_name ?? "Expiration") {
this.type = type;
volsurface_column = c;
Header = header;
is_visible = true;
Width = 80;
id = key ?? throw new InvalidOperationException("Column key cannot be null");
}
public VolSurfaceSimplifiedColumnType type { get; private set; }
public VolSurfaceDisplayGridColumn volsurface_column { get; private set; }
public override FrameworkElement view_factory() {
var rv = new TextBlock { Text = "test"};
return rv;
}
}
class VolSurfaceSimplifiedGridVM : DisposableViewModelBase {
readonly VolSurfaceVM _parent;
readonly ObservableCollection<VolSurfaceDisplayGridExpiration> _expirations = new();
readonly ObservableCollection<VolSurfaceDisplayGridColumn> _internal_columns = new();
ISet<string> _hidden_columns;
ISet<VolSurfaceExpiration> _hidden_expirations;
IDisposable _shift_editor;
public VolSurfaceSimplifiedGridVM(VolSurfaceVM vm, VolSurfaceDisplayModel model,
ISet<string> hidden_columns, ISet<VolSurfaceExpiration> hidden_expirations) {
Log.assert(hidden_columns != null);
Log.assert(hidden_expirations != null);
_parent = vm;
this.model = model;
_hidden_columns = hidden_columns;
_hidden_expirations = hidden_expirations;
this.model.on_candidate_grid_change += _on_grid_updated;
this.model.on_committed_grid_change += _on_grid_updated;
current_grid = this.model.get_active_grid();
committed_grid = is_dirty ? this.model.get_committed_grid() : current_grid;
// Rows
visible_rows.AddRange(rows);
visible_rows.CollectionChanged += (o, e) => {
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove) {
Debug.WriteLine("Removed {0}", string.Join(",", e.OldItems));
}
};
// Columns
_internal_columns.AddRange(current_grid.get_ordered_columns());
// data_columns contains all columns except the expiration (header) column
var data_columns = new ObservableCollection<DIYGrid.ColumnBase>();
_dispose = Disposable.Create(
ObservableAutoWrapper.connect(_expirations, rows, exp => new VolSurfaceRowContext(this, exp)),
ObservableAutoWrapper.connect(_internal_columns, data_columns, c => new VolSurfaceSimplifiedColumn(_map(c.type), c.header, c)),
ObservableAggregateCollection.connect(
columns, new ObservableCollection<DIYGrid.ColumnBase> { create_exp_column_view() }, data_columns),
Disposable.Create(() => {
this.model.on_candidate_grid_change -= _on_grid_updated;
this.model.on_committed_grid_change -= _on_grid_updated;
Disposable.dispose(ref _shift_editor);
}));
VolSurfaceSimplifiedColumn create_exp_column_view() {
var filter = new MultiSelectDropDown() { HeaderText = "Expirations" };
filter.Foreground = Brushes.Black;
filter.SetBinding(MultiSelectDropDown.ItemsSourceProperty, new Binding() {
Path = new PropertyPath("rows"),
Source = this,
Mode = BindingMode.OneWay
});
filter.SetBinding(MultiSelectDropDown.SelectedItemsProperty, new Binding() {
Path = new PropertyPath("visible_rows"),
Source = this,
Mode = BindingMode.OneWay
});
return new VolSurfaceSimplifiedColumn(VolSurfaceSimplifiedColumnType.RowHeader, null, null) { Header = filter };
}
}
public event Action<IEnumerable<VolSurfaceDisplayGridExpiration>> on_selection_changed;
public VolSurfaceDisplayGrid current_grid { get; private set; }
public VolSurfaceDisplayGrid committed_grid { get; private set; }
public VolSurfaceDisplayModel model { get; }
public bool is_dirty => model.is_dirty;
public int frozen_columns => 1;
public ObservableCollection<DIYGrid.ColumnBase> columns { get; } = new();
public ObservableCollection<VolSurfaceRowContext> rows { get; } = new();
public ObservableCollection<object> visible_rows { get; } = new();
public bool any_masters_selected { get { return selected_rows.Any(r => !r.expiration.is_slave); } }
public IEnumerable<VolSurfaceRowContext> selected_rows {
get {
return visible_rows
.OfType<VolSurfaceRowContext>()
.Where(r => r.is_selected);
}
}
public DataTemplate row_template =>
// Because the View exists in bts_view we need our custom row template
new() {
VisualTree = new FrameworkElementFactory(typeof(VolSurfaceRowControl))
};
IEnumerable<VolSurfaceRowContext> typed_visible_rows => visible_rows.Cast<VolSurfaceRowContext>();
IEnumerable<VolSurfaceDisplayGridExpiration> selected_expirations => selected_rows.Select(r => r.expiration);
IEnumerable<VolSurfaceDisplayGridExpiration> master_expirations => model.get_active_grid().get_ordered_expirations().Where(e => !e.is_slave);
IEnumerable<VolSurfaceDisplayGridExpiration> all_expirations => model.get_active_grid().get_ordered_expirations();
public ICommand main_settings_command { get { return _parent.main_settings_command; } }
public ICommand advanced_settings_command { get { return _parent.advanced_settings_command; } }
public ICommand graph_settings_command { get { return _parent.vol_curve_vm.settings_command; } }
public ICommand grid_settings_command { get { return _parent.grid_settings_command; } }
public IEnumerable<DIYGridSuperHeader> super_headers =>
// There are no superheaders over frozen columns (currently)
columns
.Skip(frozen_columns)
.Cast<VolSurfaceSimplifiedColumn>()
.GroupBy(col => col.volsurface_column.group)
.Select(group => new DIYGridSuperHeader(group.Count(), group.Key, _short_header(group.Key)))
.ToList();
public void update_column_filter(ISet<string> hidden_cols) {
_hidden_columns = hidden_cols;
_on_grid_updated();
}
internal void signal_selection_changed() {
var e = on_selection_changed;
if (e != null) {
e.Invoke(selected_rows.Select(r => r.expiration));
}
RaisePropertyChanged("any_masters_selected");
}
internal void shift_selection(VolSurfaceDisplayGridTextInputColumn column) =>
_launch_shift_editor(column, shift => _shift(column, selected_expirations, shift));
internal void shift_masters(VolSurfaceDisplayGridTextInputColumn column) =>
_launch_shift_editor(column, shift => _shift(column, master_expirations, shift));
internal void shift_all(VolSurfaceDisplayGridTextInputColumn column) =>
_launch_shift_editor(column, shift => _shift(column, all_expirations, shift));
internal void clear(VolSurfaceDisplayGridColumn col, GridColumnSet where) {
switch (where) {
case GridColumnSet.Column:
foreach (VolSurfaceDisplayGridExpiration exp in selected_expirations) {
_clear(exp, col);
}
_commit();
break;
case GridColumnSet.Group:
foreach (VolSurfaceDisplayGridExpiration exp in selected_expirations) {
foreach (var c in _internal_columns.Where(c => c.group == col.group)) _clear(exp, c);
}
_commit();
break;
case GridColumnSet.All:
foreach (VolSurfaceDisplayGridExpiration exp in selected_expirations) {
foreach (var c in _internal_columns) _clear(exp, c);
}
_commit();
break;
default:
throw new NotImplementedException();
}
}
internal void copy_to_selection(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn column, GridColumnSet set) {
if (column is VolSurfaceDisplayGridTextColumn input_col) {
_replicate(exp, selected_expirations.Except(new[] { exp }), _get_columns(input_col, set));
}
}
internal void copy_to_masters(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn column, GridColumnSet set) {
if (column is VolSurfaceDisplayGridTextColumn input_col) {
_replicate(exp, master_expirations.Except(new[] { exp }), _get_columns(input_col, set));
}
}
internal void copy_to_all(VolSurfaceDisplayGridExpiration exp, VolSurfaceDisplayGridColumn column, GridColumnSet set) {
if (column is VolSurfaceDisplayGridTextColumn input_col) {
_replicate(exp, all_expirations.Except(new[] { exp }), _get_columns(input_col, set));
}
}
static VolSurfaceSimplifiedColumnType _map(DataGridKnownColumnType type) =>
type switch {
DataGridKnownColumnType.ReadOnly or DataGridKnownColumnType.ReadOnlyDiff => VolSurfaceSimplifiedColumnType.ReadOnly,
DataGridKnownColumnType.ReadWriteDiff or DataGridKnownColumnType.ReadWriteTick or DataGridKnownColumnType.ReadWrite => VolSurfaceSimplifiedColumnType.ReadWriteTick,
_ => VolSurfaceSimplifiedColumnType.ReadOnly,
};
static string _short_header(string header) =>
string.Join("", header.Where(Char.IsUpper));
bool _is_column_visible(VolSurfaceDisplayGridColumn column) =>
!_hidden_columns.Contains(column.unique_col_name);
void _on_grid_updated() {
var grid_new = model.get_active_grid();
// add/remove columns
var cols_new = grid_new.get_ordered_columns()
.Where(_is_column_visible).ToList();
var new_hash = cols_new.aggregate_hash();
var old_hash = _internal_columns.aggregate_hash();
if (new_hash != old_hash) {
_internal_columns.sync_with(cols_new);
RaisePropertyChanged("super_headers");
}
// Add/remove rows too
var old_row_count = _expirations.Count;
_expirations.sync_with(grid_new.get_ordered_expirations());
if (old_row_count == 0) {
// Initial data download
if (_hidden_expirations != null) {
visible_rows.AddRange(rows.Where(r => !_hidden_expirations.Contains(r.expiration.ToVSExp())));
_hidden_expirations = null;
} else {
visible_rows.AddRange(rows);
}
}
current_grid = grid_new;
committed_grid = is_dirty ? model.get_committed_grid() : current_grid;
_invalidate_rows();
}
void _invalidate_rows() {
foreach (var row in rows) {
row.invalidate();
}
}
void _launch_shift_editor(VolSurfaceDisplayGridTextInputColumn column, Action<double> commit_shift) {
Disposable.dispose(ref _shift_editor);
var input_text = new System.Windows.Controls.TextBox();
var commit_cmd = new DelegateCommand(
() => commit_shift(parse_input()),
() => !double.IsNaN(parse_input()));
input_text.TextChanged += (s, e) => commit_cmd.RaiseCanExecuteChanged();
var editor = new OKCancelDialog() {
Content = input_text,
OKCommand = commit_cmd
};
editor.Title = "Shift '{0}'".fmt(column.display_name);
editor.MinWidth = 160d;
editor.WindowStartupLocation = System.Windows.WindowStartupLocation.Manual;
editor.move_to_mouse(-200, -200);
editor.Show();
_shift_editor = Disposable.Create(() => {
if (editor != null) {
try { editor.Close(); } catch { } finally { editor = null; }
}
});
double parse_input() =>
double.TryParse(input_text.Text, out var val) ? val : double.NaN;
}
void _shift(VolSurfaceDisplayGridTextInputColumn column, IEnumerable<VolSurfaceDisplayGridExpiration> target_exps, double shift) {
var grid = model.get_active_grid();
foreach (var exp in target_exps) {
// an inelegant (yet effective and simple) way to apply the column's parse logic to the shift argument
object parsed = column.parse(shift.ToString());
if (parsed is double) {
object data;
if (grid.get_grid_data(exp, column, out data) && data is double)
grid.set_grid_data(exp, column, (double)data + (double)parsed);
}
}
model.set_candidate_grid(grid);
}
void _clear(VolSurfaceDisplayGridExpiration row, VolSurfaceDisplayGridColumn col) {
current_grid.set_grid_data(row, col, double.NaN);
}
IEnumerable<VolSurfaceDisplayGridTextColumn> _get_columns(VolSurfaceDisplayGridTextColumn col, GridColumnSet set) {
switch (set) {
case GridColumnSet.Column: return new[] { col };
case GridColumnSet.Group: return _internal_columns.OfType<VolSurfaceDisplayGridTextInputColumn>().Where(c => c.group == col.group);
case GridColumnSet.All: return _internal_columns.OfType<VolSurfaceDisplayGridTextInputColumn>();
default: throw new ArgumentException("Received an unexpected [GridColumnSet] '{0}.'".fmt(set), "set");
}
}
void _replicate(VolSurfaceDisplayGridExpiration source, IEnumerable<VolSurfaceDisplayGridExpiration> target_exps, IEnumerable<VolSurfaceDisplayGridTextColumn> cols) {
foreach (var col in cols) {
foreach (var exp in target_exps) {
_copy(source, exp, col);
}
}
_commit();
}
void _copy(VolSurfaceDisplayGridExpiration source, VolSurfaceDisplayGridExpiration dest, VolSurfaceDisplayGridColumn col) {
if (current_grid.get_grid_data(source, col, out var value)) {
current_grid.set_grid_data(dest, col, value);
}
}
void _commit() =>
model.set_candidate_grid(current_grid);
public List<VolSurfaceExpiration> get_hidden_expirations() {
var visible_exps = new HashSet<VolSurfaceDisplayGridExpiration>(typed_visible_rows.Select(rc => rc.expiration));
return rows.Where(r => !visible_exps.Contains(r.expiration)).Select(r => r.expiration.ToVSExp()).ToList();
}
}
}
@@ -0,0 +1,74 @@
using mbts.analytics;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
namespace mbts.spark {
class VolSurfaceAdvancedSettingsEditorVM : ViewModelBase {
readonly VolSurfaceAdvancedSettings _settings;
public VolSurfaceAdvancedSettingsEditorVM(VolSurfaceAdvancedSettings settings, string vs_name, Action<VolSurfaceAdvancedSettings> commit) {
_settings = settings;
_settings.theo_handle_measure = VolSurfaceEnums.GeneralChangeMeasure.Absolute;
_settings.slide_handle_measure = VolSurfaceEnums.GeneralChangeMeasure.Percentage;
if (_settings.precomputed_slide_handles == null)
_settings.precomputed_slide_handles = new List<double>();
if (_settings.precomputed_theo_handles == null)
_settings.precomputed_theo_handles = new List<double>();
vol_surface_name = vs_name;
this.commit = new DelegateCommand(() => request_commit?.Invoke(ProtoBufSerializationHelper.clone_protobuf(_settings)));
}
public event Action<VolSurfaceAdvancedSettings> request_commit;
public IReadOnlyList<VolSurfaceEnums.GeneralChangeMeasure> general_change_measures =>
EnumHelper.get_values<VolSurfaceEnums.GeneralChangeMeasure>();
public IReadOnlyList<VolSurfaceEnums.VolCurveStrikeAxis> strike_normalization_axes =>
EnumHelper.get_values<VolSurfaceEnums.VolCurveStrikeAxis>();
public string vol_surface_name { get; }
public double number_of_cash_saved_days {
get => _settings.number_of_cashed_saved_days;
set => _settings.number_of_cashed_saved_days = value;
}
public IEnumerable<double> precomputed_theo_handles {
get => _settings.precomputed_theo_handles;
set => _settings.precomputed_theo_handles = value.ToList();
}
public VolSurfaceEnums.GeneralChangeMeasure theo_handle_measure {
get => _settings.theo_handle_measure;
set => _settings.theo_handle_measure = value;
}
public IEnumerable<double> precomputed_slide_handles {
get => _settings.precomputed_slide_handles;
set => _settings.precomputed_slide_handles = value.ToList();
}
public VolSurfaceEnums.GeneralChangeMeasure slide_handle_measure {
get => _settings.slide_handle_measure;
set => _settings.slide_handle_measure = value;
}
public VolSurfaceEnums.VolCurveStrikeAxis selected_strike_normalization_axis {
get => _settings.strike_normalization_axis;
set => _settings.strike_normalization_axis = value;
}
public bool publish_from_client {
get => _settings.publish_from_client;
set => _settings.publish_from_client = value;
}
public ICommand commit { get; }
}
}
@@ -0,0 +1,65 @@
using mbts.ui;
using mbts.ui.controls.graph;
using System;
using System.Windows.Input;
using System.Windows.Media;
namespace mbts.spark
{
class VolSurfaceGraphSettingsEditorVM
{
public VolSurfaceGraphSettingsEditorVM(string vol_surface_name, VolSurfaceGraphSettings settings, Action<VolSurfaceGraphSettings> commit) {
this.vol_surface_name = vol_surface_name;
_settings = settings;
this.commit = new DelegateCommand(() => commit(_settings));
}
private readonly VolSurfaceGraphSettings _settings;
public string vol_surface_name { get; private set; }
public VolSurfaceScatterSeriesSettingsVM implied_puts { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.implied_puts); } }
public VolSurfaceScatterSeriesSettingsVM implied_atm { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.implied_atm); } }
public VolSurfaceScatterSeriesSettingsVM implied_calls { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.implied_calls); } }
public VolSurfaceScatterSeriesSettingsVM put_control_points { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.put_control_points); } }
public VolSurfaceScatterSeriesSettingsVM atm { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.atm); } }
public VolSurfaceScatterSeriesSettingsVM call_control_points { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.call_control_points); } }
public VolSurfaceLineSeriesSettingsVM put_wing { get { return new VolSurfaceLineSeriesSettingsVM(_settings.put_wing); } }
public VolSurfaceLineSeriesSettingsVM inner_curve { get { return new VolSurfaceLineSeriesSettingsVM(_settings.inner_curve); } }
public VolSurfaceLineSeriesSettingsVM call_wing { get { return new VolSurfaceLineSeriesSettingsVM(_settings.call_wing); } }
public VolSurfaceLineSeriesSettingsVM vol_path { get { return new VolSurfaceLineSeriesSettingsVM(_settings.vol_path); } }
public ICommand commit { get; private set; }
}
class VolSurfaceScatterSeriesSettingsVM
{
public VolSurfaceScatterSeriesSettingsVM(ScatterSeriesSettings settings) {
_settings = settings;
}
private readonly ScatterSeriesSettings _settings;
public MarkerShape shape { get { return _settings.shape; } set { _settings.shape = value; } }
public double size { get { return _settings.size; } set { _settings.size = value; } }
public Color color { get { return (Color)_settings.color; } set { _settings.color = (BTSColor)value; } }
public Array shapes { get { return Enum.GetValues(typeof(MarkerShape)); } }
}
class VolSurfaceLineSeriesSettingsVM
{
public VolSurfaceLineSeriesSettingsVM(LineSeriesSettings settings) {
_settings = settings;
}
private readonly LineSeriesSettings _settings;
public Color color { get { return (Color)_settings.color; } set { _settings.color = (BTSColor)value; } }
public double thickness { get { return _settings.stroke_thickness; } set { _settings.stroke_thickness = value; } }
}
}
@@ -0,0 +1,75 @@
using mbts;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
namespace mbts.spark {
class VolSurfaceGridSettingsEditorVM : ViewModelBase {
readonly Action<VolSurfaceMacroGridSettings> _commit;
readonly VolSurfaceMacroGridSettings _settings;
readonly string _vol_surface_name;
public VolSurfaceGridSettingsEditorVM(string vol_surface_name, VolSurfaceMacroGridSettings settings, Action<VolSurfaceMacroGridSettings> commit) {
_settings = settings;
_commit = commit;
_vol_surface_name = vol_surface_name;
columns = _settings.configuration.columns
.GroupBy(col => col.group)
.SelectMany(g => g.Select((col_conf, i) => new ColumnVM(new BTSTabularGridColumnConfiguration(col_conf), i == g.Count() - 1)))
.ToList();
// don't draw line at the bottom of the list
columns.Last().is_last_column_in_group = false;
this.commit = new DelegateCommand(() => commit(ProtoBufSerializationHelper.clone_protobuf(_settings)));
}
public string vol_surface_name { get { return _vol_surface_name; } }
private IEnumerable<BTSTabularGridColumnConfiguration> _selected_columns { get { return columns.Where(c => c.is_selected).Select(c => c.column); } }
public IEnumerable<ColumnVM> columns { get; private set; }
private ColumnVM _selected_column;
public ColumnVM selected_column { get { return _selected_column; } set { _selected_column = value; RaisePropertyChanged("tick_unit", "tick_base", "tick_move", "multiplier"); } }
public double tick_unit {
get { return _selected_column == null ? 0.0 : _selected_column.column.cell_configuration.tick_interval; }
set { _selected_columns.ForEach(col => col.cell_configuration.tick_interval = value); }
}
public double tick_base {
get { return _selected_column == null ? 0.0 : _selected_column.column.cell_configuration.tick_base; }
set { _selected_columns.ForEach(col => col.cell_configuration.tick_base = value); }
}
public double tick_move {
get { return _selected_column == null ? 0.0 : _selected_column.column.cell_configuration.tick_move; }
set { _selected_columns.ForEach(col => col.cell_configuration.tick_move = value); }
}
public double multiplier {
get { return _selected_column == null ? 0.0 : _selected_column.column.cell_configuration.multiplier; }
set { _selected_columns.ForEach(col => col.cell_configuration.multiplier = value); }
}
public ICommand commit { get; }
public class ColumnVM {
public ColumnVM(BTSTabularGridColumnConfiguration column, bool is_last_column_in_group) {
this.column = column;
this.is_last_column_in_group = is_last_column_in_group;
}
public BTSTabularGridColumnConfiguration column { get; private set; }
public bool is_last_column_in_group { get; set; }
private bool _is_selected;
public bool is_selected { get { return _is_selected; } set { _is_selected = value; if (is_selected_changed != null) is_selected_changed(); } }
public event Action is_selected_changed;
}
}
}
@@ -0,0 +1,872 @@
namespace mbts.spark {
using bts;
using bts.api;
using bts.collections;
using mbts;
using mbts.analytics;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Input;
public class VolSurfaceSettingsEditorVM : ViewModelBase {
readonly uint _atm_shifts_id = 0;
readonly VolSurfaceSettings _settings;
readonly VolSurfaceCoreSettings _core_settings;
public VolSurfaceSettingsEditorVM(IBus bus, VolSurfaceSettings settings, Action<VolSurfaceSettings> commit) {
if (settings is null) {
throw new ArgumentNullException(nameof(settings));
}
_settings = settings.ensure_no_nulls();
_core_settings = settings.core_settings;
symbol_structure_vm = new VSSymbolStructureVM(bus, settings);
vol_model_polynomial_vm.load_from(settings.polynomial_model_settings);
vol_model_cubic_spline_vm.load_from(settings.spline_model_settings);
vol_model_dual_quadratic_vm.load_from(settings.dualquadratic_model_settings);
vol_path_parabolic_vm.load_from(settings.core_settings.volpath_settings.parabolic_vol_path_settings);
init_rotation_vms(call_rotations, _core_settings.call_rotation.strike_vol_movement_pairs);
init_rotation_vms(put_rotations, _core_settings.put_rotation.strike_vol_movement_pairs);
if (_core_settings.atm_shift is null) {
_core_settings.atm_shift = new VolCurveMovementOperation {
strike_vol_movement_pairs = new List<Tuple<double, double>>()
};
}
atm_shifts.Add(new RotationVM(atm_shifts, _atm_shifts_id++) {
move = _core_settings.atm_shift.atm_strike_vol_movement
});
_initialize_full_rotation_set(
curve_ops_strike_axis,
full_rotations,
_core_settings.full_rotation.strike_vol_movement_pairs,
"full rotations",
_core_settings.vol_surface_name);
_initialize_full_rotation_set(
curve_ops_strike_axis,
strangles,
_core_settings.strangle.strike_vol_movement_pairs,
"strangles",
_core_settings.vol_surface_name);
this.commit = new DelegateCommand(commit_impl);
void commit_impl() {
var symbols = symbol_structure_vm.driver_grids
.SelectMany(dg => dg.symbols.Where(sym => sym.is_selected))
.ToList();
_core_settings.master_slave_relationships = symbols
.Where(sym => sym.masters.Any())
.Select(sym => new VolSurfaceSymbolRelationship {
symbol = sym.name,
connected_symbols = sym.masters.Cast<string>().ToList()
})
.ToList();
_core_settings.implied_vol_marketdata_relationships = symbols
.Where(sym => sym.fits.Any())
.Select(sym => new VolSurfaceSymbolRelationship {
symbol = sym.name,
connected_symbols = sym.fits.Cast<string>().ToList()
})
.ToList();
vol_model_polynomial_vm.assign_to(_settings.polynomial_model_settings);
vol_model_cubic_spline_vm.assign_to(_settings.spline_model_settings);
vol_model_dual_quadratic_vm.assign_to(_settings.dualquadratic_model_settings);
vol_path_parabolic_vm.assign_to(_settings.core_settings.volpath_settings.parabolic_vol_path_settings);
_core_settings.symbol_pricing_model_map = symbols.Select(sym => Tuple.Create(sym.name, sym.pricing_model)).ToList();
_core_settings.put_rotation.strike_vol_movement_pairs = put_rotations
.Select(r => Tuple.Create(r.target_strike, r.move))
.ToList();
_core_settings.call_rotation.strike_vol_movement_pairs = call_rotations
.Select(r => Tuple.Create(r.target_strike, r.move))
.ToList();
_core_settings.full_rotation.strike_vol_movement_pairs = full_rotations.SelectMany(r => new[] {
Tuple.Create(r.target_put_strike, r.put_move),
Tuple.Create(r.target_call_strike, r.call_move)
}).ToList();
_core_settings.strangle.strike_vol_movement_pairs = strangles.SelectMany(r => new[] { Tuple.Create(r.target_put_strike, r.put_move), Tuple.Create(r.target_call_strike, r.call_move) }).ToList();
_core_settings.atm_shift.atm_strike_vol_movement = atm_shifts.Count == 1 ? atm_shifts[0].move : 0;
commit(_settings);
}
static void init_rotation_vms(
ObservableCollection<RotationVM> rotation_vms, IEnumerable<Tuple<double, double>> vol_movement_pairs) {
foreach (var (tgt_k, move) in vol_movement_pairs.DefaultIfEmpty(Tuple.Create(0.0, 0.0))) {
rotation_vms.Add(new RotationVM(rotation_vms, (uint)rotation_vms.Count) {
target_strike = tgt_k,
move = move
});
}
}
}
public string vol_surface_name { get { return _core_settings.vol_surface_name; } }
public VSSymbolStructureVM symbol_structure_vm { get; set; }
public VolModelPolynomialVM vol_model_polynomial_vm { get; } = new();
public VolModelCubicSplineVM vol_model_cubic_spline_vm { get; } = new();
public VolModelDualQuadraticVM vol_model_dual_quadratic_vm { get; } = new();
public VolPathParabolicVM vol_path_parabolic_vm { get; } = new();
public ObservableCollection<RotationVM> call_rotations { get; } = new();
public ObservableCollection<RotationVM> put_rotations { get; } = new();
public ObservableCollection<RotationVM> atm_shifts { get; } = new();
public ObservableCollection<FullRotationVM> full_rotations { get; } = new();
public ObservableCollection<FullRotationVM> strangles { get; } = new();
public IEnumerable<VolSurfaceEnums.StrikeConversionVol> strike_conversion_vol_choices => EnumHelper.get_values<VolSurfaceEnums.StrikeConversionVol>();
public IEnumerable<VolSurfaceEnums.VolTimePeriod> vol_time_period_choices => EnumHelper.get_values<VolSurfaceEnums.VolTimePeriod>();
public IEnumerable<VolSurfaceEnums.VolSurfaceTimeMode> vol_time_mode_choices => EnumHelper.get_values<VolSurfaceEnums.VolSurfaceTimeMode>();
public IEnumerable<VolSurfaceEnums.VolCurveFitRegion> auto_fit_region_choices => EnumHelper.get_values<VolSurfaceEnums.VolCurveFitRegion>();
public IEnumerable<VolSurfaceEnums.VolCurveStrikeAxis> strike_axis_choices => EnumHelper.get_values_except(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike);
public IEnumerable<VolSurfaceEnums.VolCurveStrikeAxis> all_strike_axis_choices => EnumHelper.get_values<VolSurfaceEnums.VolCurveStrikeAxis>();
public IEnumerable<VolSurfaceEnums.VolMovementTerms> vol_movement_choices => EnumHelper.get_values<VolSurfaceEnums.VolMovementTerms>();
public IEnumerable<VolSurfaceEnums.VolCurveVolAxis> vol_axis_choices => EnumHelper.get_values<VolSurfaceEnums.VolCurveVolAxis>();
public IEnumerable<VolSurfaceEnums.GeneralChangeMeasure> general_change_measure_choices => EnumHelper.get_values<VolSurfaceEnums.GeneralChangeMeasure>();
public VolSurfaceEnums.StrikeConversionVol strike_conversion_vol {
get => _core_settings.strike_conversion_vol;
set => Set(ref _core_settings.strike_conversion_vol, value);
}
public VolSurfaceEnums.VolTimePeriod vol_time_period {
get => _core_settings.voltime_period;
set => Set(ref _core_settings.voltime_period, value);
}
public VolSurfaceEnums.VolCurveStrikeAxis curve_ops_strike_axis {
get => _core_settings.put_rotation.strike_axis;
set {
using var _ = detect_property_change();
_set_standard_curve_operation_strike_term(value);
}
}
public VolSurfaceEnums.VolMovementTerms curve_ops_vol_movement {
get => _core_settings.full_rotation.target_terms;
set {
using var _ = detect_property_change();
_set_standard_curve_movement_term(value);
}
}
public double atm_max_absolute_change {
get => _core_settings.safety_limits.atm_absolute_change;
set => Set(ref _core_settings.safety_limits.atm_absolute_change, value);
}
public double atm_max_percentage_change {
get => _core_settings.safety_limits.atm_percentage_change;
set => Set(ref _core_settings.safety_limits.atm_percentage_change, value);
}
public double general_max_absolute_change {
get => _core_settings.safety_limits.general_absolute_change;
set => Set(ref _core_settings.safety_limits.general_absolute_change, value);
}
public double general_max_percentage_change {
get => _core_settings.safety_limits.general_percentage_change;
set => Set(ref _core_settings.safety_limits.general_percentage_change, value);
}
public bool ignore_one_sided_markets {
get => _core_settings.market_fit_settings.ignore_one_sided_markets;
set => Set(ref _core_settings.market_fit_settings.ignore_one_sided_markets, value);
}
public uint minimum_top_book_size {
get => _core_settings.market_fit_settings.minimum_top_book_size;
set => Set(ref _core_settings.market_fit_settings.minimum_top_book_size, value);
}
public uint maximum_bid_ask_spread_ticks {
get => _core_settings.market_fit_settings.maximum_bid_ask_spread_ticks;
set => Set(ref _core_settings.market_fit_settings.maximum_bid_ask_spread_ticks, value);
}
public double graph_update_period_ms {
get => _core_settings.market_fit_settings.graph_update_period_ms;
set { _core_settings.market_fit_settings.graph_update_period_ms = value; }
}
public uint regression_order {
get => _core_settings.market_fit_settings.regression_order;
set {
using var _ = detect_property_change();
_core_settings.market_fit_settings.regression_order = value;
}
}
public bool enable_auto_fit {
get => _core_settings.market_fit_settings.enable_auto_fit;
set {
using var _ = detect_property_change();
_core_settings.market_fit_settings.enable_auto_fit = value;
}
}
public VolSurfaceEnums.VolCurveFitRegion auto_fit_region {
get => _core_settings.market_fit_settings.auto_fit_region;
set { _core_settings.market_fit_settings.auto_fit_region = value; }
}
public double auto_fit_time_ms {
get => _core_settings.market_fit_settings.auto_fit_time_ms;
set { _core_settings.market_fit_settings.auto_fit_time_ms = value; }
}
public bool auto_decay_vol_time {
get => _core_settings.time_settings.time_mode == VolSurfaceEnums.VolSurfaceTimeMode.AutoDecay;
set {
using var _ = detect_property_change();
_core_settings.time_settings.time_mode = value ?
VolSurfaceEnums.VolSurfaceTimeMode.AutoDecay :
VolSurfaceEnums.VolSurfaceTimeMode.Manual;
}
}
public bool use_business_calendar_for_vol {
get => _core_settings.time_settings.vol_time_measure.account_for_holidays_and_weekends;
set {
using var _ = detect_property_change();
_core_settings.time_settings.vol_time_measure.account_for_holidays_and_weekends = value;
_core_settings.time_settings.vol_time_measure.days_per_year = value ?
252 : _core_settings.time_settings.interest_time_measure.days_per_year;
}
}
public double calendar_days_per_year {
get => _core_settings.time_settings.interest_time_measure.days_per_year;
set {
using var _ = detect_property_change();
_core_settings.time_settings.interest_time_measure.days_per_year = value;
if (!use_business_calendar_for_vol) {
_core_settings.time_settings.vol_time_measure.days_per_year = value;
}
}
}
public bool vol_model_polynomial_selected {
get => _core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Polynomial;
set {
if (value) {
_core_settings.vol_surface_model = VolSurfaceEnums.VolSurfaceModel.Polynomial;
}
}
}
public bool vol_model_cubic_spline_selected {
get => _core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.CubicSpline;
set {
if (value) {
_core_settings.vol_surface_model = VolSurfaceEnums.VolSurfaceModel.CubicSpline;
}
}
}
public bool vol_model_dual_quadratic_selected {
get => _core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.DualQuadratic;
set {
if (value) {
_core_settings.vol_surface_model = VolSurfaceEnums.VolSurfaceModel.DualQuadratic;
}
}
}
public bool vol_model_custom_selected {
get => _core_settings.vol_surface_model == VolSurfaceEnums.VolSurfaceModel.Custom;
set {
if (value) {
_core_settings.vol_surface_model = VolSurfaceEnums.VolSurfaceModel.Custom;
}
}
}
public bool vol_path_two_way_slope_selected {
get => _core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.TwoWaySlope;
set {
if (value) {
_core_settings.volpath_settings.vol_path_model = VolSurfaceEnums.VolSurfaceVolPathModel.TwoWaySlope;
}
}
}
public bool vol_path_parabolic_selected {
get => _core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.Parabolic;
set {
if (value) {
_core_settings.volpath_settings.vol_path_model = VolSurfaceEnums.VolSurfaceVolPathModel.Parabolic;
}
}
}
public bool vol_path_custom_selected {
get => _core_settings.volpath_settings.vol_path_model == VolSurfaceEnums.VolSurfaceVolPathModel.Custom;
set {
if (value) {
_core_settings.volpath_settings.vol_path_model = VolSurfaceEnums.VolSurfaceVolPathModel.Custom;
}
}
}
public bool wing_model_implicit_selected {
get => _core_settings.wing_settings.wing_model == VolSurfaceEnums.VolCurveWingModel.ImplicitSlopeWithHorizontalAsymptotes;
set {
if (value) {
_core_settings.wing_settings.wing_model = VolSurfaceEnums.VolCurveWingModel.ImplicitSlopeWithHorizontalAsymptotes;
}
}
}
public bool wing_model_explicit_selected {
get => _core_settings.wing_settings.wing_model == VolSurfaceEnums.VolCurveWingModel.ExplicitSlopeWithHorizontalAsymptotes;
set {
if (value) {
_core_settings.wing_settings.wing_model = VolSurfaceEnums.VolCurveWingModel.ExplicitSlopeWithHorizontalAsymptotes;
}
}
}
public bool wing_model_single_point_selected {
get => _core_settings.wing_settings.wing_model == VolSurfaceEnums.VolCurveWingModel.OnePointSlope;
set {
if (value) {
_core_settings.wing_settings.wing_model = VolSurfaceEnums.VolCurveWingModel.OnePointSlope;
}
}
}
public ICommand commit { get; }
public VolSurfaceSettings get_settings() {
var rv = ProtoBufSerializationHelper.clone_protobuf(_settings);
var symbols = symbol_structure_vm.driver_grids
.SelectMany(dg => dg.symbols.Where(sym => sym.is_selected))
.ToList();
var settings = new VolSurfaceSettings();
var core_settings = settings.core_settings;
core_settings.master_slave_relationships = symbols
.Where(sym => sym.masters.Any())
.Select(sym => new VolSurfaceSymbolRelationship {
symbol = sym.name,
connected_symbols = sym.masters.Cast<string>().ToList()
})
.ToList();
core_settings.implied_vol_marketdata_relationships = symbols
.Where(sym => sym.fits.Any())
.Select(sym => new VolSurfaceSymbolRelationship {
symbol = sym.name,
connected_symbols = sym.fits.Cast<string>().ToList()
})
.ToList();
vol_model_polynomial_vm.assign_to(_settings.polynomial_model_settings);
vol_model_cubic_spline_vm.assign_to(_settings.spline_model_settings);
vol_model_dual_quadratic_vm.assign_to(_settings.dualquadratic_model_settings);
vol_path_parabolic_vm.assign_to(_settings.core_settings.volpath_settings.parabolic_vol_path_settings);
core_settings.symbol_pricing_model_map = symbols.Select(sym => Tuple.Create(sym.name, sym.pricing_model)).ToList();
core_settings.put_rotation.strike_vol_movement_pairs = put_rotations
.Select(r => Tuple.Create(r.target_strike, r.move))
.ToList();
core_settings.call_rotation.strike_vol_movement_pairs = call_rotations
.Select(r => Tuple.Create(r.target_strike, r.move))
.ToList();
core_settings.full_rotation.strike_vol_movement_pairs = full_rotations.SelectMany(r => new[] {
Tuple.Create(r.target_put_strike, r.put_move),
Tuple.Create(r.target_call_strike, r.call_move)
}).ToList();
core_settings.strangle.strike_vol_movement_pairs = strangles.SelectMany(r => new[] { Tuple.Create(r.target_put_strike, r.put_move), Tuple.Create(r.target_call_strike, r.call_move) }).ToList();
core_settings.atm_shift.atm_strike_vol_movement = atm_shifts.Count == 1 ? atm_shifts[0].move : 0;
return rv;
}
static void _initialize_full_rotation_set(
VolSurfaceEnums.VolCurveStrikeAxis strike_terms,
ObservableCollection<FullRotationVM> rotation_set,
List<Tuple<double, double>> shifts,
string rotation_name,
string vol_surface_name) {
switch (shifts.Count) {
case 0:
rotation_set.Add(new FullRotationVM(rotation_set, 0));
break;
case 2:
//add put side, then call side
bool item1_is_put = !VolSurfaceCoreFunctions.is_call_or_put(shifts[0].Item1, strike_terms, double.NaN);
bool item2_is_put = !VolSurfaceCoreFunctions.is_call_or_put(shifts[1].Item1, strike_terms, double.NaN);
if (!item1_is_put && item2_is_put) {
rotation_set.Add(new FullRotationVM(rotation_set, 0) {
target_put_strike = shifts[1].Item1,
put_move = shifts[1].Item2,
target_call_strike = shifts[0].Item1,
call_move = shifts[0].Item2
});
break;
}
rotation_set.Add(new FullRotationVM(rotation_set, 0) {
target_put_strike = shifts[0].Item1,
put_move = shifts[0].Item2,
target_call_strike = shifts[1].Item1,
call_move = shifts[1].Item2
});
break;
default:
Log.assert(false, $"Vol surface '{vol_surface_name}' had an unexpected number ({shifts.Count}) of {rotation_name} strike vol movement pairs");
break;
}
}
void _set_standard_curve_operation_strike_term(VolSurfaceEnums.VolCurveStrikeAxis term) {
_core_settings.put_rotation.strike_axis = term;
_core_settings.call_rotation.strike_axis = term;
_core_settings.full_rotation.strike_axis = term;
_core_settings.strangle.strike_axis = term;
_core_settings.atm_shift.strike_axis = term;
}
void _set_standard_curve_movement_term(VolSurfaceEnums.VolMovementTerms term) {
_core_settings.put_rotation.target_terms = term;
_core_settings.call_rotation.target_terms = term;
_core_settings.full_rotation.target_terms = term;
_core_settings.strangle.target_terms = term;
_core_settings.atm_shift.target_terms = term;
}
public class VSDriver : IEquatable<VSDriver> {
public VSDriver(Venue exchange, string name) {
this.exchange = exchange;
this.name = name;
}
public string name { get; }
public Venue exchange;
public ObservableCollection<string> symbols { get; } = new();
public bool Equals(VSDriver other) =>
other != null && other.name == name && other.exchange == exchange;
public override bool Equals(object obj) =>
Equals(obj as VSDriver);
public override int GetHashCode() =>
name.GetHashCode();
}
public class VSSymbol : IEquatable<VSSymbol> {
public VSSymbol(VSDriver driver, string name) {
this.driver = driver;
this.name = name;
}
public VSDriver driver { get; }
public string name { get; }
public bool is_selected { get; set; }
public ObservableCollection<string> fits { get; } = new();
public ObservableCollection<string> masters { get; } = new();
public VolSurfaceEnums.VolSurfacePricingModel pricing_model { get; set; }
public bool Equals(VSSymbol other) =>
other != null && name == other.name && driver.Equals(other.driver);
public override bool Equals(object obj) =>
Equals(obj as VSSymbol);
public override int GetHashCode() =>
name.GetHashCode();
}
public class VSSymbolGridVM {
public VSSymbolGridVM(VSDriver driver) {
this.driver = driver;
symbols = new ObservableCollection<VSSymbol>();
}
public VSDriver driver { get; private set; }
public string header { get { return "{0} ({1})".fmt(driver.name, driver.exchange); } }
public ObservableCollection<VSSymbol> symbols { get; private set; }
}
public class VSSymbolStructureVM : DisposableViewModelBase {
public VSSymbolStructureVM(IBus bus, VolSurfaceSettings settings) {
driver_grids = new ObservableCollection<VSSymbolGridVM>();
settings.core_settings.master_slave_relationships ??= new List<VolSurfaceSymbolRelationship>();
settings.core_settings.implied_vol_marketdata_relationships ??= new List<VolSurfaceSymbolRelationship>();
_dispose = bus.subscribe(SparkTags.ExpirationParametersInputTag).OnDispatcher().Subscribe(on_exp_params_input);
void on_exp_params_input(AnalyticsExpirationParametersMap data) {
var driver_map = data.get_option_driver_map();
var driver_symbols_aux = new Dictionary<VSDriver, HashSet<string>>();
bool init_with_settings = driver_grids.Count == 0;
foreach (var (driver_exp, slave_exps) in driver_map.Where(kv => kv.Key.exchange != Venue.Unset)) {
var driver = new VSDriver(driver_exp.exchange, driver_exp.symbol);
if (!driver_symbols_aux.TryGetValue(driver, out var driven_by_this_driver)) {
driver_symbols_aux[driver] = driven_by_this_driver = new HashSet<string>();
}
driven_by_this_driver.AddRange(slave_exps.Select(s => s.symbol));
}
var driver_symbols = driver_symbols_aux.ToDictionary(kv => kv.Key, kv => new List<string>(kv.Value));
driver_grids.RemoveWhere(driver_sym_grid => !driver_symbols.ContainsKey(driver_sym_grid.driver));
foreach (var symbols in driver_symbols.Values) {
symbols.Sort();
}
foreach (var (key, i) in driver_symbols.OrderBy(kv => kv.Key.name).Select((kv, i) => (key: kv.Key, i))) {
if (!driver_grids.Select(dg => dg.driver).Contains(key)) {
driver_grids.Insert(i, new VSSymbolGridVM(key));
}
}
foreach (var sym_grid in driver_grids) {
sym_grid.driver.symbols.sync_with(driver_symbols[sym_grid.driver]);
sym_grid.symbols.sync_with(driver_symbols[sym_grid.driver].Select(sym => new VSSymbol(sym_grid.driver, sym)));
}
if (!init_with_settings) {
return;
}
foreach (var sym in driver_grids.SelectMany(grid => grid.symbols)) {
if (settings.core_settings.symbol_pricing_model_map is null) {
continue;
}
var pricing_model = settings.core_settings.symbol_pricing_model_map.FirstOrDefault(pm => pm.Item1 == sym.name);
if (pricing_model != null) {
sym.is_selected = true;
sym.pricing_model = pricing_model.Item2;
var master_slaves = settings.core_settings.master_slave_relationships.FirstOrDefault(msr => msr.symbol == sym.name);
if (master_slaves != null)
sym.masters.sync_with(master_slaves.connected_symbols);
var implied_vols = settings.core_settings.implied_vol_marketdata_relationships.FirstOrDefault(iv => iv.symbol == sym.name);
if (implied_vols != null)
sym.fits.sync_with(implied_vols.connected_symbols);
}
}
}
}
public IReadOnlyList<VolSurfaceEnums.VolSurfacePricingModel> pricing_models => EnumHelper.get_values<VolSurfaceEnums.VolSurfacePricingModel>();
public ObservableCollection<VSSymbolGridVM> driver_grids { get; private set; }
}
public class RotationVM : ViewModelBase, IEquatable<RotationVM> {
double _target_strike;
double _move;
public RotationVM(ObservableCollection<RotationVM> l, uint id) {
remove_me = new DelegateCommand(_ => l.Remove(this));
this.id = id;
}
public uint id { get; }
public double target_strike {
get => _target_strike;
set => Set(ref _target_strike, value);
}
public double move {
get => _move;
set => Set(ref _move, value);
}
public ICommand remove_me { get; }
public bool Equals(RotationVM other) =>
other != null && other.id == id;
public override bool Equals(object obj) =>
Equals(obj as RotationVM);
public override int GetHashCode() =>
(int)id;
}
public class FullRotationVM : ViewModelBase, IEquatable<FullRotationVM> {
double _target_call_strike;
double _call_move;
double _target_put_strike;
double _put_move;
public FullRotationVM(ObservableCollection<FullRotationVM> l, uint id) {
this.id = id;
remove_me = new DelegateCommand(_ => l.Remove(this));
}
public uint id { get; }
public double target_call_strike {
get => _target_call_strike;
set => Set(ref _target_call_strike, value);
}
public double call_move {
get => _call_move;
set => Set(ref _call_move, value);
}
public double target_put_strike {
get => _target_put_strike;
set => Set(ref _target_put_strike, value);
}
public double put_move {
get => _put_move;
set => Set(ref _put_move, value);
}
public ICommand remove_me { get; }
public bool Equals(FullRotationVM other) =>
other != null && other.id == id;
public override bool Equals(object obj) =>
Equals(obj as RotationVM);
public override int GetHashCode() =>
(int)id;
}
public class VolModelPolynomialVM : ViewModelBase {
VolSurfaceEnums.VolCurveStrikeAxis _strike_axis;
VolSurfaceEnums.VolCurveVolAxis _vol_axis;
uint _num_call_points;
uint _num_put_points;
public VolModelPolynomialVM() { }
public VolModelPolynomialVM(PolynomialModelVolSurfaceSettings settings) =>
load_from(settings);
public VolSurfaceEnums.VolCurveStrikeAxis strike_axis {
get => _strike_axis;
set => _strike_axis = value;
}
public VolSurfaceEnums.VolCurveVolAxis vol_axis {
get => _vol_axis;
set => Set(ref _vol_axis, value);
}
public uint num_call_points {
get => _num_call_points;
set => Set(ref _num_call_points, value);
}
public uint num_put_points {
get => _num_put_points;
set => Set(ref _num_put_points, value);
}
public void load_from(PolynomialModelVolSurfaceSettings settings) {
if (settings is null) {
return;
}
strike_axis = settings.strike_axis;
vol_axis = settings.vol_axis;
num_call_points = settings.n_call_points;
num_put_points = settings.n_put_points;
}
public void assign_to(PolynomialModelVolSurfaceSettings settings) {
if (settings is null) {
throw new ArgumentNullException(nameof(settings));
}
settings.strike_axis = strike_axis;
settings.vol_axis = vol_axis;
settings.n_call_points = num_call_points;
settings.n_put_points = num_put_points;
}
}
public class VolModelCubicSplineVM : ViewModelBase {
VolSurfaceEnums.VolCurveStrikeAxis _strike_axis;
VolSurfaceEnums.VolCurveVolAxis _vol_axis;
uint _num_call_points;
uint _num_put_points;
public VolSurfaceEnums.VolCurveStrikeAxis strike_axis {
get => _strike_axis;
set => Set(ref _strike_axis, value);
}
public VolSurfaceEnums.VolCurveVolAxis vol_axis {
get => _vol_axis;
set => Set(ref _vol_axis, value);
}
public uint num_call_points {
get => _num_call_points;
set => Set(ref _num_call_points, value);
}
public uint num_put_points {
get => _num_put_points;
set => Set(ref _num_put_points, value);
}
public void load_from(SplineModelVolSurfaceSettings settings) {
if (settings is null) {
return;
}
strike_axis = settings.strike_axis;
vol_axis = settings.vol_axis;
num_call_points = settings.n_call_points;
num_put_points = settings.n_put_points;
}
public void assign_to(SplineModelVolSurfaceSettings settings) {
if (settings is null) {
throw new ArgumentNullException(nameof(settings));
}
settings.strike_axis = strike_axis;
settings.vol_axis = vol_axis;
settings.n_call_points = num_call_points;
settings.n_put_points = num_put_points;
}
}
// public class VolModelCustomVM {
// public VolModelCustomVM(CustomModelVolSurfaceSettings settings) {
// _settings = settings;
// }
// private readonly CustomModelVolSurfaceSettings _settings;
// public string model_name { get { return _settings.vol_model_name; } set { _settings.vol_model_name = value; } }
// public string[] model_choices { get { return _settings.custom_volmodel_choices(); } }
// }
public class VolPathParabolicVM : ViewModelBase {
VolSurfaceEnums.GeneralChangeMeasure _price_change;
VolSurfaceEnums.GeneralChangeMeasure _vol_change;
public IEnumerable<VolSurfaceEnums.GeneralChangeMeasure> price_change_choices {
get {
yield return VolSurfaceEnums.GeneralChangeMeasure.Absolute;
yield return VolSurfaceEnums.GeneralChangeMeasure.Percentage;
}
}
public VolSurfaceEnums.GeneralChangeMeasure price_change {
get => _price_change;
set => Set(ref _price_change, value);
}
public VolSurfaceEnums.GeneralChangeMeasure vol_change {
get => _vol_change;
set => Set(ref _vol_change, value);
}
public void load_from(ParabolicVolPathSettings settings) {
if (settings is null) {
return;
}
price_change = settings.price_change_measure;
vol_change = settings.vol_change_measure;
}
public void assign_to(ParabolicVolPathSettings settings) {
if (settings is null) {
throw new ArgumentNullException(nameof(settings));
}
settings.price_change_measure = price_change;
settings.vol_change_measure = vol_change;
}
}
public class WingModelImplicitVM : ViewModelBase {
VolSurfaceEnums.VolCurveStrikeAxis _strike_axis;
public VolSurfaceEnums.VolCurveStrikeAxis strike_axis {
get => _strike_axis;
set => Set(ref _strike_axis, value);
}
public void load_from(VolSurfaceImplicitSlopeWingSettings settings) {
if (settings is null) {
return;
}
strike_axis = settings.wing_start_strike_axis;
}
public void assign_to(VolSurfaceImplicitSlopeWingSettings settings) {
if (settings is null) {
throw new ArgumentNullException(nameof(settings));
}
settings.wing_start_strike_axis = strike_axis;
}
}
public class WingModelExplicitVM : ViewModelBase {
VolSurfaceEnums.VolCurveStrikeAxis _strike_axis;
public VolSurfaceEnums.VolCurveStrikeAxis strike_axis {
get => _strike_axis;
set => Set(ref _strike_axis, value);
}
public void load_from(VolSurfaceExplicitSlopeWingSettings settings) {
if (settings is null) {
return;
}
strike_axis = settings.wing_start_strike_axis;
}
public void assign_to(VolSurfaceExplicitSlopeWingSettings settings) {
if (settings is null) {
throw new ArgumentNullException(nameof(settings));
}
settings.wing_start_strike_axis = strike_axis;
}
}
public class VolModelDualQuadraticVM : ViewModelBase {
VolSurfaceEnums.VolCurveStrikeAxis _strike_axis;
VolSurfaceEnums.VolCurveStrikeAxis _curve_endpoint_axis;
public IEnumerable<VolSurfaceEnums.VolCurveStrikeAxis> strike_axes =>
EnumHelper.get_values_except(VolSurfaceEnums.VolCurveStrikeAxis.Delta);
public VolSurfaceEnums.VolCurveStrikeAxis strike_axis {
get => _strike_axis;
set => Set(ref _strike_axis, value);
}
public VolSurfaceEnums.VolCurveStrikeAxis curve_endpoint_axis {
get => _curve_endpoint_axis;
set => Set(ref _curve_endpoint_axis, value);
}
public void load_from(DualQuadraticModelVolSurfaceSettings settings) {
if (settings is null) {
return;
}
strike_axis = settings.strike_axis;
curve_endpoint_axis = settings.curve_endpoint_axis;
}
public void assign_to(DualQuadraticModelVolSurfaceSettings settings) {
if (settings is null) {
throw new ArgumentNullException(nameof(settings));
}
settings.strike_axis = strike_axis;
settings.curve_endpoint_axis = curve_endpoint_axis;
}
}
}
}
@@ -0,0 +1,64 @@
namespace mbts.spark {
using System;
using System.Collections.Generic;
using System.Linq;
using mbts.ui.controls;
internal class VolSurfaceEventDemux {
VolSurfaceDisplayModel _model;
VolSurfaceDisplayGrid _active;
public VolSurfaceEventDemux(VolSurfaceDisplayModel model) {
_model = model;
_model.on_candidate_grid_change += _model_on_active_grid_change;
_model.on_committed_grid_change += _model_on_committed_grid_change;
_active = _model.get_active_grid();
}
private void _model_on_committed_grid_change() {
var evt = on_committed_grid_change;
if (evt != null) {
evt();
}
// If we're not dirty the Active grid is the commited grid
if (!_model.is_dirty) {
_model_on_active_grid_change();
}
}
private void _model_on_active_grid_change() {
var active_new = _model.get_active_grid();
try {
if (on_schema_change != null) {
if (_active == null || VolSurfaceDisplayGrid.cols_changed(active_new, _active))
on_schema_change.Invoke();
}
if (on_expirations_change != null) {
if (_active == null) {
on_expirations_change(active_new.get_ordered_expirations(), new List<VolSurfaceDisplayGridExpiration>());
} else {
IEnumerable<VolSurfaceDisplayGridExpiration> added, removed;
VolSurfaceDisplayGrid.compare_exps(active_new, _active, out removed, out added);
if (added.Count() > 0 || removed.Count() > 0)
on_expirations_change(added, removed);
}
}
if (on_candidate_grid_change != null)
on_candidate_grid_change();
} finally {
_active = active_new;
}
}
public event Action on_candidate_grid_change;
public event Action on_committed_grid_change;
public event Action<IEnumerable<VolSurfaceDisplayGridExpiration>, IEnumerable<VolSurfaceDisplayGridExpiration>> on_expirations_change;
public event Action on_schema_change;
public void Dispose() {
_model.on_candidate_grid_change -= _model_on_active_grid_change;
_model.on_committed_grid_change -= _model_on_committed_grid_change;
}
}
}
@@ -0,0 +1,101 @@
using mbts;
using mbts.analytics;
using mbts.ui;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
namespace mbts.spark
{
internal class VolSurfaceGlobalParameterVM : ViewModelBase, IHaveTemplateKey, IDisposable
{
public object TemplateKey { get { return "Manual"; } }
public VolSurfaceGlobalParameterVM(VolSurfaceDisplayModel model) {
_model = model;
decay_editor = new VolSurfaceTimeDecayEditorVM(_model);
_model.on_candidate_grid_change += _on_grid_change;
_model.on_committed_grid_change += _on_grid_change;
}
private readonly VolSurfaceDisplayModel _model;
private void _on_grid_change() {
if (read_date() != DateTime.MinValue) RaisePropertyChanged("is_date_committed", "time", "date");
// Don't interrupt user inputting values if the TimeEditor popup is open
if (!_vol_time_popup_open) _sync_time_mode();
}
private void _sync_time_mode() {
VolSurfaceEnums.VolSurfaceTimeMode curr = _model.get_active_vol_time_mode();
if (time_mode != curr) {
time_mode = curr;
RaisePropertyChanged("time_mode");
}
}
private bool _vol_time_popup_open;
public bool vol_time_popup_open {
get { return _vol_time_popup_open; }
set {
if (_vol_time_popup_open != value) {
if (!(_vol_time_popup_open = value)) _sync_time_mode();
else if (time_mode == VolSurfaceEnums.VolSurfaceTimeMode.AutoDecay) decay_editor.sync_with_candidate();
RaisePropertyChanged();
}
}
}
public VolSurfaceTimeDecayEditorVM decay_editor { get; private set; }
public VolSurfaceEnums.VolSurfaceTimeMode time_mode { get; private set; }
private DateTime read_date() { return _model.get_active_vol_time(); }
private void write_date(DateTime date) {
_model.set_candidate_vol_time(date);
}
private string _get_decay_points_msg() {
var tups = _model.get_active_time_decay_points();
string message;
if (tups == null) message = "NULL";
else {
message = string.Empty;
foreach (var tup in tups) {
message += tup.Item1.ToString() + "---" + tup.Item2.ToString();
}
}
return message;
}
public object time {
get {
return date.ToString("t");
}
set {
if (value is DateTime) {
write_date((DateTime)value);
}
else {
var time = DateTime.Parse(value.ToString());
write_date(new DateTime(date.Year, date.Month, date.Day, time.Hour, time.Minute, time.Second));
}
}
}
public bool is_date_committed { get { return time_mode == VolSurfaceEnums.VolSurfaceTimeMode.AutoDecay || _model.get_active_vol_time() == _model.get_committed_vol_time(); } }
public DateTime date {
get {
return read_date();
}
set {
var current_datetime = read_date();
write_date(new DateTime(value.Year, value.Month, value.Day, current_datetime.Hour, current_datetime.Minute, current_datetime.Second));
}
}
public void Dispose() {
_model.on_candidate_grid_change -= _on_grid_change;
_model.on_committed_grid_change -= _on_grid_change;
}
}
}
@@ -0,0 +1,92 @@
namespace mbts.spark {
using bts;
using bts.utils;
using mbts.ui;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
class VolSurfaceMacroActionsVM : ViewModelBase {
readonly VolSurfaceDisplayModel _model;
List<VolSurfaceDisplayGridExpiration> _selected_exps;
bool _cascade_up;
bool _cascade_down;
bool _can_cascade;
bool _can_execute;
bool _use_weighted_regression_fit;
public VolSurfaceMacroActionsVM(VolSurfaceDisplayModel model) {
_model = model;
put_rotation = new DelegateCommand<bool>(is_up => _model.put_rotation(_selected_exps, is_up, cascade_up, cascade_down), _ => can_execute_commands);
call_rotation = new DelegateCommand<bool>(is_up => _model.call_rotation(_selected_exps, is_up, cascade_up, cascade_down), _ => can_execute_commands);
full_rotation = new DelegateCommand<bool>(is_up => _model.full_rotation(_selected_exps, is_up, cascade_up, cascade_down), _ => can_execute_commands);
strangle = new DelegateCommand<bool>(is_up => _model.strangle(_selected_exps, is_up, cascade_up, cascade_down), _ => can_execute_commands);
atm_shift = new DelegateCommand<bool>(is_up => _model.atm_shift(_selected_exps, is_up, cascade_up, cascade_down), t => can_execute_commands);
fit_to_market = new DelegateCommand<Tuple<int, int>>(
t => _model.fit_to_market(_selected_exps, t.Item2 == 1, t.Item2 == 1, use_weighted_regression_fit, cascade_up, cascade_down),
_ => can_execute_commands);
rebuild = new DelegateCommand(_ => _model.rebuild(_selected_exps, cascade_up, cascade_down), _ => can_execute_commands);
vol_shift = new DelegateCommand(is_up => _model.global_vol_shift(is_up), t => !can_execute_commands);
Log.assert_d(_commands.All(c => c != null));
}
public bool can_cascade {
get => _can_cascade;
set => Set(ref _can_cascade, value);
}
public bool cascade_up {
get => _cascade_up;
set => Set(ref _cascade_up, value);
}
public bool cascade_down {
get => _cascade_down;
set => Set(ref _cascade_down, value);
}
public bool can_execute_commands {
get => _can_execute;
set {
if (Set(ref _can_execute, value)) {
foreach (var c in _commands) {
c.RaiseCanExecuteChanged();
}
}
}
}
public bool use_weighted_regression_fit {
get => _use_weighted_regression_fit;
set => Set(ref _use_weighted_regression_fit, value);
}
public IRaiseCanExecuteChangedCommand put_rotation { get; }
public IRaiseCanExecuteChangedCommand call_rotation { get; }
public IRaiseCanExecuteChangedCommand full_rotation { get; }
public IRaiseCanExecuteChangedCommand strangle { get; }
public IRaiseCanExecuteChangedCommand atm_shift { get; }
public IRaiseCanExecuteChangedCommand fit_to_market { get; }
public IRaiseCanExecuteChangedCommand rebuild { get; }
public IRaiseCanExecuteChangedCommand vol_shift { get; }
IEnumerable<IRaiseCanExecuteChangedCommand> _commands =>
ObjectSnapshot.property_delegates_of_type<VolSurfaceMacroActionsVM, IRaiseCanExecuteChangedCommand>()
.Select(g => g(this));
public void selection_changed(IEnumerable<VolSurfaceDisplayGridExpiration> selected) {
_selected_exps = selected.ToList();
can_execute_commands = _selected_exps.Count > 0;
can_cascade = _selected_exps.Count == 1;
if (_selected_exps.Count > 1) {
cascade_down = false;
cascade_up = false;
}
}
}
}
@@ -0,0 +1,115 @@
namespace mbts.spark {
using bts.collections;
using bts.utils;
using mbts;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows.Input;
class VolSurfaceTimeDecayEditorVM : DisposableViewModelBase, IHaveTemplateKey {
readonly VolSurfaceDisplayModel _model;
readonly PropertyUpdateGate _commit_gate = new();
TimeTextTuple _new_actual_time;
public VolSurfaceTimeDecayEditorVM(VolSurfaceDisplayModel model) {
_model = model;
time_decay_items = new ObservableCollection<TimeDecayItem>();
var curr = _model.get_active_time_decay_points();
time_decay_items.AddRange(
_model.get_active_time_decay_points().empty_if_null()
.Select(tup => new TimeDecayItem(tup.Item1, tup.Item2, this)));
add_item = new DelegateCommand(() => {
time_decay_items.insert_sorted_if_distinct(
new TimeDecayItem(_new_actual_time.result ?? throw new InvalidOperationException($"'{nameof(new_actual_time)}' does not have a value"), double.NaN, this),
Comparer<TimeSpan>.Default.wrap<TimeSpan, TimeDecayItem>(tdi => tdi.actual_time.TimeOfDay));
},
() => {
var nat = _new_actual_time.result;
return nat.HasValue && !time_decay_items.Any(tdi => tdi.actual_time.TimeOfDay == nat.Value.TimeOfDay);
});
remove_item = new DelegateCommand<TimeDecayItem>(tdi => time_decay_items.Remove(tdi));
_dispose = time_decay_items.Subscribe((s, e) => _commit());
}
public object TemplateKey => VolSurfaceView2.TimeDecayTemplateKey;
public ObservableCollection<TimeDecayItem> time_decay_items { get; } = new();
public TimeTextTuple new_actual_time {
get => _new_actual_time;
set {
_new_actual_time = value;
add_item.RaiseCanExecuteChanged();
}
}
public IRaiseCanExecuteChangedCommand add_item { get; }
public ICommand remove_item { get; }
public void sync_with_candidate() {
var tdps = _model.get_active_time_decay_points() ?? Enumerable.Empty<Tuple<DateTime, double>>();
using var _ = _commit_gate.update();
time_decay_items.sync_with(tdps.Select(_from_tuple));
}
void _commit(bool throw_if_already_updating = false) =>
_commit_gate.update(
() => _model.set_candidate_time_decay_parameters(time_decay_items.Where(tdi => tdi.is_valid).Select(_to_tuple)),
throw_if_already_updating);
TimeDecayItem _from_tuple(Tuple<DateTime, double> tup) =>
new(tup.Item1, tup.Item2, this);
Tuple<DateTime, double> _to_tuple(TimeDecayItem tdi) =>
Tuple.Create(tdi.actual_time, tdi.decay_hours);
public class TimeDecayItem : ViewModelBaseWithValidation, IEquatable<TimeDecayItem> {
readonly VolSurfaceTimeDecayEditorVM _owner;
double _decay_hours;
public TimeDecayItem(DateTime actual_time, double decay_hours, VolSurfaceTimeDecayEditorVM owner) {
this.actual_time = actual_time;
_decay_hours = decay_hours;
_owner = owner;
}
public DateTime actual_time { get; }
public double decay_hours {
get => _decay_hours;
set {
_decay_hours = value;
_validate();
if (!HasErrors) {
_owner._commit();
}
}
}
public bool is_valid => !double.IsNaN(decay_hours) && _decay_hours >= 0 && _decay_hours <= 24;
public bool Equals(TimeDecayItem other) =>
other != null &&
other.actual_time.TimeOfDay == actual_time.TimeOfDay &&
other._decay_hours.Equals(_decay_hours);
public override bool Equals(object obj) =>
Equals(obj as TimeDecayItem);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(actual_time.TimeOfDay.GetHashCode(), _decay_hours.GetHashCode());
void _validate() {
using (validation())
validation_assert(is_valid, "Decay Hours cannot be less than 0 or greater than 24.", "decay_hours");
}
}
}
}
@@ -0,0 +1,200 @@
namespace mbts.spark {
using bts;
using bts.api;
using mbts;
using mbts.analytics;
using mbts.spark.VolSurface;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows.Input;
class VolSurfaceVM : ViewModelBase, IDisposable {
readonly int _vs_id;
readonly IBus _bus;
readonly string _request_id = Guid.NewGuid().ToString();
VolSurfaceDisplayModel _model;
VolSurfaceMacroGridSettings _grid_settings;
public VolSurfaceVM(VolSurfaceDisplayModel model, int id, IBus bus, VolSurfaceWindowSettings startup_data) {
Log.notnull(startup_data);
_model = model;
var demux = new VolSurfaceEventDemux(model);
_vs_id = id;
_bus = bus;
_grid_settings = startup_data.macro_grid_settings ?? new VolSurfaceMacroGridSettings();
if (_grid_settings.configuration == null) {
_grid_settings.configuration = VolSurfaceMacroGridSettings.Default.configuration;
}
_model.publish_grid_settings(_grid_settings);
var initial_visible_rows = startup_data.hidden_exps ?? new List<VolSurfaceExpiration>();
var initial_grid_selected_rows = startup_data.vol_curve_visible_series ?? new List<VolSurfaceExpiration>();
vol_curve_vm = new VolSurfaceGraphVM(
_model, demux, startup_data, (show_ivol, exp) => _model.publish_new_grid_selection(_request_id, exp, show_ivol));
vol_terms_vm = new VolTermsGraphVM(_model, demux);
revert_command = new DelegateCommand(o => _model.revert(), o => _model.is_dirty);
commit_command = new DelegateCommand(o => _model.commit(), o => _model.is_dirty);
load_previous_command = new DelegateCommand(_ => { var cur = selected_previous_state; selected_previous_state = null; _model.load_previous_state(cur); }, _ => !string.IsNullOrEmpty(selected_previous_state));
main_settings_command = new DialogCommand(() => {
var settings = _model.get_active_settings();
if (settings == null) {
return null;
}
return new VolSurfaceSettingsEditor { DataContext = new VolSurfaceSettingsEditorVM(_bus, settings, _model.set_candidate_settings) };
});
advanced_settings_command = new DialogCommand(() => {
var settings = _model.get_active_settings();
if (settings == null) {
return null;
}
// return new VolSurfaceAdvancedSettingsEditor {
// DataContext = new VolSurfaceAdvancedSettingsEditorVM(
// VolSurfaceUtilityFunctions.clone_proto(settings.advanced_settings),
// settings.core_settings.vol_surface_name,
// advanced_settings => {
// var current_settings = _get_volsurface_settings();
// if (current_settings == null) BTSMessageBox.Show("Error changing settings", "VS Settings", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error, true, true, true);
// else {
// current_settings.advanced_settings = advanced_settings;
// _model.set_candidate_settings(current_settings);
// }
// }
// )
// };
return null;
});
grid_settings_command = new DialogCommand(() => {
var settings = _model.get_active_settings();
if (settings == null) return null;
// return new VolSurfaceGridSettingsEditor {
// DataContext = new VolSurfaceGridSettingsEditorVM(settings.core_settings.vol_surface_name, erializationHelper.clone_protobuf(_grid_settings),
// new_settings => {
// _grid_settings = new_settings;
// _model.publish_grid_settings(_grid_settings);
// grid.update_column_filter(new HashSet<string>(_grid_settings.hidden_cols()));
// })
// };
return null;
});
_model.on_dirty_change += raise_dirty_changed;
macro_actions = new VolSurfaceMacroActionsVM(_model);
globals = new VolSurfaceGlobalParameterVM(_model);
demux.on_candidate_grid_change += () => { RaisePropertyChanged("previous_states"); };
demux.on_schema_change += () => {
var existing = _grid_settings.configuration.columns.ToDictionary(c => c.id);
_grid_settings.configuration = new mbts.ui.settings.GridSettings();
// _grid_settings.configuration = new GridSettings(
// columns = model.get_active_grid()
// .get_ordered_columns()
// .Select(col => {
// if (existing.TryGetValue(col.unique_col_name, out var col_settings)) {
// return col_settings;
// } else {
// return new GridColumnSettings (
// col.unique_col_name,
// col.display_name,
// true
// // cell_configuration = new BTSTabularGridCellConfiguration {
// // tick_base = 100,
// // tick_interval = 1,
// // tick_move = 1,
// // multiplier = double.NaN
// // },
// );
// }
// }));
};
grid = new VolSurfaceSimplifiedGridVM(this, _model, _grid_settings.hidden_cols(), new HashSet<VolSurfaceExpiration>(startup_data.hidden_exps ?? Enumerable.Empty<VolSurfaceExpiration>()));
grid.on_selection_changed += _on_grid_selection_changed;
}
public VolSurfaceSimplifiedGridVM grid { get; private set; }
public VolSurfaceGraphVM vol_curve_vm { get; private set; }
public VolTermsGraphVM vol_terms_vm { get; private set; }
public VolSurfaceMacroActionsVM macro_actions { get; private set; }
public VolSurfaceGlobalParameterVM globals { get; private set; }
private bool _ignore_implied_vol_settings;
public bool ignore_implied_vol_settings { get { return _ignore_implied_vol_settings; } set { _model.publish_ignore_implied_vol_settings(_request_id, _ignore_implied_vol_settings = value); } }
public bool is_dirty { get { return _model.is_dirty; } }
public IRaiseCanExecuteChangedCommand revert_command { get; private set; }
public IRaiseCanExecuteChangedCommand commit_command { get; private set; }
public IDialogCommand main_settings_command { get; private set; }
public IDialogCommand advanced_settings_command { get; private set; }
public IDialogCommand grid_settings_command { get; private set; }
public ICommand details_command => new DelegateCommand(_ => _show_details());
public ICommand load_previous_command { get; private set; }
public IEnumerable<string> previous_states {
get {
return _model.get_previous_states();
}
}
private string _selected_state = string.Empty;
public string selected_previous_state {
get { return _selected_state; }
set {
_selected_state = value;
load_previous_command.TryRaiseCanExecuteChanged();
RaisePropertyChanged();
}
}
public VolSurfaceWindowSettings get_startup_data() {
var rv = new VolSurfaceWindowSettings {
id = _vs_id,
vol_curve_visible_series = vol_curve_vm.get_visible_series().ToList(),
show_mkt_implied_vol = vol_curve_vm.show_implied_vol,
hidden_exps = grid.get_hidden_expirations(),
vol_curve_graph_settings = vol_curve_vm.get_settings(),
macro_grid_settings = _grid_settings
};
(rv.vol_curve_x_axis, rv.vol_curve_y_axis) = vol_curve_vm.get_graph_axes();
return rv;
}
public void Dispose() {
vol_curve_vm.Dispose();
vol_terms_vm.Dispose();
globals.Dispose();
if (grid != null) grid.Dispose();
main_settings_command.Dispose();
advanced_settings_command.Dispose();
grid_settings_command.Dispose();
Disposable.dispose(ref _model);
}
void raise_dirty_changed() {
RaisePropertyChanged("is_dirty");
revert_command.RaiseCanExecuteChanged();
commit_command.RaiseCanExecuteChanged();
}
void _on_grid_selection_changed(IEnumerable<VolSurfaceDisplayGridExpiration> selection) {
var selected = selection.FirstOrDefault();
if (selected != null) {
vol_curve_vm.set_visible_expiration(selected);
_model.publish_new_grid_selection(_request_id, selected, vol_curve_vm.show_implied_vol);
}
macro_actions.selection_changed(selection);
}
async Task<VolSurfaceSettings> _get_volsurface_settings() =>
(await _bus.subscribe(SparkTags.VolSurfaceCommittedOutputTag(_vs_id)).FirstOrDefaultAsync())
?.volsurface_input
?.surface_settings;
void _show_details() =>
_model.show_details();
}
}
@@ -0,0 +1,191 @@
using bts.api;
using bts.utils;
using mbts.analytics;
using mbts.collections;
using mbts.ui;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Windows.Media;
namespace mbts.spark {
class VolTermsGraphVM : DisposableViewModelBase {
readonly VolSurfaceDisplayModel _model;
readonly DateTimeAxisVM _exp_terms_x_axis;
readonly List<VolSurfaceDisplayGridExpiration> _expirations = new();
bool _show_day_numbers;
public VolTermsGraphVM(VolSurfaceDisplayModel model, VolSurfaceEventDemux demux) {
_model = model;
graph_vm = new BTSGraphVM {
plot_area_background = Colors.Transparent,
background = Colors.Transparent,
plot_margins = new System.Windows.Thickness(40, 0, 35, 35),
};
graph_vm.axes.AddRange(new AxisVM[] {
_exp_terms_x_axis = new DateTimeAxisVM {
name = "Exp",
position = AxisPosition.BottomLeftToRight,
major_step = 1,
minor_step = 1,
interval_type = DateTimeIntervalType.Days,
minor_interval_type = DateTimeIntervalType.Days,
minimum = DateTime.Today,
maximum = DateTime.Today.AddYears(1),
extra_grid_line_color = BTSColors.Graph.grid_line,
label_formatter = _format_exp_axis_label
},
new LinearAxisVM {
name = "Vol",
position = AxisPosition.LeftBottomToTop,
minimum = 0,
maximum = 1,
major_grid_line_color = BTSColors.Graph.grid_line,
label_formatter = vol => vol.ToString("P0")
}
});
graph_vm.series.Add(
new VolTermsLineSeriesVM {
name = "Committed",
is_committed = true,
is_visible = true,
color = BTSColors.VolSurfaceGraph.main_curve,
line_style = LineStyle.Solid,
stroke_thickness = 1.5,
});
graph_vm.series.Add(
new VolTermsScatterSeriesVM {
name = "Committed",
is_committed = true,
is_visible = true,
marker_color = BTSColors.VolSurfaceGraph.main_curve_atm,
marker_shape = MarkerShape.Circle,
marker_size = 3.0,
});
graph_vm.series.Add(
new VolTermsLineSeriesVM {
name = "Candidate",
is_committed = false,
is_visible = true,
color = BTSColors.VolSurfaceGraph.main_curve,
line_style = LineStyle.Dashed,
stroke_thickness = 1.5,
});
graph_vm.series.Add(
new VolTermsScatterSeriesVM {
name = "Candidate",
is_committed = false,
is_visible = true,
marker_color = BTSColors.VolSurfaceGraph.main_curve_atm,
marker_shape = MarkerShape.Circle,
marker_size = 3.0,
});
demux.on_expirations_change += _on_expirations_change;
_model.on_graph_change += _on_graph_change;
_dispose = Disposable.Create(
selected_symbols.Subscribe(_on_selected_symbols_changed),
Disposable.Create(() => {
demux.on_expirations_change -= _on_expirations_change;
_model.on_graph_change -= _on_graph_change;
}));
_refresh_title();
_update_points();
}
public ObservableCollection<string> symbols { get; } = new();
public ObservableCollectionEx<string> selected_symbols { get; } = new();
public BTSGraphVM graph_vm { get; private set; }
public bool show_day_numbers {
get => _show_day_numbers;
set {
if (Set(ref _show_day_numbers, value)) {
graph_vm.replot();
}
}
}
string _format_exp_axis_label(DateTime dt) {
if (dt.Day == 1) {
return (_show_day_numbers ? "\n{0} {1}" : "{0} {1}")
.fmt(DateFormatter.GetMonthAbv(dt.Month), dt.Year - 2000);
}
if (_show_day_numbers && _expirations.Any(e => e.expiration == dt && selected_symbols.Contains(e.symbol))) {
return dt.Day.ToString();
}
return string.Empty;
}
void _on_expirations_change(IEnumerable<VolSurfaceDisplayGridExpiration> added, IEnumerable<VolSurfaceDisplayGridExpiration> removed) {
foreach (var exp in removed) {
_expirations.Remove(exp);
}
_expirations.AddRange(added);
bool select_all = symbols.Count == 0;
symbols.sync_with(_expirations.Select(e => e.symbol).Distinct().Ordered());
if (select_all) {
selected_symbols.AddRange(symbols);
}
DateTime min = _expirations.FirstOrDefault().expiration, max = _expirations.LastOrDefault().expiration;
min = new DateTime(min.Year, min.Month, 1);
max = new DateTime(max.Year, max.Month, 1);
int month_diff = (max.Year - min.Year) * 12 + (max.Month - min.Month);
_exp_terms_x_axis.extra_grid_lines = Enumerable.Range(0, month_diff + 2).Select(min.AddMonths).ToList();
_update_points();
}
void _on_selected_symbols_changed(object sender, NotifyCollectionChangedEventArgs e) {
_refresh_title();
_update_points();
}
void _refresh_title() =>
graph_vm.title = selected_symbols.Count == 0 ?
"Select Symbol(s)" :
", ".join(selected_symbols);
void _on_graph_change() =>
_update_points();
void _update_points() {
var settings = _model.get_active_settings();
var master_symbols = settings == null ? new HashSet<string>() : VolSurfaceUtilityFunctions.get_master_symbols(settings);
var committed_map = _get_exp_date_map(_model.get_committed_term_structure_map(), master_symbols);
var candidate_map = _get_exp_date_map(_model.get_candidate_term_structure_map(), master_symbols);
foreach (var s in graph_vm.series.Cast<IVolTermsSeries>()) s.update_points(s.is_committed ? committed_map : candidate_map);
}
Dictionary<DateTime, double> _get_exp_date_map(
IReadOnlyDictionary<VolSurfaceExpiration, double> exp_map, HashSet<string> master_symbols) =>
exp_map.Where(kv => selected_symbols.Contains(kv.Key.symbol) &&
master_symbols.Contains(kv.Key.symbol))
.ToDictionaryCrushed(kv => kv.Key.expiration, kv => kv.Value);
public class SymbolItem : IEquatable<SymbolItem> {
public SymbolItem(string symbol, Color color) {
_symbol = symbol;
_color = color;
}
private readonly string _symbol;
private readonly Color _color;
public string symbol { get { return _symbol; } }
public Brush brush { get { return new SolidColorBrush(_color); } }
public bool Equals(SymbolItem other) { return other != null && other._symbol == _symbol; }
public override bool Equals(object obj) { return Equals(obj as SymbolItem); }
public override int GetHashCode() { return _symbol.GetHashCode(); }
}
}
}
+32 -22
View File
@@ -1,19 +1,17 @@
using bts.api;
namespace mbts.spark {
using bts.api;
using bts.utils;
using mbts;
using mbts.analytics;
using mbts.analytics;
using mbts.ui.controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using mbts.ui.controls;
using bts.utils;
using System.Reactive.Linq;
using System.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
namespace mbts.spark {
public class VolSurfaceDisplayModel : IDisposable {
class VolSurfaceDisplayModel : IDisposable {
public enum DisplayModelState {
/// Start state, as soon as the first
/// server state is received, it gets
@@ -75,7 +73,10 @@ namespace mbts.spark {
public event Action on_dirty_change;
#endregion
public VolSurfaceDisplayModel(int vs_id, IBus bus, bool publish_lifetime = false) {
private static int _tid() { return VolSurfaceTroubleshootingFunctions.tid(); }
public VolSurfaceDisplayModel(int vs_id, IBus bus, bool publish_lifetime = true) {
bts.Log.Ui.info($"VolSurfaceDisplayModel cons vs_id:{vs_id} tid:{_tid()}");
_vs_id = vs_id;
_bus = bus;
_publish_lifetime = publish_lifetime;
@@ -373,6 +374,12 @@ namespace mbts.spark {
#region Blackboard response
private void _on_server_update(VolSurfaceOutput vs_output) {
Action fire_committed_change = () => {
bool event_hooked = on_committed_grid_change != null;
bts.Log.Ui.info($"VolSurfaceDiplayModel._on_server_update firing on_committed_grid_change event_hooked: {event_hooked} committed_data: {_committed_data.log_string()}");
if (event_hooked)
on_committed_grid_change();
};
if (vs_output != null) {
vs_output = vs_output.Clone() as VolSurfaceOutput;
if (_state == DisplayModelState.WaitingForCommittedState) {
@@ -381,8 +388,7 @@ namespace mbts.spark {
_committed_data.vs_output = vs_output;
VolSurfaceUIAdapter.copy_output_to_ui(_committed_data.vs_output, _grid_settings, out _committed_data.exp_grid, out _committed_data.global_grid, out _committed_data.exp_graph_map);
_change_state(DisplayModelState.Idle);
if (on_committed_grid_change != null)
on_committed_grid_change();
fire_committed_change();
if (on_graph_change != null)
on_graph_change();
} else if (_state == DisplayModelState.Idle || _state == DisplayModelState.WaitingForCalcResponse || _state == DisplayModelState.ResponseReady) {
@@ -390,8 +396,7 @@ namespace mbts.spark {
bts.Log.Ui.diag(String.Format("Received committed update for vol surface id {0} state {1}", _vs_id, _state.ToString()));
_committed_data.vs_output = vs_output;
VolSurfaceUIAdapter.copy_output_to_ui(_committed_data.vs_output, _grid_settings, out _committed_data.exp_grid, out _committed_data.global_grid, out _committed_data.exp_graph_map);
if (on_committed_grid_change != null)
on_committed_grid_change();
fire_committed_change();
if (on_graph_change != null)
on_graph_change();
} else
@@ -415,13 +420,17 @@ namespace mbts.spark {
}
}
private void _on_impl_vol_update(IDictionary<VolSurfaceExpiration, Tuple<VolSurfaceExpiration, VolCurveMarketImpliedVolData>> data) {
private void _on_impl_vol_update(
IDictionary<VolSurfaceExpiration,
Tuple<VolSurfaceExpiration, VolCurveMarketImpliedVolData>> data) {
bts.Log.Ui.info($"VolSurfaceDisplayModel._on_impl_vol_update count:{data.Count()} tid:{_tid()}");
_impl_vol_map = data;
if (on_graph_change != null)
on_graph_change();
}
private void _on_state_list_update(IEnumerable<VolSurfaceInputSnapshot> data) {
bts.Log.Ui.info($"VolSurfaceDisplayModel._on_state_list_update count:{data.Count()} tid:{_tid()}");
_input_snapshot_list = new List<VolSurfaceInputSnapshot>(data);
if (on_previous_state_list_change != null)
on_previous_state_list_change();
@@ -507,12 +516,13 @@ namespace mbts.spark {
public void commit() {
if (_state == DisplayModelState.ResponseReady) {
bts.Log.Ui.info($"VolSurfaceDiplayModel.commit vs_id:{_vs_id}");
_bus.post(SparkTags.VolSurfaceCommitTag(_vs_id), _candidate_data.vs_output.volsurface_input);
_change_state(DisplayModelState.Idle);
} else
_log_bad_transition(_state, "commit");
}
#endregion
#endregion
/// Put Rot, Call Rot, RR, Strangle and ATM
/// operation go call this
@@ -597,8 +607,8 @@ namespace mbts.spark {
public void Dispose() {
if (_publish_lifetime)
_bus.post(SparkTags.VolSurfaceActiveUITag(_vs_id), true);
_bus.post(SparkTags.VolSurfaceActiveUITag(_vs_id), false);
Disposable.dispose(ref _subscriptions);
}
}
}
}
+67 -49
View File
@@ -1,52 +1,70 @@
using System;
using System.Collections.Generic;
using System.Linq;
using mbts.ui.controls;
using bts.api;
using bts.api.analytics;
using Microsoft.Scripting.Actions;

namespace mbts.spark {
internal static class VolSurfaceExtensions {
using bts.api;
using bts.api.analytics;
using mbts.ui.controls;
using System.Collections.Generic;
using System.Linq;
static class VolSurfaceExtensions {
// VolSurfaceUsage
public static IEnumerable<int> vss(this VolSurfaceUsageListImmutable list) {
HashSet<int> rv = new HashSet<int>();
foreach (VolSurfaceUsageEntryImmutable e in list.UsageList) {
rv.Add(e.VsId);
}
return rv;
}
public static Nullable<int> get_vs_id(this VolSurfaceUsageListImmutable list, SecurityTuple security_tuple) {
foreach (VolSurfaceUsageEntryImmutable e in list.UsageList) {
if (e.SymbolName == security_tuple.security_name &&
e.SymbolVenue == security_tuple.security_exchange) {
return e.VsId;
}
}
return null;
}
public static Nullable<int> get_vs_id(this VolSurfaceUsageListImmutable list, string option_name) {
SecurityTuple st = new SecurityTuple(SecurityType.Option, option_name, Venue.Unset);
return get_vs_id(list, st);
}
public static bool symbol_driven_by_vs(this VolSurfaceUsageListImmutable list,
string option_name, int vs_id) {
foreach (var usage in list.UsageList) {
if (usage.SymbolName == option_name &&
usage.VsId == vs_id) {
return true;
}
}
return false;
}
public static HashSet<string> hidden_cols(this VolSurfaceMacroGridSettings gs) {
return new HashSet<string>(gs.configuration.column_configurations.Where(cc => !cc.visible).Select(cc => cc.name));
}
public static mbts.analytics.VolSurfaceExpiration ToVSExp(this VolSurfaceDisplayGridExpiration vsdge) {
return new mbts.analytics.VolSurfaceExpiration { expiration = vsdge.expiration, symbol = vsdge.symbol };
}
public static mbts.SecurityExpiration ToSecurityExp(this VolSurfaceDisplayGridExpiration vsdge) {
return new mbts.SecurityExpiration(Venue.Unset, SecurityType.Option, vsdge.symbol, vsdge.expiration);
}
public static IEnumerable<int> vss(this VolSurfaceUsageListImmutable list) =>
new HashSet<int>(list.UsageList.Select(e => e.VsId));
public static int? get_vs_id(this VolSurfaceUsageListImmutable list, SecurityTuple security_tuple) =>
list.UsageList.TryGetFirst(e => e.SymbolName == security_tuple.security_name &&
e.SymbolVenue == security_tuple.security_exchange, out var res) ?
res.VsId : null;
public static int? get_vs_id(this VolSurfaceUsageListImmutable list, string option_name) =>
get_vs_id(list, new SecurityTuple(SecurityType.Option, option_name, Venue.Unset));
public static bool symbol_driven_by_vs(this VolSurfaceUsageListImmutable list, string option_name, int vs_id) =>
list.UsageList.Any(u => u.SymbolName == option_name && u.VsId == vs_id);
public static HashSet<string> hidden_cols(this VolSurfaceMacroGridSettings gs) =>
new(gs.configuration.columns.Where(cc => !cc.is_visible).Select(cc => cc.id));
public static analytics.VolSurfaceExpiration ToVSExp(this VolSurfaceDisplayGridExpiration vsdge) =>
new() { expiration = vsdge.expiration, symbol = vsdge.symbol };
public static SecurityExpiration ToSecurityExp(this VolSurfaceDisplayGridExpiration vsdge) =>
new(Venue.Unset, SecurityType.Option, vsdge.symbol, vsdge.expiration);
public static bool is_candidate(this VolSurfaceGraphSeriesType series_type) =>
series_type switch {
VolSurfaceGraphSeriesType.CandidatePutWing or
VolSurfaceGraphSeriesType.CandidateInnerCurve or
VolSurfaceGraphSeriesType.CandidateCallWing or
VolSurfaceGraphSeriesType.CandidateSpecialPuts or
VolSurfaceGraphSeriesType.CandidateSpecialCalls or
VolSurfaceGraphSeriesType.CandidateControlPoints or
VolSurfaceGraphSeriesType.CandidateVolPath or
VolSurfaceGraphSeriesType.CandidateATM => true,
_ => false,
};
public static bool is_committed(this VolSurfaceGraphSeriesType series_type) =>
series_type switch {
VolSurfaceGraphSeriesType.CommittedPutWing or
VolSurfaceGraphSeriesType.CommittedInnerCurve or
VolSurfaceGraphSeriesType.CommittedCallWing or
VolSurfaceGraphSeriesType.CommittedSpecialPuts or
VolSurfaceGraphSeriesType.CommittedSpecialCalls or
VolSurfaceGraphSeriesType.CommittedControlPoints or
VolSurfaceGraphSeriesType.CommittedVolPath or
VolSurfaceGraphSeriesType.CommittedATM => true,
_ => false,
};
public static bool is_implied(this VolSurfaceGraphSeriesType series_type) =>
series_type switch {
VolSurfaceGraphSeriesType.ImpliedVolPuts or
VolSurfaceGraphSeriesType.ImpliedVolATM or
VolSurfaceGraphSeriesType.ImpliedVolCalls => true,
_ => false,
};
}
}
}
+180
View File
@@ -0,0 +1,180 @@
namespace mbts.spark {
using bts.api;
using bts.collections;
using bts.spark;
using mbts.analytics;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Composition;
using System.IO;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
[Export(typeof(IShellModule))]
class VolSurfaceModule : ViewModelBase, IShellModule, IShellModuleViewFactory {
readonly IBus _bus;
readonly IWindowManager _wm;
readonly VolSurfaceWindowFactory _vol_surface_window_factory;
readonly AnalyticsExpirationParametersWindowFactory _exp_params_window_factory;
string _new_vol_surface_name;
IDisposable _subscriptions;
[ImportingConstructor]
public VolSurfaceModule(IBus bus, IWindowManager wm, persist.UserSettingsHub settings_hub, OrdersModel orders_model) {
_wm = wm;
_bus = bus;
_vol_surface_window_factory = new(this, bus);
_exp_params_window_factory = new(this, bus);
_subscriptions = Disposable.Create(
_bus.subscribe(SparkTags.VolSurfaceListTag).OnDispatcher()
.Subscribe(async vs => await _set_current_vol_surfaces(vs)));
}
public enum WindowType { Main, Heatmap }
public static string ANALYTICS_EXPIRATION_PARAMETERS_HEADER => "Analytics Expiration Parameters";
public static string MAIN_WINDOW_HEADER => "Main Window";
public static string DETAILED_GRID_HEADER => "Detailed Grid";
public string name => "Pricing";
public ImageSource icon => Icons.vol_surface;
public int priority => 20;
public IEnumerable<SparkCommand> actions {
get {
yield return SparkCommands.pick_analytics_exp_params;
}
}
public ICommand launch_exp_params_view_cmd =>
SparkCommands.pick_analytics_exp_params.ICommand(_bus);
// new DelegateCommand(() => _bus.post(SparkTags.show_analytics_exp_params, null));
// await _wm.add(new AnalyticsExpirationParametersEditorWindow(
// _bus, _exp_params_window_factory, new AnalyticsExpirationParametersEditorVM.StartupData())));
public ObservableCollection<AlgoMenuItemVM> current_vol_surfaces { get; } = new();
public string new_vol_surface_name {
get => _new_vol_surface_name;
set => Set(ref _new_vol_surface_name, value);
}
public ICommand create_new_vol_surface => new DelegateCommand(_create_new_vol_surface);
public UIElement create_view() =>
new VolSurfaceShellModuleContent { DataContext = this };
public Task<IShellWindow> create(Stream load_stream) {
if (!ProtoBufSerializationHelper.try_deserialize(load_stream, out ShellSerializationHeader header)) {
return Task.FromResult<IShellWindow>(null);
}
async Task<IShellWindow> get_main_window() {
if (!ProtoBufSerializationHelper.try_deserialize(load_stream, out VolSurfaceWindowSettings ws)) {
return null;
}
if (ws.vol_curve_visible_series == null) {
ws.vol_curve_visible_series = new List<VolSurfaceExpiration>();
}
if (ws.hidden_exps == null) {
ws.hidden_exps = new List<VolSurfaceExpiration>();
}
if (ws.macro_grid_settings == null) {
ws.macro_grid_settings = new VolSurfaceMacroGridSettings();
}
return new VolSurfaceWindow(_vol_surface_window_factory, _bus, await _get_vs_name(ws.id), ws);
}
if (header.name == MAIN_WINDOW_HEADER) {
return get_main_window();
} else if (header.name == ANALYTICS_EXPIRATION_PARAMETERS_HEADER &&
ProtoBufSerializationHelper.try_deserialize(load_stream, out AnalyticsExpirationParametersVM.StartupData startup_data)) {
return Task.FromResult<IShellWindow>(new AnalyticsExpirationParametersWindow(_bus, _exp_params_window_factory, startup_data));
}
return Task.FromResult<IShellWindow>(null);
}
public void Dispose() =>
Disposable.dispose(ref _subscriptions);
void _create_new_vol_surface() {
if (string.IsNullOrWhiteSpace(_new_vol_surface_name)) {
return;
}
var vm = new VolSurfaceSettingsEditorVM(_bus, new VolSurfaceSettings {
core_settings = new VolSurfaceCoreSettings {
vol_surface_name = new_vol_surface_name,
vol_surface_model = VolSurfaceEnums.VolSurfaceModel.Polynomial,
call_rotation = new VolCurveMovementOperation { strike_vol_movement_pairs = new List<Tuple<double, double>>() },
put_rotation = new VolCurveMovementOperation { strike_vol_movement_pairs = new List<Tuple<double, double>>() },
strangle = new VolCurveMovementOperation { strike_vol_movement_pairs = new List<Tuple<double, double>>() },
full_rotation = new VolCurveMovementOperation { strike_vol_movement_pairs = new List<Tuple<double, double>>() },
atm_shift = new VolCurveMovementOperation() { strike_vol_movement_pairs = new List<Tuple<double, double>>() },
symbols = new List<string>(),
symbol_structure_list = new List<VolSurfaceSymbolStructure>(),
wing_settings = new VolSurfaceWingSettings {
explicit_slope_wing_settings = new VolSurfaceExplicitSlopeWingSettings(),
implicit_slope_wing_settings = new VolSurfaceImplicitSlopeWingSettings(),
onepoint_slope_wing_settings = new VolSurfaceOnePointSlopeWingSettings()
},
unset_expiration_calculation_settings = new VolSurfaceUnsetExpirationCalculationSettings(),
volpath_settings = new VolPathSettings(),
safety_limits = new VolChangeSafetyCheck(),
},
polynomial_model_settings = new PolynomialModelVolSurfaceSettings()
},
(settings) => _bus.post(SparkTags.VolSurfaceCreateTag, settings));
_new_vol_surface_name = string.Empty;
RaisePropertyChanged(nameof(new_vol_surface_name));
var window = new VolSurfaceSettingsEditor {
DataContext = vm,
WindowStartupLocation = WindowStartupLocation.CenterScreen
};
window.Show();
}
async Task<VolSurfaceWindow> _create_main_window(VolSurfaceWindowSettings startup_data) =>
new(_vol_surface_window_factory, _bus, await _get_vs_name(startup_data.id), startup_data);
async Task<string> _get_vs_name(int vs_id) {
var (vol_surfaces, success) = await _bus.subscribe(SparkTags.VolSurfaceListTag).FirstAsyncTask(TimeSpan.FromSeconds(2));
return success && vol_surfaces != null && vol_surfaces.TryGetValue(vs_id, out var vs_name) ?
vs_name : "(...)";
}
async Task _set_current_vol_surfaces(IDictionary<int, string> id_names) {
current_vol_surfaces.SetItems(id_names.Select(kvp => new AlgoMenuItemVM(kvp.Key, kvp.Value,
(id, name) => {
var windows = _wm.list_windows();
if (windows.OfType<VolSurfaceWindow>().TryGetFirst(w => w.vs_id == id, out var w)) {
_wm.MakeVisible(w);
return;
}
_bus.post(SparkTags.ShowVolSurface, new() { id = id });
},
(id, name) => {
if (BTSMessageBox.Confirm($"Are you sure you want to delete {name}?", "Vol Surface")) {
_bus.post(SparkTags.VolSurfaceDeleteTag, id);
}
})));
//reset titles for all open vol surface windows
foreach (var window in _wm.list_windows().OfType<VolSurfaceWindow>()) {
var vs_name = await _get_vs_name(window.vs_id);
if (window.vs_name != vs_name) {
window.Title = vs_name;
}
}
}
}
}
+42
View File
@@ -0,0 +1,42 @@
namespace mbts.spark {
using bts.api;
using bts.spark;
using mbts;
using mbts.ui;
using mbts.ui.shell;
using System;
using System.Windows;
class VolSurfaceWindow : SparkWindow<VolSurfaceWindowSettings>, ISharedWindow {
readonly VolSurfaceWindowSettings _startup_data;
VolSurfaceVM _vm;
VolSurfaceView2 _view;
public VolSurfaceWindow(
VolSurfaceWindowFactory factory, IBus bus, string vs_name, VolSurfaceWindowSettings startup_data) :
base("Vol Surface", bus, factory, Icons.vol_surface) {
_startup_data = startup_data ?? throw new ArgumentNullException(nameof(startup_data));
this.vs_name = vs_name;
_dispose = Disposable.Create(() => Disposable.dispose(ref _vm));
}
public override string window_type => _window_type;
string ISharedWindow.thread_id => "VolSurface";
public int vs_id => _startup_data.id;
public string vs_name { get; }
static string _window_type => "VolSurface";
public override VolSurfaceWindowSettings SaveState => _vm?.get_startup_data();
public override UIElement Content => _view;
public void thread_init() {
_vm = new VolSurfaceVM(new VolSurfaceDisplayModel(vs_id, _bus, true), vs_id, _bus, _startup_data);
_view = new VolSurfaceView2 { DataContext = _vm };
}
}
}
@@ -0,0 +1,33 @@
namespace mbts.spark {
using bts.api;
using bts.shell;
using mbts.ui;
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
class VolSurfaceWindowFactory : ShellWindowFactory<VolSurfaceWindowSettings> {
readonly IBus _bus;
public VolSurfaceWindowFactory(IShellModule module, IBus bus)
: base(module, "VolSurface") {
_bus = bus;
_dispose = bus.subscribe(SparkTags.ShowVolSurface).OnDispatcher().Subscribe(
async state => _bus.post(SparkTags.ShowWindow, await _create(state)));
}
public override Task<IShellWindow> load(VolSurfaceWindowSettings state) =>
_create(state);
async Task<IShellWindow> _create(VolSurfaceWindowSettings state) =>
new VolSurfaceWindow(this, _bus, await _lookup_vs_name(state.id), state);
async Task<string> _lookup_vs_name(int vs_id) {
var (vol_surfaces, success) = await _bus.subscribe(SparkTags.VolSurfaceListTag).FirstAsyncTask(TimeSpan.FromSeconds(2));
return success && vol_surfaces != null && vol_surfaces.TryGetValue(vs_id, out var vs_name) ?
vs_name : "(...)";
}
}
}
@@ -1,57 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.analytics {
using bts;
namespace mbts.analytics
{
using mbts.ui.shell;
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Contains the input (and settings) and vol per strike
public class VolSurfaceOutput : ICloneable
{
/// </summary>
public class VolSurfaceOutput : ICloneable<VolSurfaceOutput> {
public readonly VolSurfaceInput volsurface_input;
public readonly IDictionary<VolSurfaceExpiration, VolCurveOutput> exp_output_map;
public readonly IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map;
public VolSurfaceOutput(VolSurfaceInput this_volsurface_input,
IDictionary<VolSurfaceExpiration, VolCurveOutput> this_exp_output_map,
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> this_aux_data_map)
{
volsurface_input = this_volsurface_input;
exp_output_map = this_exp_output_map;
aux_data_map = this_aux_data_map;
public VolSurfaceOutput(
VolSurfaceInput volsurface_input,
IDictionary<VolSurfaceExpiration, VolCurveOutput> exp_output_map,
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map) {
this.volsurface_input = volsurface_input;
this.exp_output_map = exp_output_map;
this.aux_data_map = aux_data_map;
}
public VolCurveOutput this[VolSurfaceExpiration exp]
{
get
{
VolCurveOutput rv = exp_output_map != null && exp_output_map.TryGetValue(exp, out rv) ? rv : VolCurveOutput.get_empty_output(Double.NaN, null);
return rv;
}
}
public VolCurveOutput this[VolSurfaceExpiration exp] =>
exp_output_map != null && exp_output_map.TryGetValue(exp, out var res) ?
res : VolCurveOutput.get_empty_output(double.NaN, null);
public DateTime get_vol_time()
{
public DateTime get_vol_time() {
/// TODO : this should be part of the data vs being in each exp
/// (with the baked in assumption that its the same)
return (aux_data_map != null && aux_data_map.Count > 0) ? aux_data_map.ElementAt(0).Value.base_vol_time : DateTime.MinValue;
}
public object Clone()
{
return null;
// TODO
// return new VolSurfaceOutput(VolSurfaceUtilityFunctions.clone_proto(volsurface_input),
// new Dictionary<VolSurfaceExpiration, VolCurveOutput>(exp_output_map),
// new Dictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData>(aux_data_map));
}
public static VolSurfaceOutput get_empty_output() => new(
new VolSurfaceInput(),
new Dictionary<VolSurfaceExpiration, VolCurveOutput>(),
new Dictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData>());
public static VolSurfaceOutput get_empty_output()
{
return new VolSurfaceOutput(new VolSurfaceInput(),
new Dictionary<VolSurfaceExpiration, VolCurveOutput>(),
new Dictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData>());
}
public VolSurfaceOutput Clone() => new(
ProtoBufSerializationHelper.clone_protobuf(volsurface_input),
new Dictionary<VolSurfaceExpiration, VolCurveOutput>(exp_output_map),
new Dictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData>(aux_data_map));
object ICloneable.Clone() => Clone();
}
}
@@ -27,6 +27,9 @@ namespace mbts {
// for ProtoBuf deserialization
private SecurityExpiration() { }
public SecurityExpiration(Venue exchange, Security.ContractOneofCase type, string symbol, DateTime exp, Nullable<uint> id = null)
: this(exchange, type.security_type(), symbol, exp, id) { }
public SecurityExpiration(Venue exchange, SecurityType type, string symbol, DateTime exp, Nullable<uint> id = null)
: this(new SecurityTuple(type, symbol, exchange), exp, id) { }
@@ -1,27 +1,61 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mbts.analytics {
using ProtoBuf;
namespace mbts.analytics
{
/// All model settings exist here. With the core being there
/// they all in a way "derive" from core
[ProtoBuf.ProtoContract(Name = "VolSurfaceSettings")]
public class VolSurfaceSettings
{
[ProtoBuf.ProtoMember(10)]
[ProtoContract]
public class VolSurfaceSettings {
[ProtoMember(10)]
public VolSurfaceCoreSettings core_settings;
[ProtoBuf.ProtoMember(15)]
[ProtoMember(15)]
public VolSurfaceAdvancedSettings advanced_settings;
[ProtoBuf.ProtoMember(20)]
[ProtoMember(20)]
public PolynomialModelVolSurfaceSettings polynomial_model_settings;
[ProtoBuf.ProtoMember(30)]
[ProtoMember(30)]
public SplineModelVolSurfaceSettings spline_model_settings;
[ProtoBuf.ProtoMember(40)]
[ProtoMember(40)]
public DualQuadraticModelVolSurfaceSettings dualquadratic_model_settings;
// [ProtoBuf.ProtoMember(50)]
// public CustomModelVolSurfaceSettings custom_model_settings;
public VolSurfaceSettings ensure_no_nulls() {
if (polynomial_model_settings == null) {
polynomial_model_settings = new PolynomialModelVolSurfaceSettings();
}
if (spline_model_settings == null) {
spline_model_settings = new SplineModelVolSurfaceSettings();
}
if (dualquadratic_model_settings is null) {
dualquadratic_model_settings = new DualQuadraticModelVolSurfaceSettings();
}
if (core_settings.volpath_settings == null) {
core_settings.volpath_settings = new VolPathSettings();
}
if (core_settings.volpath_settings.two_way_slope_vol_path_settings == null) {
core_settings.volpath_settings.two_way_slope_vol_path_settings = new TwoWaySlopeVolPathSettings();
}
if (core_settings.volpath_settings.parabolic_vol_path_settings == null) {
core_settings.volpath_settings.parabolic_vol_path_settings = new ParabolicVolPathSettings();
}
if (core_settings.wing_settings == null) {
core_settings.wing_settings = new VolSurfaceWingSettings();
}
if (core_settings.wing_settings.implicit_slope_wing_settings == null) {
core_settings.wing_settings.implicit_slope_wing_settings = new VolSurfaceImplicitSlopeWingSettings();
}
if (core_settings.wing_settings.explicit_slope_wing_settings == null) {
core_settings.wing_settings.explicit_slope_wing_settings = new VolSurfaceExplicitSlopeWingSettings();
}
if (core_settings.wing_settings.onepoint_slope_wing_settings == null) {
core_settings.wing_settings.onepoint_slope_wing_settings = new VolSurfaceOnePointSlopeWingSettings();
}
if (core_settings.market_fit_settings == null) {
core_settings.market_fit_settings = new VolSurfaceMarketFitSettings();
}
if (core_settings.time_settings == null) {
core_settings.time_settings = new VolSurfaceTimeSettings();
}
return this;
}
}
}
}
@@ -11,6 +11,8 @@ using bts.settings;
using bts.spark;
using mbts.spark;
using mbts.ui.converters;
using bts.utils;
namespace mbts.analytics {
/// <summary>
@@ -77,8 +79,10 @@ namespace mbts.analytics {
}
public class VolSurfaceStrikeMap {
public readonly IDictionary<VolSurfaceExpiration, IEnumerable<double>> strike_map = null;
public VolSurfaceStrikeMap(IDictionary<VolSurfaceExpiration, IEnumerable<double>> strike_map_arg) {
strike_map = strike_map_arg;
public VolSurfaceStrikeMap(IEnumerable<string> option_names, SystemContractData sc_data) {
var on_map = new HashSet<string>(option_names);
var aux_map = sc_data.get_option_strikes(on_map);
strike_map = aux_map.ToDictionaryDupes(kv => new VolSurfaceExpiration(kv.Key), kv => kv.Value);
}
}
}
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using bts.api;
using bts.api.analytics;
@@ -1,16 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProtoBuf;
using bts.api;
using bts.settings;
using bts.spark;
using mbts.spark;
namespace mbts.analytics {
/// This is the input data (other than vol) that
@@ -28,18 +20,18 @@ namespace mbts.analytics {
/// - settlement price (if applicable)
/// - interest rate
public class VolSurfaceNonVolInput {
//public readonly bts.config.StaticConfiguration sym_input;
public readonly IDictionary<SecurityExpiration, AnalyticsExpirationParameters> exp_input_map;
public VolSurfaceNonVolInput(/*bts.config.StaticConfiguration this_sym_input,*/
IDictionary<SecurityExpiration, AnalyticsExpirationParameters> this_exp_input_map) {
//sym_input = this_sym_input;
public VolSurfaceNonVolInput(
IDictionary<SecurityExpiration, AnalyticsExpirationParameters> this_exp_input_map) {
exp_input_map = this_exp_input_map;
}
public IDictionary<VolSurfaceExpiration, AnalyticsExpirationParameters> get_option_exp_input() {
var list = exp_input_map.Where(kv => kv.Key.security_type == SecurityType.Option);
return list.ToDictionary(kv => new VolSurfaceExpiration() { symbol = kv.Key.symbol, expiration = kv.Key.expiration }, kv => kv.Value);
return list.ToDictionary(
kv => new VolSurfaceExpiration() { symbol = kv.Key.symbol, expiration = kv.Key.expiration },
kv => kv.Value);
}
public AnalyticsExpirationParameters find_exp_parameter(SecurityExpiration exp) {
@@ -50,7 +42,8 @@ namespace mbts.analytics {
/// This ignores the exchange in the comparison and returns
/// the first match. This will be a problem for multi-listed
/// symbols
public AnalyticsExpirationParameters find_exp_parameter(SecurityType sec_type, string symbol, DateTime exp) {
public AnalyticsExpirationParameters find_exp_parameter(SecurityType sec_type,
string symbol, DateTime exp) {
/// TODO:incons
foreach (KeyValuePair<SecurityExpiration, AnalyticsExpirationParameters> kv in exp_input_map)
if (kv.Key.security_type == sec_type && kv.Key.symbol == symbol && kv.Key.expiration == exp)
@@ -67,7 +60,8 @@ namespace mbts.analytics {
}
public IDictionary<mbts.SecurityTuple, double> get_cpp_map() {
return get_cpp_list().ToDictionary(t => new mbts.SecurityTuple(t.Item1, t.Item2, Venue.Unset), t => t.Item3);
return get_cpp_list().ToDictionary(
t => new mbts.SecurityTuple(t.Item1, t.Item2, Venue.Unset), t => t.Item3);
}
}
}
+1
View File
@@ -207,6 +207,7 @@ namespace mbts.ui {
public static ImageSource WarningExclamation => create_icon(WarningExclamationGeometryKey, Brushes.IndianRed);
public static ImageSource UndoCircular => create_icon(UndoCircularGeometryKey);
public static ImageSource ViewSettings => load_resource_and_freeze("ViewSettings");
public static ImageSource vol_surface => Math;
public static ImageSource Wrench { get { return load_resource_and_freeze("Wrench"); } }
public static ImageSource RightArrow { get { return (load_resource_and_freeze("RightArrow")); } }
public static ImageSource DownArrow { get { return (load_resource_and_freeze("DownArrow")); } }
@@ -43,6 +43,11 @@ namespace mbts.spark {
_settings_manager = settings_manager;
Icon.Freeze();
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().market_view ? "MarketView" : null;
_dispose = Disposable.Create(() => {
Disposable.dispose(ref _subscriptions);
_vm.Dispose();
Commands.OfType<IDisposable>().DisposeAll();
});
}
event Action<MarketViewWindowFactory.StartupData> _state_changed;
@@ -193,12 +198,6 @@ namespace mbts.spark {
_sorted_selected_security_criteria_backing = null;
}
public override void Dispose() {
Disposable.dispose(ref _subscriptions);
_vm.Dispose();
Commands.OfType<IDisposable>().DisposeAll();
}
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
_menu_display_vm.safe_bind_to_view(parent_view);
}
@@ -83,10 +83,10 @@ namespace bts.shell {
var ask_col_index = columns.FindIndex(x => x.id == col_id(Columns.Ask));
if (bid_col_index > -1 && ask_col_index > -1) {
if (!columns[bid_col_index].background_color_override.HasValue) {
columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.ToUint()));
columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.value));
}
if (!columns[ask_col_index].background_color_override.HasValue) {
columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.ToUint()));
columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.value));
}
}
// and enable background color upgrade
@@ -253,11 +253,11 @@ namespace bts.shell {
bool applied = false;
if (bid_col_index > -1 && ask_col_index > -1) {
if (!columns[bid_col_index].background_color_override.HasValue) {
columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.ToUint()));
columns[bid_col_index] = columns[bid_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.bid.value));
applied = true;
}
if (!columns[ask_col_index].background_color_override.HasValue) {
columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.ToUint()));
columns[ask_col_index] = columns[ask_col_index].with(background_color_override: new NullableColorProto(BTSColors.MarketData.ask.value));
applied = true;
}
}
@@ -60,6 +60,7 @@ namespace bts.shell.time_and_sales {
_can_pause_updates = can_pause_updates;
thread_id = mbts.config.Configuration.get<bts.config.MultiThreadedWindows>().time_and_sales ? _window_type : null;
Icon.Freeze();
_dispose = Disposable.Create(_dispose_resources);
}
event Action<SecurityCriteria> _security_criteria_changed;
@@ -88,9 +89,6 @@ namespace bts.shell.time_and_sales {
}
}
public override void Dispose() =>
_dispose_resources();
public void thread_init() {
_dispose_resources();
_ensure_state();
@@ -33,7 +33,7 @@ namespace mbts.spark {
SyntheticManagementView _view;
SparkMenuDisplayVM _menu_display_vm;
IDisposable _subscriptions;
IReadOnlyList<SparkCommand> _commands;
List<SparkCommand> _commands;
readonly IWindowSettingsManager<GridSettings> _settings_manager;
public SyntheticManagementWindow(SyntheticManagementWindowFactory factory, IBus bus, OrdersModel orders_model, StartupData state, IWindowSettingsManager<GridSettings> settings_manager)
@@ -42,7 +42,15 @@ namespace mbts.spark {
_state = state;
_settings_manager = settings_manager;
Icon.Freeze();
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().synthetic_management ? "SyntheticManagement" : null;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().synthetic_management ?
"SyntheticManagement" : null;
_dispose = Disposable.Create(() => {
Disposable.dispose(ref _vm);
if (_commands != null) {
_commands.OfType<IDisposable>().DisposeAll();
_commands = null;
}
});
}
public override string window_type => _window_type;
@@ -65,7 +73,8 @@ namespace mbts.spark {
var current_row_source = vm_connectable_builder.create(vm => vm.current_row_observable);
var current_row_connectable_builder = new ConnectableSeriesBuilder<SyntheticManagementDialogVM.Row>(current_row_source);
_commands = new SparkCommand[] {
Log.isnull(_commands);
_commands = new() {
SparkCommand.create("Add", Icons.AddSynthetic, SparkTags.ShowSyntheticCreateTag).complete(
() => new SecurityCriteria(), () => true
), SparkCommand.create("Remove", Icons.RemoveSynthetic, SparkTags.SyntheticDeleteTag).complete(
@@ -132,11 +141,6 @@ namespace mbts.spark {
SyntheticImporter.import_from_file(path, _bus, _orders_model);
}
public override void Dispose() {
Disposable.dispose(ref _vm);
Commands.OfType<IDisposable>().DisposeAll();
}
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
_menu_display_vm.safe_bind_to_view(parent_view);
@@ -19,12 +19,13 @@ namespace bts.shell {
const string _window_type = "ActivityLog";
readonly IObservable<LogViewerMessage> _message_src;
readonly LogViewerMessageCollection _messages = new LogViewerMessageCollection();
IDisposable _dispose;
IDisposable _ui_thread_dispose;
LogViewer _content;
public ActivityLogWindow(IObservable<LogViewerMessage> messages, IBus bus, ActivityWindowFactory isw)
: base("Activity Log", bus, isw, SparkCommands.ShowActivityLog.icon) {
_message_src = messages;
_dispose = Disposable.Create(() => Disposable.dispose(ref _ui_thread_dispose));
}
public override string window_type => _window_type;
@@ -34,12 +35,9 @@ namespace bts.shell {
public string thread_id => nameof(ActivityLogWindow);
public override void Dispose() {
Disposable.dispose(ref _dispose);
}
public void thread_init() {
_dispose = _message_src.OnDispatcher().Subscribe(_messages.AddLog);
Log.isnull(_ui_thread_dispose);
_ui_thread_dispose = _message_src.OnDispatcher().Subscribe(_messages.AddLog);
_content =
new LogViewer {
ItemsSource = _messages,
@@ -42,6 +42,7 @@ namespace mbts.spark {
_model = model;
_state = state;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().algo_studio ? "AlgoStudio" : null;
_dispose = Disposable.Create(_dispose_core);
}
public override StartupData SaveState => _state = _vm.create();
@@ -58,9 +59,6 @@ namespace mbts.spark {
bts.config.AlgoStudioOptions _ui_configuration => _model.algo_model.ui_configuration;
public override void Dispose() =>
_dispose_core();
public void thread_init() {
_dispose_core();
_vm = new AlgoStudioVM(_model);
@@ -21,14 +21,16 @@ using System.Windows;
namespace mbts.spark {
class FillsWindow : SparkWindow<FillsSettings>, ISharedWindow {
public const string window_type_name = "Fills";
readonly AllowOnce _init_guard = new AllowOnce("Fills");
readonly OrdersModel _orders_model;
readonly IWindowSettingsManager<GridSettings> _settings_manager;
FillsVM _vm;
FillsView _view;
FillsSettings _state;
SparkMenuDisplayVM _menu_display_vm;
IReadOnlyList<SparkCommand> _commands;
List<SparkCommand> _commands;
public FillsWindow(FillsWindowFactory factory, IBus bus, OrdersModel orders_model, FillsSettings state, WindowSettingsManager<GridSettings> settings_manager)
: base("Fills", bus, factory, SparkCommands.ShowFills().icon) {
@@ -36,6 +38,13 @@ namespace mbts.spark {
_state = state;
_settings_manager = settings_manager;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().fills ? "Fills" : null;
_dispose = Disposable.Create(() => {
Disposable.dispose(ref _vm);
if (_commands != null) {
_commands.OfType<IDisposable>().DisposeAll();
_commands = null;
}
});
}
public override string window_type => window_type_name;
@@ -62,7 +71,8 @@ namespace mbts.spark {
_vm = new FillsVM(_bus, _orders_model, _state, _settings_manager);
_view = new FillsView { DataContext = _vm };
_commands = new List<SparkCommand> {
Log.isnull(_commands);
_commands = new() {
// wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes
SparkCommands.window_settings_command(new DialogCommand(() => {
var vm = new ShellSettingsDialogVM<GridSettings, SimpleGridSettingsVM>(
@@ -84,11 +94,6 @@ namespace mbts.spark {
};
}
public override void Dispose() {
Disposable.dispose(ref _vm);
Commands.OfType<IDisposable>().DisposeAll();
}
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
_menu_display_vm.safe_bind_to_view(parent_view);
}
@@ -94,19 +94,14 @@ namespace mbts.spark {
}
public void update() {
// update brushes
Color color;
switch (side) {
case Side.Buy: color = BTSColors.MarketData.bid_alt; break;
case Side.Sell: color = BTSColors.MarketData.ask_alt; break;
case Side.Undefined:
default:
color = BTSColors.MarketData.bid_ask_alt_blend; break;
}
var darker = BTSColor.darken2(color.R, color.G, color.B, 0.75);
Color dark = new Color() { A = 255, R = darker.r, G = darker.g, B = darker.b };
var buy_sell_background_fill_color = new SolidColorBrush(color);
buy_sell_background_fill_color.Freeze();
var color = side switch {
Side.Buy => BTSColors.MarketData.bid_alt,
Side.Sell => BTSColors.MarketData.ask_alt,
_ => BTSColors.MarketData.bid_ask_alt_blend,
};
var (r, g, b) = color.darken2(0.75);
var dark = Color.FromRgb(r, g, b);
var buy_sell_background_fill_color = color.to_brush().frozen();
background = buy_sell_background_fill_color;
hoverbackground = mkbrush(dark, _darkbg, 0);
@@ -726,7 +726,7 @@ namespace mbts.spark {
public LadderMarketBreakLine get_settings() =>
new LadderMarketBreakLine {
color = new BTSColor(color).ToUint(),
color = new BTSColor(color).value,
show = show,
refresh_mode = refresh_mode
};
@@ -51,6 +51,11 @@ namespace mbts.spark {
_settings_manager = settings_manager;
_can_edit_specific_algo_params = can_edit_specific_algo_params;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().order_book ? "OrderBook" : null;
_dispose = Disposable.Create(() => {
Disposable.dispose(_thread_init_resources);
Disposable.dispose(ref _attachment_exit_sub);
Disposable.dispose(ref _vm);
});
}
public override OrderBookStartupData SaveState {
@@ -72,12 +77,6 @@ namespace mbts.spark {
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
public string thread_id { get; }
public override void Dispose() {
Disposable.dispose(_thread_init_resources);
Disposable.dispose(ref _attachment_exit_sub);
Disposable.dispose(ref _vm);
}
public void thread_init() {
Log.assert(_thread_init_resources == null, $"{nameof(_thread_init_resources)} must be initialized in thread_init.");
_thread_init_resources = new List<IDisposable>();
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff. Show more