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

This commit is contained in:
Kevin Darby committed 2019-06-18 14:40:23 -04:00
commit 2b7f5572db
55 files changed
+1553 -928

No files matched your search

+20 -2
View File
@@ -4,6 +4,23 @@ weight = 3
sort_by = "weight"
insert_anchor_links = "right"
+++
## 2.3.0
### User Visible Changes
- Changed cover order to continue even if hedgding child is canceled and detach from hedges if canceled
- Changed Lean and Join algos to hide themselves in the ladder once they are triggered
- Changed manual fills to appear in day PnL rather than in the SOD records
- Add buy/sell coloring to fill rows in fills window
- Streamlined the mini order book as follows:
- We now only show exchange orders
- We now only display update buttons for orders that are under control of an algo with the update applying to the entire algo, not just the exchange order
- We can now select multiple rows to attach, detach, update or cancel multiple orders in a batch
- A checkbox column has been added to make clearer which rows are selected
### API Changes
- Enhanced the API to allow algos to implement custom cancel handling
- Allowed algos to control their visibility in the ladder through the API
### Internal Changes
- Added system requirements to Spark documentation
## 2.2.0
### User Visible Changes
- Made our orders easier to spot in MBO display
@@ -18,7 +35,8 @@ insert_anchor_links = "right"
- Fixed a number of problems with filtering on the Fills form
- On the Lean algo, OnToward and Away are now calculated with respect to the opposite inside market at time of the order launch
- Iceberg Spreaders with queue holders are not erroneously cancelled after the first fill
- Security symbol added for fills window
- Added security symbol column to fills window
- Re-organized ladder settings dialog to make it clearer and easier to use
## 2.1.4
### User Visible Changes
@@ -351,7 +369,7 @@ insert_anchor_links = "right"
- This is configurable from a ladder's settings as well
### Customized settings in all windows
- All windows now contain a settings page where grid settings (font color, size, etc) are applied
- These settings can be saved on a per-window basis or as a Default for newly-launched windows
- These settings can be saved on a per-window basis or as a Default for newly-launched windows␍
## 1.3.1 Through 1.3.4
@@ -0,0 +1,55 @@
+++
title = "System Requirements"
weight = 4
sort_by = "weight"
insert_anchor_links = "right"
+++
### Minimum Workstation
* New XPS Tower
* 8th Generation Intel® Core™ i7-8700 6-Core Processor (12M Cache, up to 4.6 GHz)
* 16GB, 2666MHz, DDR4 up to 64GB
* Windows 10 Professional 64-bit
* NVIDIA® GeForce® GTX 1070 with 8GB GDDR5 Graphics Memory
* 1 x 2.5" 256GB SATA Solid State Drive
### Recommended Workstation
* Similar or better than:
* Dell Precision Tower 5820
* Intel Xeon W-2145 3.7GHz, 4.5GHz Turbo, 8C, 11M Cache, HT, (140W) DDR4-2666
* Windows 10 Professional 64-bit
* NVIDIA® Quadro® P1000, 4GB, 4 mDP
* 16GB (4x4GB) 2133MHz DDR4 RDIMM ECC
* 2 x 2.5" 256GB SATA Solid State Drive running RAID1
### BTS Recommended Server Specifications
* Dell R640
* 2x Intel Xeon Gold 6148 2.40GHz 20-Core Processors. For better performance BTS recommends Intel® Xeon® Platinum 8268 2.9G, 24 Core CPU
* 192GB RAM 2666MHz DDR4
* 3x 480GB SSD RAID 5 HBA Minicard
* iDRAC 9 Enterprise
* Embedded Broadcom NIC
* Solarflare SFN8522-R2
* Redundant Power Supply
### BTS Minimum Server Specifications
* Dell R620
* Chassis with up to 8, 2.5” Hard Drives, up to 2 PCIe Slots (With Optional Riser)
* 2 x Intel® E5-2670 (16 total cores/ 32 total threads)
* 64GB total memory
* RAID 1 for H330/H730/H730P
* PERC H730 RAID Controller, 1GB NV Cache
* 3 x 300GB 10K RPM SATA 6Gbps 2.5in Hot-plug Hard Drive (RAID 5)
* iDRAC8 Enterprise, integrated Dell Remote Access Controller, Enterprise (varies by hosting company)
* Solarflare Ultra SFN7122F Dual-Port 10GbE (10 GB connectivity requirements, copper vs optical, varies by hosting company).
* Dual, Hot-plug, Redundant Power Supply (1+1), 750W
* Performance BIOS Setting
* ReadyRails Sliding Rails Without Cable Management Arm (varies by hosting company)
### Edge Tablet Requirements
* Similar or better than:
* Microsoft Surface Pro 4 Or Motion R12
* Intel i7
* 8 GB DDR4 RAM
-5
View File
@@ -1,7 +1,6 @@
#/bin/bash
#python -m mkdocs build -d site
cp -r ../../src/sdk/doc/* ./content/bts_spark_sdk/Server/
./run_zola.sh build
scp -r ./public bts@bluetradesys.com:/home/bts/doc/
@@ -14,7 +13,3 @@ sudo mv ./public/* /var/www/documentation/
EOF
rm -r public
cd ./content/bts_spark_sdk/server/
find . -not -name '_index.md' -delete
cd ../..
@@ -49,13 +49,8 @@ namespace mbts.spark {
add_column(TimeAndSalesView.Columns.Aggressor, DefaultColumnHeaders.Aggressor, DefaultColumnWidths.Aggressor, nameof(Row.aggressor_side), aggressor_filter, DataGridFilterKnownTemplates.EnumValues);
add_column(TimeAndSalesView.Columns.SecurityKey, DefaultColumnHeaders.SecurityKey, DefaultColumnWidths.SecurityKey, nameof(Row.security_key), security_key_filter, DataGridFilterKnownTemplates.Regex);
void add_column(TimeAndSalesView.Columns col_key, string header, double width, string sort_member_path, IDataGridColumnFilter filter, string filter_template, System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) =>
columns.Add(new TimeAndSalesColumn(
col_key
, (r) => _get_aggressor_brush(r)
, filter
, filter_template
)
{ Header = header, Width = width, sort_member_path = sort_member_path, horizontal_alignment = h_alignment }
columns.Add(new RenderTextColumn<Row, TimeAndSalesView.Columns>(col_key, r => r[col_key], filter, filter_template, r => _get_aggressor_brush(r))
{ id = col_id(col_key), Header = header, Width = width, sort_member_path = sort_member_path, horizontal_alignment = h_alignment }
);
// be sure to load GridSettings AFTER the columns collection has been populated, the grid settings manager looks columns by id to apply the appropriate settings,
@@ -3,6 +3,7 @@ using bts.persist.algo;
using bts.utils;
using ProtoBuf;
using System;
using System.Linq;
namespace mbts.spark {
[ProtoContract]
@@ -14,6 +15,11 @@ namespace mbts.spark {
[ProtoMember(3)]
readonly uint? _persisted_key;
public static readonly AlgoID[] exchange_algo_keys = utilities.OrderDataHelper.outright_order_types
.Concat(new CustomOrderDefinition.CustomOneofCase[] { CustomOrderDefinition.CustomOneofCase.Spreader })
.Select(cooc => new AlgoID(cooc))
.ToArray();
public AlgoID(CustomOrderDefinition.CustomOneofCase factory_key) {
_factory_key = factory_key;
_dynamic_key = null;
@@ -6,6 +6,10 @@
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:uspcv="clr-namespace:mbts.ui.spark.converters"
xmlns:cv="clr-namespace:mbts.ui.converters"
xmlns:u="clr-namespace:mbts.ui"
xmlns:api="clr-namespace:bts.api;assembly=spark_api"
xmlns:bts="clr-namespace:mbts.ui.controls"
FocusManager.IsFocusScope="True"
Background="{StaticResource CommonBackground}"
>
@@ -15,6 +19,10 @@
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/FilterTemplates.xaml"/>
</ResourceDictionary.MergedDictionaries>
<uspcv:TickDisplayConverter x:Key="TickDisplayConverter"/>
<cv:ValueMap x:Key="SideToBrushConverter" Default="{u:Brush Transparent}">
<cv:KeyValue Key="{u:Enum Buy, Type=api:Side}" Value="{x:Static semi_transparent_bid_brush, MemberType={u:Nested u:BTSColors.MarketData}}"/>
<cv:KeyValue Key="{u:Enum Sell, Type=api:Side}" Value="{x:Static semi_transparent_ask_brush, MemberType={u:Nested u:BTSColors.MarketData}}"/>
</cv:ValueMap>
</ResourceDictionary>
</UserControl.Resources>
<AdornerDecorator>
@@ -41,10 +49,10 @@
CanExecute="{x:Static c:DIYGrid.DefaultRowActionCanExecute}"
/>
</c:DIYGrid.CommandBindings>
<c:DIYGrid.RowTemplate>
<DataTemplate>
<usp:FillsRowView/>
</DataTemplate>
<c:DIYGrid.RowTemplate>
<DataTemplate>
<usp:FillsRowView Background="{Binding side, Converter={StaticResource SideToBrushConverter}}"/>
</DataTemplate>
</c:DIYGrid.RowTemplate>
</c:DIYGrid>
<StatusBar Grid.Row="1" DockPanel.Dock="Bottom">
@@ -327,7 +327,15 @@ namespace mbts.spark {
public enum BadgeStyle { Normal, Alternate }
public enum NetChangeTerms { None, Dollars, Ticks }
// TODO: rename to PriceDisplayFormat (today is merge monday, since this isn't a functional change, it is not worth the potential merge headaches right now)
public enum NetChangeTerms {
[Description("Standard Ticks")]
None,
[Description("Net Change Dollars")]
Dollars,
[Description("Net Change Ticks")]
Ticks
}
[ProtoMember(1)]
public double row_height { get; set; }
@@ -1,5 +1,6 @@
using bts.api;
using bts.api.orderman;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.shell;
using System;
@@ -297,7 +298,8 @@ namespace mbts.spark {
new bts.shell.orderbook.FilterStates {
security_criteria = new SecurityCriteria(_owner.security),
price = price_filter,
statuses = new[] { OrderStatus.Working }
statuses = new[] { OrderStatus.Working },
order_types = AlgoID.exchange_algo_keys
},
bts.shell.orderbook.OrderBookStartupData.default_mini_grid,
use_defaults: false
@@ -335,6 +337,7 @@ namespace mbts.spark {
}
obvm.columns.Insert(0, new OrderBookVM.UpdateColumn(typeof(MiniOrderBookView)));
obvm.columns.Insert(0, new OrderBookVM.CancelColumn(nameof(OrderBookRowVM.cancel_command)));
obvm.columns.Insert(0, new OrderBookVM.CheckColumn(nameof(OrderBookRowVM.is_selected)));
obvm.load_from(state);
return obvm;
@@ -23,6 +23,7 @@ namespace mbts.spark {
readonly Property<LadderSettings.BadgeStyle> _badge_style;
readonly Property<uint> _alternate_order_size;
readonly DelegateProperty<double> _row_height;
LadderSettings.NetChangeTerms _price_format;
Func<double> _get_order_entry_panel_width, _get_zoom_factor;
LadderSettings _current;
LadderColumnSettingsVM
@@ -30,8 +31,8 @@ namespace mbts.spark {
_bid = new LadderColumnSettingsVM("Bid"),
_price = new LadderColumnSettingsVM("Price"),
_ask = new LadderColumnSettingsVM("Ask"),
_last = new LadderColumnSettingsVM("Last", true),
_piq = new LadderColumnSettingsVM("PIQ", true);
_last = new LadderColumnSettingsVM("Last", LadderSettingsView.LastColumnTemplateKey, true),
_piq = new LadderColumnSettingsVM("PIQ", can_toggle_show: true);
VolumeColumnVM _volume = new VolumeColumnVM();
LadderMarketBreakLineVM
_bid_mkt_line = new LadderMarketBreakLineVM("Bid"),
@@ -59,10 +60,6 @@ namespace mbts.spark {
_cancel_buys_visibility = new OrderEntryPanelItemVisibilityVM("Cancel Buys"),
_cancel_sells_visibility = new OrderEntryPanelItemVisibilityVM("Cancel Sells"),
_cancel_all_visibility = new OrderEntryPanelItemVisibilityVM("Cancel All");
readonly Property<bool>
_show_in_net_change,
_show_in_net_change_dollars,
_show_in_net_change_ticks;
public LadderSettingsVM(OrdersModel model, bool is_synthetic, Func<double> get_left_panel_width, Func<double> get_zoom_factor) {
this.is_synthetic = is_synthetic;
@@ -74,10 +71,6 @@ namespace mbts.spark {
_alternate_order_size = backing<uint>(nameof(alternate_order_size));
_get_order_entry_panel_width = get_left_panel_width;
_get_zoom_factor = get_zoom_factor;
_show_in_net_change = backing<bool>(nameof(show_in_net_change));
_show_in_net_change_dollars = backing<bool>(nameof(show_in_net_change_dollars));
_show_in_net_change_ticks = backing<bool>(nameof(show_in_net_change_ticks));
// be sure to initialize backings before this measure_row_height call
_row_height = backing(nameof(row_height), () => LadderRender.measure_row_height(get_result()));
_orders.font_size_changed += on_font_size_changed;
@@ -110,6 +103,8 @@ namespace mbts.spark {
}
public MarketSizeDisplayVM size_display { get; } = new MarketSizeDisplayVM();
public LadderSettings.NetChangeTerms price_format { get => _price_format; set => Set(ref _price_format, value); }
public IEnumerable<LadderSettings.NetChangeTerms> price_format_options => EnumHelper.get_values<LadderSettings.NetChangeTerms>();
public FavoriteAlgosVM favorite_algos_vm { get; }
public double row_height => _row_height.Value;
@@ -175,32 +170,6 @@ namespace mbts.spark {
}
}
public bool show_in_net_change {
get => _show_in_net_change.Value;
set {
// when unchecking, clear out dollars and ticks
if (!value) {
show_in_net_change_dollars = false;
show_in_net_change_ticks = false;
}
// when checking, by defalt check dollars
if (value) {
show_in_net_change_dollars = true;
}
_show_in_net_change.Value = value;
}
}
public bool show_in_net_change_dollars {
get => _show_in_net_change_dollars.Value;
set => _show_in_net_change_dollars.Value = value;
}
public bool show_in_net_change_ticks {
get => _show_in_net_change_ticks.Value;
set => _show_in_net_change_ticks.Value = value;
}
public string key => GridSettingsTemplateKeys.Ladder;
public void load(LadderSettings settings) {
@@ -241,13 +210,11 @@ namespace mbts.spark {
_cancel_buys_visibility.show = settings.cancel_buys_visible;
_cancel_sells_visibility.show = settings.cancel_sells_visible;
_cancel_all_visibility.show = settings.cancel_all_visible;
price_format = settings.net_change;
// do not read the order entry panel width here from settings
// because it could have changed from the UI
// there might be a better way of doing this, like how
// does the widths of the ladder grid column pull this off?
show_in_net_change = settings.net_change != LadderSettings.NetChangeTerms.None;
show_in_net_change_dollars = settings.net_change == LadderSettings.NetChangeTerms.Dollars;
show_in_net_change_ticks = settings.net_change == LadderSettings.NetChangeTerms.Ticks;
}
public LadderSettings get_result() {
@@ -291,19 +258,8 @@ namespace mbts.spark {
clone.order_entry_panel_initial_width = _get_order_entry_panel_width();
clone.zoom_slider_visible = _zoom_slider_visbility.show;
clone.zoom_factor = _get_zoom_factor();
clone.net_change = _create_net_change_terms(show_in_net_change_dollars, show_in_net_change_ticks);
clone.net_change = price_format;
return clone;
LadderSettings.NetChangeTerms _create_net_change_terms(bool dollars, bool ticks) {
if (dollars) {
return LadderSettings.NetChangeTerms.Dollars;
}
if (ticks) {
return LadderSettings.NetChangeTerms.Ticks;
}
return LadderSettings.NetChangeTerms.None;
}
}
public void Dispose() => favorite_algos_vm.Dispose();
@@ -323,11 +279,12 @@ namespace mbts.spark {
readonly DelegateProperty<FontWeight> _font_weight;
readonly DelegateProperty<string> _font_display_name;
readonly Property<bool> _show;
readonly bool _can_toggle_visibility;
readonly string _template_key;
public LadderColumnSettingsVM(string name, bool can_toggle_visibility = false) {
public LadderColumnSettingsVM(string name, string template_key = null, bool can_toggle_show = false) {
this.name = name;
_can_toggle_visibility = can_toggle_visibility;
_template_key = template_key;
this.can_toggle_show = can_toggle_show;
foreground_palettes = new ObservableCollection<ColorPaletteVM>(ColorPalette.all_presets().Select(p => new ColorPaletteVM(p)));
background_palettes = new ObservableCollection<ColorPaletteVM>(ColorPalette.all_presets().Select(p => new ColorPaletteVM(p)));
_show = backing(nameof(show), true);
@@ -340,8 +297,14 @@ namespace mbts.spark {
_font_display_name = backing(nameof(font_display_name),
() => TextUtils.display_name(font_family, font_weight, font_size), nameof(font_family), nameof(font_weight), nameof(font_size));
_font_size.Changed += (oldval, newval) => font_size_changed?.Invoke(oldval, newval);
toggle_show_details_cmd = new DelegateCommand(() => {
show_details = !show_details;
RaisePropertyChanged(nameof(show_details));
});
}
public event Action<double, double> font_size_changed;
public string name { get; }
public Typeface typeface { get => _typeface.Value; set => _typeface.Value = value; }
public FontFamily font_family => _font_family.Value;
@@ -350,14 +313,17 @@ namespace mbts.spark {
public double font_size { get => _font_size.Value; set => _font_size.Value = value; }
public uint width { get; set; }
public bool show { get => _show.Value; set => _show.Value = value; }
public bool can_toggle_show { get; }
public bool show_details { get; private set; }
public Color foreground { get => _foreground.Value; set => _foreground.Value = value; }
public Color background { get => _background.Value; set => _background.Value = value; }
public ObservableCollection<ColorPaletteVM> foreground_palettes { get; }
public ObservableCollection<ColorPaletteVM> background_palettes { get; }
public event Action<double, double> font_size_changed;
public virtual string sample_text => "999-56789.01234";
string ITemplateSelectorKey.key => _can_toggle_visibility ? ui.spark.LadderSettingsView.ColumnVisibilityToggleTemplateKey : null;
public ICommand toggle_show_details_cmd { get; }
string ITemplateSelectorKey.key => _template_key;
public void assign_from(LadderColumnSettings settings) {
typeface = new Typeface(
@@ -395,7 +361,7 @@ namespace mbts.spark {
public Brush badge_border { get; } = new SolidColorBrush(BTSColors.MarketData.ask);
public Brush badge_background { get; } = Brushes.White;
string ITemplateSelectorKey.key => ui.spark.LadderSettingsView.OrdersColumnSampleTemplateKey;
string ITemplateSelectorKey.key => ui.spark.LadderSettingsView.OrdersColumnTemplateKey;
}
public class LadderMarketBreakLineVM : ViewModelBase {
@@ -463,7 +429,7 @@ namespace mbts.spark {
}
}
public LadderColumnSettingsVM general { get; } = new LadderColumnSettingsVM("Volume", true);
public LadderColumnSettingsVM general { get; } = new LadderColumnSettingsVM("Volume", LadderSettingsView.VolumeColumnTemplateKey, true);
public VolumeAtPriceAnimationVM buy { get; }
public VolumeAtPriceAnimationVM sell { get; }
public VolumeAtPriceAnimationVM passive { get; }
@@ -337,6 +337,7 @@ namespace mbts.spark {
if (e.ChangedButton == MouseButton.Middle) {
if (bs.HasValue) {
_send_parameterized_order(point, bs.Value);
return;
} else if (column.column_type == ColumnType.Price) {
if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown (Key.RightShift) ||
Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt)) {
@@ -344,6 +345,7 @@ namespace mbts.spark {
} else {
_scroll_to_center();
}
return;
}
}
var pbs = (price, bs, e.ChangedButton);
@@ -139,6 +139,7 @@ namespace mbts.spark {
// properly Dispose of it later when the popup is closed.
DataContext = obvm,
Child = view,
// StaysOpen true for debugging
StaysOpen = false,
PlacementTarget = popup_placement_target,
Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom,
File diff suppressed because it is too large. Load diff
@@ -10,10 +10,15 @@ namespace mbts.ui.spark {
/// </summary>
partial class LadderSettingsView : UserControl {
public const string
OrdersColumnSampleTemplateKey = nameof(OrdersColumnSampleTemplateKey),
ColumnVisibilityToggleTemplateKey = nameof(ColumnVisibilityToggleTemplateKey),
OrdersColumnTemplateKey = nameof(OrdersColumnTemplateKey),
VolumeColumnTemplateKey = nameof(VolumeColumnTemplateKey),
LastColumnTemplateKey = nameof(LastColumnTemplateKey),
FavoriteAlgoAddButtonTemplateKey = nameof(FavoriteAlgoAddButtonTemplateKey);
public static readonly IMultiValueConverter LadderColumnToggleShowToolTipConverter =
ValueConverter.create<bool, bool, string, string>((can_toggle_show, show, col_name) =>
can_toggle_show ? $"{(show ? "Hide" : "Show")} {col_name}" : $"{col_name} cannot be {(show ? "hidden" : "shown")}.");
public LadderSettingsView() =>
InitializeComponent();
@@ -99,7 +99,16 @@
</MultiDataTrigger.Setters>
</MultiDataTrigger>
</Style.Triggers>
<!-- We added this IsSelected after seeing some strangeness when bringing up the Mini OB,
then clicking the attach button, then performing a click to modify a param in the popup, the grid
would lose the appearance of its selected row. I think this was actually a result of a bad path
in the SelectionHighlight expression below, but that leaves me questioning how if it was bad (and
it was, I confirmed in Snoop) did the Grid successfully show a highlighted row in the first place.
At any rate, I have a strong suspicion this Setter is no longer necessary, but I am too exhausted
and scared to remove it at this point.
-->
<Setter Property="IsSelected" Value="{Binding is_selected, Mode=TwoWay}" />
</Style>
<DataTemplate x:Key="{x:Static sp:MiniOrderBookView.RowTemplateKey}">
<sp:MiniOrderBookRowView/>
@@ -121,10 +130,9 @@
Rows="{Binding rows}"
RowStyle="{StaticResource {x:Static sp:MiniOrderBookView.RowStyleKey}}"
RowTemplate="{StaticResource {x:Static sp:MiniOrderBookView.RowTemplateKey}}"
SelectionHighlight="{Binding grid_settings_manager.selection_highlight, Mode=OneWay}"
SelectionHighlight="{Binding grid_settings_manager.core_manager.selection_highlight, Mode=OneWay}"
RowsHorizontalScrollBarVisibility="Collapsed"
RowHeight="20"
SelectionMode="Single"
>
<c:DIYGrid.Resources>
<ResourceDictionary>
@@ -724,6 +724,33 @@ namespace mbts.spark {
}
}
public class CheckColumn : FrameworkElementColumnBase<Columns> {
readonly BindingBase _checked_binding;
public CheckColumn(string checked_property) : base(Columns.Check) {
id = key.ToString();
Width = 30;
_checked_binding = new Binding(checked_property);
var header_cb = new CheckBox();
header_cb.ToolTip = "Select / Unselect All";
header_cb.SetBinding(CheckBox.IsCheckedProperty, new Binding(nameof(OrderBookVM.all_rows_selected)));
this.Header = header_cb;
}
public override FrameworkElement view_factory() {
var grid = new Grid() {
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
};
var cb = new CheckBox();
cb.Name = "check_col";
cb.SetBinding(CheckBox.IsCheckedProperty, _checked_binding);
grid.Children.Add(cb);
return grid;
}
}
public class CancelColumn : FrameworkElementColumnBase<Columns> {
readonly BindingBase _command_binding;
@@ -829,13 +856,13 @@ namespace mbts.spark {
var row_vm_attach_command_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookRowVM.attach_command)));
row_vm_attach_command_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
attach_button.SetBinding(Button.CommandProperty, row_vm_attach_command_binding);
attach_button.SetBinding(Button.CommandProperty, row_vm_attach_command_binding);
#region OrderParamsPanel
// finally, set the order_params DataContext to that of the ContextMenu
var order_params = AlgoEditorGridView.create_attach_view();
var order_params_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.attach_vm)));
order_params_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
order_params_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
order_params.SetBinding(FrameworkElement.DataContextProperty, order_params_binding);
order_params.SetBinding(AlgoEditorGridView.AlgoRootsProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_roots))));
order_params.SetBinding(AlgoEditorGridView.SelectedAlgoRootProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_root))));
@@ -857,6 +884,7 @@ namespace mbts.spark {
// We take our original ICommand (send_attached) and wrap it in another Command by way of a Converter on the binding,
// pure genious!
var send_attach_button_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.send_attached_orders_cmd))) {
// set to true for debugging
Converter = CommandWithActionWrapper.mk_wrap_converter(() => popup.IsOpen = false)
};
send_attach_button_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
@@ -907,6 +935,7 @@ namespace mbts.spark {
#endregion
popup.Child = border;
// set to true for debugging
popup.StaysOpen = false;
popup.PlacementTarget = attach_button;
popup.Placement = PlacementMode.Bottom;
@@ -914,7 +943,6 @@ namespace mbts.spark {
popup.SetBinding(Popup.DataContextProperty, new Binding("PlacementTarget.DataContext") {
RelativeSource = new RelativeSource(RelativeSourceMode.Self)
});
#endregion
#region Detach Button
@@ -970,15 +998,16 @@ namespace mbts.spark {
public override FrameworkElement view_factory() {
var popup = new System.Windows.Controls.Primitives.Popup();
#region Attach Button
#region Update Button
// create the attach button and assign the menu to it
// create the update button and assign the menu to it
var update_button = new Button() {
Name = "update_button",
Content = "···",
Margin = new Thickness(2),
VerticalAlignment = VerticalAlignment.Center,
Focusable = false
Focusable = false,
ToolTip = "Update"
};
update_button.Click += (s, e) => { popup.IsOpen = !popup.IsOpen; };
@@ -995,21 +1024,26 @@ namespace mbts.spark {
row_vm_update_command_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
update_button.SetBinding(Button.CommandProperty, row_vm_update_command_binding);
// update button is only visible for orders under the control of an algo
var update_button_visibility_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookRowVM.root_algo_order_type))) {
Converter = ValueConverter.create<CustomOrderDefinition.CustomOneofCase, Visibility>(ord_type => utilities.OrderDataHelper.outright_order_types.Contains(ord_type) ? Visibility.Hidden : Visibility.Visible)
};
update_button_visibility_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MiniOrderBookRowView), 1);
update_button.SetBinding(Button.VisibilityProperty, update_button_visibility_binding);
#endregion
#region OrderParamsPanel
// finally, set the order_params DataContext to that of the ContextMenu
var order_params = new AlgoEditorGridView {
Margin = new Thickness(6),
CanUserChangeAlgoRoot = false,
};
;
var order_params_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.order_mod_vm)));
order_params_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
order_params.SetBinding(FrameworkElement.DataContextProperty, order_params_binding);
order_params.SetBinding(AlgoEditorGridView.AlgoRootsProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_roots))));
order_params.SetBinding(AlgoEditorGridView.SelectedAlgoRootProperty, new Binding(WPFHelper.join_binding_paths(nameof(OrderParamsVM.algo_vm), nameof(AlgoDefinitionVM.algo_root))));
order_params.SetBinding(AlgoEditorGridView.AlgoParamRowsProperty, new Binding(nameof(OrderParamsVM.param_rows)));
#endregion
#region Dialog Skirt
@@ -1027,6 +1061,7 @@ namespace mbts.spark {
// We take our original ICommand (send_attached) and wrap it in another Command by way of a Converter on the binding,
// pure genious!
var modify_selected_button_binding = new Binding(WPFHelper.join_binding_paths("DataContext", nameof(OrderBookVM.modify_selected_orders_cmd))) {
// set to true for debugging
Converter = CommandWithActionWrapper.mk_wrap_converter(() => popup.IsOpen = false)
};
modify_selected_button_binding.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(Popup), 1);
@@ -1086,8 +1121,9 @@ namespace mbts.spark {
RelativeSource = new RelativeSource(RelativeSourceMode.Self)
});
popup.Closed += (s, e) => {
if (popup.try_find_ancestor_of_type(out MiniOrderBookView mini_ob) && mini_ob.DataContext is OrderBookVM ob_vm)
if (popup.try_find_ancestor_of_type(out MiniOrderBookView mini_ob) && mini_ob.DataContext is OrderBookVM ob_vm) {
ob_vm.is_attaching_orders = false;
}
};
var the_whole_thing = new Grid();
@@ -27,14 +27,16 @@ namespace mbts.spark {
// for mini-ob
uint _prospective_quantity;
double _prospective_price;
Action<bool> _on_selection_changed;
public OrderBookRowVM(OrderBookVM owner, OrderSecurity order_tuple, bool is_expanded) {
public OrderBookRowVM(OrderBookVM owner, OrderSecurity order_tuple, bool is_expanded, Action<bool> on_selection_changed) {
_owner = owner;
this.order_tuple = order_tuple;
is_visible = !is_child;
_is_expanded = is_expanded;
prospective_quantity = this.quantity;
prospective_price = this.price;
_on_selection_changed = on_selection_changed;
}
//// This takes care of the case where the OB has all rows visible
@@ -118,7 +120,11 @@ namespace mbts.spark {
public int depth_level { get => _depth_level; set => Set(ref _depth_level, value); }
public bool is_selected {
get => _is_selected;
set => Set(ref _is_selected, value);
set {
if (Set(ref _is_selected, value)) {
_on_selection_changed(value);
}
}
}
public uint prospective_quantity {
get => _prospective_quantity;
@@ -190,14 +196,18 @@ namespace mbts.spark {
public ICommand attach_command => _attach_command ?? (
_attach_command = new DelegateCommand(() => {
// the _select me will trigger the OBVM.attach_vm to get primed
_select_me();
if (!is_selected) {
_select_me();
}
_owner.begin_attach_algos();
})
);
public ICommand update_command => _update_command ?? (
_update_command = new DelegateCommand(() => {
_select_me();
if (!is_selected) {
_select_me();
}
})
);
@@ -233,12 +243,10 @@ namespace mbts.spark {
private void _unselect_me() {
this.is_selected = false;
_owner.current_row = null;
}
private void _select_me() {
this.is_selected = true;
_owner.current_row = this;
}
// These fns present a way for the orderbook to avoid noisy, intermittent collection changes during "Expand/Collapse All" ops,
@@ -290,6 +298,10 @@ namespace mbts.spark {
// root display name
if (old_order_tuple.root_algo.name != order_tuple.root_algo.name)
RaisePropertyChanged(nameof(root_algo_display_name));
// root order type
if (old_order_tuple.root_algo.value.CustomCase != order_tuple.root_algo.value.CustomCase) {
RaisePropertyChanged(nameof(root_algo_order_type));
}
// status
if ((Columns.Status & dirty) != 0)
RaisePropertyChanged(nameof(status));
@@ -56,13 +56,15 @@ namespace mbts.spark {
bool
_show_right_panel = OrderBookStartupData.Default.show_right_panel,
_is_attaching_orders,
_is_row_collection_populated;
_is_row_collection_populated,
_all_rows_selected;
IReadOnlyDictionary<uint, OrderSecurity> _cached_orders = DictionaryHelper.empty<uint, OrderSecurity>();
IReadOnlyDictionary<uint, bool> _cached_attachable = DictionaryHelper.empty<uint, bool>(), _cached_detachable = DictionaryHelper.empty<uint, bool>();
HashSet<uint>
_attachable_selected_orders = new HashSet<uint>(),
_detachable_selected_orders = new HashSet<uint>();
FilterData _cached_filter_data;
Dictionary<uint, IDisposable> _on_updated_single_callback_gatekeeper = new Dictionary<uint, IDisposable>();
public OrderBookVM(
IObservable<string> owner_title,
@@ -98,7 +100,17 @@ namespace mbts.spark {
// we use an ObservableAppendCollection b/c the mini-ob needs a cancel column at the front
columns = new ObservableAppendCollection<DIYGrid.ColumnBase>(_columns);
_row_collection = new OperableHierarchicalCollection<OrderBookRowVM, OrderSecurity, uint>(
o => new OrderBookRowVM(this, o, rows_are_initially_expanded) {
o => new OrderBookRowVM(this, o, rows_are_initially_expanded, (row_is_selected) => {
// all are selected and one is checked off
if (all_rows_selected && !row_is_selected) {
_all_rows_selected = false;
RaisePropertyChanged(nameof(this.all_rows_selected));
// not all selected and now the last one gets turned on
} else if (!all_rows_selected && _row_collection.All(r => r.is_selected)) {
_all_rows_selected = true;
RaisePropertyChanged(nameof(this.all_rows_selected));
}
}) {
is_attachable = _cached_attachable.TryGetValue(o.order.Key, out bool ia) && ia,
is_detachable = _cached_detachable.TryGetValue(o.order.Key, out bool id)
},
@@ -419,6 +431,13 @@ namespace mbts.spark {
public bool can_attach_selected_orders => _can_attach_selected_orders.Value;
public bool can_detach_selected_orders => _can_detach_selected_orders.Value;
public Plurality security_plurality { get; private set; }
public bool all_rows_selected {
get => _all_rows_selected;
set {
Set(ref _all_rows_selected, value);
_row_collection.ForEach(r => r.is_selected = value);
}
}
public IObservable<bool> subscribe_show_fills() => _show_fills.observe_current(true);
public IObservable<bool> subscribe_show_ladder() => _show_ladder.observe_current(true);
@@ -430,19 +449,43 @@ namespace mbts.spark {
if (e.RemovedItems != null) {
foreach (var row_vm in e.RemovedItems.OfType<OrderBookRowVM>()) {
row_vm.is_selected = false;
_selected_params_mon.on_row_unselected(row_vm);
_selected_params_mon.on_order_unselected(_get_root(row_vm.order_tuple));
_attachable_selected_orders.Remove(row_vm.order_key);
_detachable_selected_orders.Remove(row_vm.order_key);
}
}
if (e.AddedItems != null) {
foreach (var row_vm in e.AddedItems.OfType<OrderBookRowVM>()) {
var root = _get_root(row_vm.order_tuple);
row_vm.is_selected = true;
_selected_params_mon.on_row_selected(row_vm);
if (!_on_updated_single_callback_gatekeeper.ContainsKey(row_vm.order_key)) {
row_vm.updated += on_updated;
_on_updated_single_callback_gatekeeper.Add(row_vm.order_key, Disposable.Create(() => row_vm.updated -= on_updated));
}
_selected_params_mon.on_order_selected(root);
if (row_vm.is_attachable)
_attachable_selected_orders.Add(row_vm.order_key);
if (row_vm.is_detachable)
_detachable_selected_orders.Add(row_vm.order_key);
void on_updated((OrderSecurity oldval, OrderSecurity newval) change) {
if (!row_vm.is_selected) {
// self destruct
if (_on_updated_single_callback_gatekeeper.TryGetValue(row_vm.order_key, out var unsubscribe_updated_disposable)) {
unsubscribe_updated_disposable.Dispose();
_on_updated_single_callback_gatekeeper.Remove(row_vm.order_key);
}
_selected_params_mon.on_order_unselected(_get_root(row_vm.order_tuple));
return;
}
var new_root = _get_root(change.newval);
if (!new_root.Equals(root)) {
// unselect and select in one smooth motion via on_row_updated
// because we thought there may be gremlins afoot when doing
// on_row_unselected and then on_row_selected
_selected_params_mon.on_order_updated((root, new_root));
root = new_root;
}
}
}
}
RowSelectionHelper.apply_changes(selected_rows, e);
@@ -547,15 +590,25 @@ namespace mbts.spark {
public bool try_get_parent(OrderBookRowVM row, out OrderSecurity parent) =>
_cached_orders.TryGetValue(row.parent_order_key, out parent);
public OrderRecordImmutable get_root(OrderRecordImmutable r) {
while (r.ParentKey != 0 && _cached_orders.TryGetValue(r.ParentKey, out var parent_osam)) {
r = parent_osam.order;
}
return r;
OrderBookRowVM _get_root_row(OrderBookRowVM row) {
while (row.parent_order_key != 0 && _row_collection.get_parent(row.parent_order_key) is OrderBookRowVM prow)
row = prow;
return row;
}
internal void detach_orders(OrderBookRowVM order) =>
_detach_orders_async(new[] { order }).ignore();
OrderSecurity _get_root(OrderSecurity os) {
while (os.order.ParentKey != 0 && _cached_orders.TryGetValue(os.order.ParentKey, out var pos))
os = pos;
return os;
}
internal void detach_orders(OrderBookRowVM row) {
if (row.is_selected) {
_detach_orders_async(selected_rows).ignore();
} else {
_detach_orders_async(new[] { row }).ignore();
}
}
public OrderSecurity get_ordersecurityalgometa(OrderRecordImmutable order) {
_cached_orders.TryGetValue(order.Key, out var osam);
@@ -571,8 +624,13 @@ namespace mbts.spark {
internal void show_order_modify(OrderBookRowVM row) =>
_bus.post(SparkTags.ShowModifyOrderTag, row.order_key);
internal void cancel_order(OrderBookRowVM row) =>
_bus.post(SparkTags.CancelOrders, new List<uint> { row.order_key });
internal void cancel_order(OrderBookRowVM row) {
if (row.is_selected) {
_bus.post(SparkTags.CancelOrders, selected_rows.Select(r => r.order_key).ToList());
} else {
_bus.post(SparkTags.CancelOrders, new List<uint> { row.order_key });
}
}
internal void modify_order_quantity(OrderBookRowVM row, uint size) =>
_bus.post(SparkTags.UpdateOrder, (row.order_key, row.price, size));
@@ -611,6 +669,7 @@ namespace mbts.spark {
}
}
// Note: modifications are performed on the selected orders' ROOT orders.
async Task _modify_selected_orders_async() {
double? price = DoubleHelper.nan_nullable(order_mod_vm.price);
uint? size = order_mod_vm.size;
@@ -623,17 +682,17 @@ namespace mbts.spark {
// their values will be cleared (in the param grid gui), and the modifications will not be applied.
// FYI this behavior is implemented to support 'partial edits.' (e.g., changing the 'price' for multiple orders that do not have the same 'size').
// ----
var update_params = selected_rows.Select(update_params_factory).ToList();
var update_params = selected_rows.Select(r => update_params_factory(_get_root(r.order_tuple))).ToList();
await Task.WhenAll(update_params.Select(t => _model.update_order(t.order, new_price: price, new_size: size, new_algo: t.new_algo)));
(OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderBookRowVM row) {
var mod_algo = row.order.Def.CustomDef.CloneToMutable();
(OrderRecordImmutable order, CustomOrderDefinitionImmutable? new_algo) update_params_factory(OrderSecurity order_tuple) {
var mod_algo = order_tuple.order.Def.CustomDef.CloneToMutable();
if (mod_algo.CustomCase == CustomOrderDefinition.CustomOneofCase.Composite) {
mod_algo_vm.assign_to(mod_algo.Composite.Definition);
} else {
mod_algo_vm.assign_to(mod_algo);
}
var mod_algoi = new CustomOrderDefinitionImmutable(mod_algo);
return (row.order, OrderDataHelper.EqualsHelpers.equals(row.order.Def.CustomDef, mod_algoi) ? (CustomOrderDefinitionImmutable?)null : mod_algoi);
return (order_tuple.order, OrderDataHelper.EqualsHelpers.equals(order_tuple.order.Def.CustomDef, mod_algoi) ? (CustomOrderDefinitionImmutable?)null : mod_algoi);
}
} else await Task.WhenAll(selected_rows.Select(r => _model.update_order(r.order, price)));
}
@@ -1006,22 +1065,18 @@ namespace mbts.spark {
public IDisposable begin_udpate() =>
_group_mon.defer_updates();
public void on_row_selected(OrderBookRowVM row) {
_group_mon.add(row.order_tuple);
row.updated += _on_row_updated;
}
public void on_order_selected(OrderSecurity order_tuple) =>
_group_mon.add(order_tuple);
public void on_row_unselected(OrderBookRowVM row) {
_group_mon.remove(row.order_tuple);
row.updated -= _on_row_updated;
}
public void on_order_unselected(OrderSecurity order_tuple) =>
_group_mon.remove(order_tuple);
public void on_security_md_map(IReadOnlyDictionary<uint, SecurityMD> security_md_map) {
_security_md_map = security_md_map;
_security_md_map_changed?.Invoke();
}
void _on_row_updated((OrderSecurity oldval, OrderSecurity newval) ch) {
public void on_order_updated((OrderSecurity oldval, OrderSecurity newval) ch) {
using (begin_udpate()) {
_group_mon.remove(ch.oldval);
_group_mon.add(ch.newval);
@@ -108,4 +108,9 @@
<MouseBinding MouseAction="LeftDoubleClick" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/>
<KeyBinding Key="Return" Command="{x:Static c:DIYGrid.DefaultRowCommand}"/>
</c:DIYGrid.InputBindings>
<c:DIYGrid.RowStyle>
<Style TargetType="ListBoxItem" BasedOn="{StaticResource DIYGridRowStyle}">
<Setter Property="IsSelected" Value="{Binding is_selected, Mode=TwoWay}" />
</Style>
</c:DIYGrid.RowStyle>
</c:DIYGrid>
@@ -50,7 +50,8 @@ namespace mbts.spark {
Update = 1 << 27,
Commit = 1 << 28,
RootAlgoType = 1 << 29,
Piq = 1 << 30
Piq = 1 << 30,
Check = 1 << 31
}
public OrderBookGridView() {
@@ -630,6 +630,13 @@ namespace mbts.spark.utilities {
CustomOrderDefinition.CustomOneofCase.Top,
CustomOrderDefinition.CustomOneofCase.Scratch,
CustomOrderDefinition.CustomOneofCase.Prorata,
},
outright_order_types = new[] {
CustomOrderDefinition.CustomOneofCase.Market,
CustomOrderDefinition.CustomOneofCase.Limit,
CustomOrderDefinition.CustomOneofCase.Stop,
CustomOrderDefinition.CustomOneofCase.StopLimit,
CustomOrderDefinition.CustomOneofCase.GlbxIceberg,
};
public static readonly CustomOrderDefinition.CustomOneofCase[] all_order_types = exchange_order_types.Union(spreader_order_types).ToArray();
@@ -6,19 +6,15 @@ namespace mbts.ui {
// Value = "{mbts:BTSColor X.y}"
// Some colos are also available as static resources in colors.xaml
public static class BTSColors {
// 84 = 255 * 0.33
const byte _one_third_opacity_strength = 84;
static Brush _header_brush, _header_text_brush, _header_alternate_brush, _header_error_text_brush;
static BTSColors() {
_init_brush(header, out _header_brush);
_init_brush(header_text, out _header_text_brush);
_init_brush(header_alternate, out _header_alternate_brush);
_init_brush(header_error_text, out _header_error_text_brush);
}
// freezing brushes makes them thread-safe
static void _init_brush(BTSColor color, out Brush brush) {
brush = color;
brush.Freeze();
_header_brush = header;
_header_text_brush = header_text;
_header_alternate_brush = header_alternate;
_header_error_text_brush = header_error_text;
}
[DisplayInfo(name = "Default Header")]
@@ -72,7 +68,7 @@ namespace mbts.ui {
}
public static class MarketData {
static readonly Brush _bid_brush, _ask_brush;
static readonly Brush _bid_brush, _ask_brush, _semi_transparent_bid_brush, _semi_transparent_ask_brush;
static MarketData() {
// null BTSColors are implicitly gray media colors/brushes (this behavior is problematic and should be changed),
@@ -81,6 +77,8 @@ namespace mbts.ui {
ask = BTSCoreColors.red_darker;
_bid_brush = bid;
_ask_brush = ask;
_semi_transparent_bid_brush = new BTSColor(_one_third_opacity_strength, BTSColors.MarketData.bid);
_semi_transparent_ask_brush = new BTSColor(_one_third_opacity_strength, BTSColors.MarketData.ask);
}
// Base Colors
[DisplayInfo(name = "Market Data")]
@@ -97,6 +95,9 @@ namespace mbts.ui {
public static Brush bid_brush => _bid_brush;
public static Brush ask_brush => _ask_brush;
public static Brush semi_transparent_bid_brush => _semi_transparent_bid_brush;
public static Brush semi_transparent_ask_brush => _semi_transparent_ask_brush;
[DisplayInfo(name = "Settlement")]
public static BTSColor settlement_background { get { return Grid.default_column_background; } }
@@ -165,14 +166,14 @@ namespace mbts.ui {
static Orders() {
_init_brush(_sent, out sent_brush);
_init_brush(filled_dark, out filled_dark_brush);
_init_brush(working_cancel, out working_cancel_brush);
_init_brush(working_order_background, out working_order_background_brush);
_init_brush(completed_order_background, out completed_order_background_brush);
_init_brush(error_order_background, out error_order_background_brush);
_init_brush(canceled_order_background, out canceled_order_background_brush);
_init_brush(modified, out modified_brush);
sent_brush = _sent;
filled_dark_brush = filled_dark;
working_cancel_brush = working_cancel;
working_order_background_brush = working_order_background;
completed_order_background_brush = completed_order_background;
error_order_background_brush = error_order_background;
canceled_order_background_brush = canceled_order_background;
modified_brush = modified;
}
// Base Colors
@@ -13,6 +13,7 @@ namespace mbts.ui.controls {
public double width { get { return column.ActualWidth; } }
public double right { get { return unclipped_left + width; } }
public bool is_partially_obscured { get { return unclipped_left < left; } }
public double visible_width => width - left + unclipped_left;
public override string ToString() {
return "{3} {0:0.0},{1:0.0} w{2:0.0}".fmt(left, right, width, column.Header);
}
@@ -1,40 +0,0 @@
using bts.shell;
using mbts.spark;
using mbts.spark.filters;
using mbts.ui.spark;
using mbts.ui.utility.text;
using System;
using System.Windows.Media;
namespace mbts.ui.controls {
partial class DIYGrid {
internal class TimeAndSalesColumn : RenderTextColumn<TimeAndSalesVM.Row>, IKeyedColumn<TimeAndSalesView.Columns> {
readonly Func<TimeAndSalesVM.Row, Brush> _get_brush;
public TimeAndSalesColumn(TimeAndSalesView.Columns key, Func<TimeAndSalesVM.Row, Brush> get_brush, IDataGridColumnFilter filter = null, string filter_template = null)
: base(r => r[key], filter, filter_template) {
this.key = key;
// id is used for settings (another case of ProtoBufs vs Generics - strings seemed like the easiest way to provide an identifier for the common GridColumnSettings proto)
id = TimeAndSalesWindowFactory.col_id(key);
_get_brush = get_brush;
}
public TimeAndSalesView.Columns key { get; }
public override void draw(TimeAndSalesVM.Row row, DrawingContext dc, ColumnGeometry position, double row_height) {
CellRender.draw_text(dc
, glyph_context
, font_size
, _get_text(row)
, position
, row_height
, font_brush
, _get_brush(row)
, horizontal_alignment
, vertical_alignment
, padding);
}
}
}
}
@@ -21,13 +21,17 @@ namespace mbts.ui.controls {
public class RenderTextColumn<TRowVM> : RenderColumnBase<TRowVM>, IRenderColumn<TRowVM>, IFilterableColumn {
protected readonly Func<TRowVM, string> _get_text;
protected readonly Func<TRowVM, Brush> _get_background_brush;
public RenderTextColumn(
Func<TRowVM, string> get_text,
IDataGridColumnFilter filter = null,
string filter_template = null)
string filter_template = null,
Func<TRowVM, Brush> get_brush = null)
: base() {
_get_text = get_text;
Func<TRowVM, Brush> get_default_background_brush = (TRowVM _) => this.background;
_get_background_brush = get_brush ?? get_default_background_brush;
this.filter = filter;
this.filter_template = filter_template;
font_params_changed += refresh_glyph_context;
@@ -46,13 +50,16 @@ namespace mbts.ui.controls {
public override void draw(TRowVM row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(
dc, glyph_context, font_size, _get_text(row), position, row_height,
font_brush, background, horizontal_alignment, vertical_alignment, padding);
font_brush, _get_background_brush(row), horizontal_alignment, vertical_alignment, padding);
}
public class RenderTextColumn<TRowVM, TColKey> : RenderTextColumn<TRowVM>, IKeyedColumn<TColKey> {
public RenderTextColumn(TColKey key, Func<TRowVM, string> get_text, IDataGridColumnFilter filter, string filter_template)
: base(get_text, filter, filter_template) => this.key = key;
public RenderTextColumn(TColKey key, Func<TRowVM, string> get_text, IDataGridColumnFilter filter, string filter_template, Func<TRowVM, Brush> get_brush)
: base(get_text, filter, filter_template, get_brush) => this.key = key;
public TColKey key { get; }
}
}
@@ -101,7 +101,7 @@ namespace mbts.ui.controls {
protected override void OnRender(DrawingContext dc) {
if (cached_background != null) {
dc.DrawRectangle(cached_background, null, new Rect(0, 0, ActualWidth, ActualHeight));
dc.DrawRectangle(cached_background, null, new Rect(0, 0, _column_layout.Sum(col => col.visible_width), ActualHeight));
}
if (_row != null) {
foreach (var cell in _column_layout) {
@@ -77,7 +77,7 @@
</u:TemplateSelectorKeyValue>
<u:TemplateSelectorKeyValue Key="{x:Static usp:GridSettingsTemplateKeys.Ladder}">
<DataTemplate>
<usp:LadderSettingsView Margin="0,4,0,0"/>
<usp:LadderSettingsView Margin="0,-16,0,0"/>
</DataTemplate>
</u:TemplateSelectorKeyValue>
<u:TemplateSelectorKeyValue Key="{x:Static usp:GridSettingsTemplateKeys.OrderBook}">
+1 -12
View File
@@ -152,9 +152,7 @@ namespace mbts.spark {
add_col(Columns.TotalPNL, DefaultColumnHeaders.TotalPnL, r => r.total_pnl_text, nameof(PnLSummaryRow.total_pnl), DefaultColumnWidths.PnL_Generic, total_pnl_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right, r => r.total_pnl_background);
add_col(Columns.PNLPrice, DefaultColumnHeaders.PnLPrice, r => r.pnl_price_text, nameof(PnLSummaryRow.pnl_price), DefaultColumnWidths.PnL_Generic, pnl_price_filter, DataGridFilterKnownTemplates.DoubleMinMax, HorizontalAlignment.Right);
void add_col(Columns key, string header, Func<PnLSummaryRow, string> get_text, string sort_prop, double width, IDataGridColumnFilter filter, string filter_template, HorizontalAlignment h_align = HorizontalAlignment.Left, Func<PnLSummaryRow, Brush> get_background = null) {
var col = get_background == null ?
new RenderTextColumn<PnLSummaryRow, Columns>(key, get_text, filter, filter_template) :
new PnLDelegateBackgroundColumn(key, get_text, get_background, filter, filter_template);
var col = new RenderTextColumn<PnLSummaryRow, Columns>(key, get_text, filter, filter_template, get_background);
col.Header = header;
col.Width = width;
col.sort_member_path = sort_prop;
@@ -357,14 +355,5 @@ namespace mbts.spark {
DateTime _last_pnl_update_time = DateTime.MinValue;
ObservableCollection<PnLSummaryRow> _pnl_data = new ObservableCollection<PnLSummaryRow>();
class PnLDelegateBackgroundColumn : RenderTextColumn<PnLSummaryRow, Columns> {
readonly Func<PnLSummaryRow, Brush> _get_brush;
public PnLDelegateBackgroundColumn(Columns key, Func<PnLSummaryRow, string> get_text, Func<PnLSummaryRow, Brush> get_brush, IDataGridColumnFilter filter, string filter_template)
: base(key, get_text, filter, filter_template) => _get_brush = get_brush;
public override void draw(PnLSummaryRow row, DrawingContext dc, ColumnGeometry position, double row_height) =>
CellRender.draw_text(dc, glyph_context, font_size, _get_text(row), position, row_height, font_brush, _get_brush.Invoke(row), horizontal_alignment, VerticalAlignment.Center, DefaultCellPadding);
}
}
}
@@ -65,8 +65,12 @@ namespace bts.collections {
return false;
}
public TRow get_parent(TKey key) =>
_tree.TryGetNode(key, out var n) ? n.value : default;
public TRow get_parent(TKey key) {
if (try_get_row(key, out TRow r)) {
return _tree.GetParent(r).value;
}
return default;
}
public IEnumerable<TRow> get_descendent_rows(TKey key) {
if (_tree.TryGetNode(key, out var n)) {
+2 -2
View File
@@ -234,8 +234,8 @@ namespace bts.tests
//create Orders Here
var all = await all_futures(test_symbol);
SecurityImmutable? sec = all.FirstOrDefault();
Assert.IsTrue(sec.HasValue);
SecurityImmutable? sec = all.TryFirst();
Assert.IsTrue(sec.HasValue, "No Futures?");
uint under_limit_order_key;
uint over_limit_order_key;
+163 -4
View File
@@ -76,7 +76,7 @@ namespace bts.tests
);
var spreader_order1_response = await OrderUtilities.send_order(_order_service, order1_def, -0.30, 1);
Assert.IsTrue(spreader_order1_response.success, "Failed to send first spreader order");
Assert.IsTrue(spreader_order1_response.success, "Failed to send spreader order");
var (spreader_order_is_working, working_spreader_order1) = await verify_order_status(spreader_order1_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(spreader_order_is_working, "Spreader order is not Working");
@@ -120,6 +120,156 @@ namespace bts.tests
}
[Test(Timeout = 300000)]
public async Task spreader_lean_qty_factor() {
await setup_spreader_tests();
string test_symbol = "SI";
var test_user = (name: "bts", id: 1u);
var test_account = (name: "ACC A", id: 1u);
(SecurityImmutable s1, SecurityImmutable s2) test_securities = await SpreaderUtilities.get_securities_for_common_setup_one(_md_relay, test_symbol);
var setup_product = await SpreaderUtilities.common_setup_one(_order_service, _synthetic_service, test_securities, test_account, test_user);
var order1_def = OrderDefinitionUtilities.create_spreader_order_def(
setup_product.synthetic.security,
Side.Buy,
setup_product.synthetic.strategy,
test_account,
test_user
);
var spreader_order1_response = await OrderUtilities.send_order(_order_service, order1_def, -0.30, 1);
Assert.IsTrue(spreader_order1_response.success, "Failed to send spreader order");
var (spreader_order_is_working, working_spreader_order1) = await verify_order_status(spreader_order1_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(spreader_order_is_working, "Spreader order is not Working");
var (quoting_order_is_working, working_quoting_order) = await verify_child_order_status(spreader_order1_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(quoting_order_is_working, "Order is not Working");
Assert.IsTrue(working_quoting_order.Value.State.Price == 18.6, "Quoting order has the wrong price");
Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, new List<OrderRecordImmutable> {working_spreader_order1.Value}), "Failed to cancel order");
var (quoting_order_is_canceled, canceled_quoting_order) = await verify_child_order_status(spreader_order1_response.value.OrderKey, OrderStatus.Canceled);
Assert.IsTrue(quoting_order_is_canceled, "Quoting order may not have been canceled");
// change the synthetic
var hedge_leg = setup_product.synthetic.strategy.LegParamsMap.Where(m => !m.Value.IsActiveQuoting).TryFirst();
Assert.IsTrue(hedge_leg.HasValue, "you need more legs");
foreach(var key in setup_product.synthetic.strategy.LegParamsMap.Keys) {
if(!setup_product.synthetic.strategy.LegParamsMap[key].IsActiveQuoting) {
setup_product.synthetic.strategy.LegParamsMap[key].QuoteParams.LeanQuantityRatio = 2d;
break;
}
}
Assert.IsTrue(await SpreaderUtilities.save_strategy(_synthetic_service, setup_product.synthetic.security.Id, (ExecutionStrategyImmutable) setup_product.synthetic.strategy), "Failed to save strategy");
var order2_def = OrderDefinitionUtilities.create_spreader_order_def(
setup_product.synthetic.security,
Side.Buy,
setup_product.synthetic.strategy,
test_account,
test_user
);
var spreader_order2_response = await OrderUtilities.send_order(_order_service, order2_def, -0.30, 1);
Assert.IsTrue(spreader_order2_response.success, "Failed to send spreader order");
var (spreader_order2_is_working, working_spreader_order2) = await verify_order_status(spreader_order2_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(spreader_order2_is_working, "Spreader order is not Working");
var (quoting_order2_is_working, working_quoting_order2) = await verify_child_order_status(spreader_order2_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(quoting_order2_is_working, "Order is not Working");
Assert.IsTrue(working_quoting_order2.Value.State.Price == 18.61, "Quoting order has the wrong price");
Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, new List<OrderRecordImmutable> {working_spreader_order2.Value}), "Failed to cancel order");
var (quoting_order2_is_canceled, canceled_quoting_order2) = await verify_child_order_status(spreader_order2_response.value.OrderKey, OrderStatus.Canceled);
Assert.IsTrue(quoting_order2_is_canceled, "Quoting order may not have been canceled");
// Order 3
foreach(var key in setup_product.synthetic.strategy.LegParamsMap.Keys) {
if(!setup_product.synthetic.strategy.LegParamsMap[key].IsActiveQuoting) {
setup_product.synthetic.strategy.LegParamsMap[key].QuoteParams.LeanQuantityRatio = 4d;
break;
}
}
Assert.IsTrue(await SpreaderUtilities.save_strategy(_synthetic_service, setup_product.synthetic.security.Id, (ExecutionStrategyImmutable) setup_product.synthetic.strategy), "Failed to save strategy");
var order3_def = OrderDefinitionUtilities.create_spreader_order_def(
setup_product.synthetic.security,
Side.Buy,
setup_product.synthetic.strategy,
test_account,
test_user
);
var spreader_order3_response = await OrderUtilities.send_order(_order_service, order3_def, -0.30, 1);
Assert.IsTrue(spreader_order3_response.success, "Failed to send spreader order");
var (spreader_order3_is_working, working_spreader_order3) = await verify_order_status(spreader_order3_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(spreader_order3_is_working, "Spreader order is not Working");
var (quoting_order3_is_working, working_quoting_order3) = await verify_child_order_status(spreader_order3_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(quoting_order3_is_working, "Order is not Working");
Assert.IsTrue(working_quoting_order3.Value.State.Price == 18.63, "Quoting order has the wrong price");
Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, new List<OrderRecordImmutable> {working_spreader_order3.Value}), "Failed to cancel order");
var (quoting_order3_is_canceled, canceled_quoting_order3) = await verify_child_order_status(spreader_order3_response.value.OrderKey, OrderStatus.Canceled);
Assert.IsTrue(quoting_order3_is_canceled, "Quoting order may not have been canceled");
// Order 4
foreach(var key in setup_product.synthetic.strategy.LegParamsMap.Keys) {
if(!setup_product.synthetic.strategy.LegParamsMap[key].IsActiveQuoting) {
setup_product.synthetic.strategy.LegParamsMap[key].QuoteParams.LeanQuantityRatio = 5d;
break;
}
}
Assert.IsTrue(await SpreaderUtilities.save_strategy(_synthetic_service, setup_product.synthetic.security.Id, (ExecutionStrategyImmutable) setup_product.synthetic.strategy), "Failed to save strategy");
var order4_def = OrderDefinitionUtilities.create_spreader_order_def(
setup_product.synthetic.security,
Side.Buy,
setup_product.synthetic.strategy,
test_account,
test_user
);
var spreader_order4_response = await OrderUtilities.send_order(_order_service, order4_def, -0.30, 1);
Assert.IsTrue(spreader_order4_response.success, "Failed to send spreader order");
var (spreader_order4_is_working, working_spreader_order4) = await verify_order_status(spreader_order4_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(spreader_order4_is_working, "Spreader order is not Working");
var no_quoting_order4 = await get_order(ord => ord.ParentKey == spreader_order4_response.value.OrderKey, TimeSpan.FromSeconds(10));
Assert.IsFalse(no_quoting_order4.HasValue, "There should not have been a quoting order here...");
OrderRecordImmutable order_from_book = setup_product.book.Where(ordi => ordi.State.Price == 18.30).First();
var mod_resp = await OrderUtilities.modify_order(_order_service, order_from_book, 2);
Assert.IsTrue(mod_resp.success, "Order size was not changed");
var (quoting_order4_is_working, working_quoting_order4) = await verify_child_order_status(spreader_order4_response.value.OrderKey, OrderStatus.Working);
Assert.IsTrue(quoting_order4_is_working, "Order is not Working");
Assert.IsTrue(working_quoting_order4.Value.State.Price == 18.63, "Quoting order has the wrong price");
var mod_resp2 = await OrderUtilities.modify_order(_order_service, order_from_book, 1);
Assert.IsTrue(mod_resp.success, "Order size was not changed");
var (quoting_order5_is_canceled, canceled_quoting_order5) = await verify_child_order_status(spreader_order4_response.value.OrderKey, OrderStatus.Canceled);
Assert.IsTrue(quoting_order5_is_canceled, "Order was not canceld");
Assert.IsTrue(await OrderUtilities.cancel_orders(_order_service, new List<OrderRecordImmutable> {working_spreader_order4.Value}), "Failed to cancel order");
}
private async Task<(Boolean, OrderRecordImmutable?)> verify_child_order_status(uint parent_order_key, OrderStatus expected_status) {
var order = await get_order(ordi => ordi.ParentKey == parent_order_key && ordi.State.Status == expected_status);
return (order.HasValue && order.Value.State.Status == expected_status, order);
@@ -140,13 +290,22 @@ namespace bts.tests
return order.HasValue && (Math.Truncate(order.Value.State.Price * precision) == precision * expected_price);
}
private async Task<OrderRecordImmutable?> get_order(Func<OrderRecordImmutable, bool> predicate)
private async Task<OrderRecordImmutable?> get_order(Func<OrderRecordImmutable, bool> predicate, TimeSpan? timeout = null)
{
if(timeout == null){
timeout = TimeSpan.FromSeconds(60);
}
var orders = await OrderUtilities.wait_for_filtered_orders(_order_service,
o => o.Where(predicate).Count() > 0,
ord => ord.Where(predicate),
TimeSpan.FromSeconds(30));
return orders.result.TryFirst();
timeout);
if(orders.result != null) {
return orders.result.TryFirst();
}
else {
return null;
}
}
@@ -75,6 +75,10 @@ namespace bts.tests
});
var tr = await tcs.Task.timeout(timeout.Value);
sub.Dispose();
if(tr.result == null) {
Console.WriteLine("Timed out while retreving orders.");
}
return tr;
}
@@ -124,7 +128,7 @@ namespace bts.tests
}
/// <summary>
/// We should replace with something like the OrderDataHeler from the Spark project.
/// We should replace with something like the OrderDataHelper from the Spark project.
/// </summary>
public static class OrderDefinitionUtilities {
@@ -27,8 +27,24 @@ namespace bts.tests
Assert.IsNotNull(exps);
Assert.IsTrue(exps.Count() > 2, "Need at least two expirations");
var exp1 = exps[0];
var exp2 = exps[1];
(uint, uint) preferred_expirations = (07,12);
FutureContract exp1;
FutureContract exp2;
if(exps.Exists(expir => expir.ExpirationMonth == preferred_expirations.Item1)) {
exp1 = exps.Where(ex => ex.ExpirationMonth == preferred_expirations.Item1).First();
}
else {
exp1 = exps[0];
}
if(exps.Exists(expir => expir.ExpirationMonth == preferred_expirations.Item2 && expir.ExpirationYear == exp1.ExpirationYear)) {
exp2 = exps.Where(ex => ex.ExpirationMonth == preferred_expirations.Item2 && ex.ExpirationYear == exp1.ExpirationYear).First();
}
else {
exp2 = exps[1];
}
Func<ChannelUpdate, bool> sec1_match = ch =>
ch.Security.Future.ExpirationYear == exp1.ExpirationYear &&
@@ -103,13 +119,15 @@ namespace bts.tests
new_synth.Synthetic.Legs.Add(legs.Select(l => l.contract));
new_synth.Symbol = deduce_symbol(new_synth);
new_synth.ContractSpec = new ContractSpecification();
new_synth.ContractSpec.LowTick = 0.01;
new_synth.ContractSpec.HighTick = 0.01;
new_synth.ContractSpec.LowTick = 0.005;
new_synth.ContractSpec.HighTick = 0.005;
new_synth.ContractSpec.PriceBreak = double.MaxValue;
new_synth.ContractSpec.MainFraction = 1u;
new_synth.ContractSpec.PriceDisplayFormat = 3u;
new_synth.ContractSpec.CashPerPoint = 1u;
new_synth.ContractSpec.PriceMultiplier = 1u;
new_synth.Exchange = Venue.Bts;
new_synth.Synthetic.Name = "TEST_SYNTH" + DateTime.Now.ToString();
new_synth.Synthetic.Name = "TEST_SYNTH" + DateTime.Now.TimeOfDay.ToString();
var result = await service.create_synthetic_async(new_synth);
Assert.IsTrue(result.success, "Unable to create synthetic");
+21 -1
View File
@@ -131,7 +131,27 @@ namespace bts.tests.utils {
System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
watch.Start();
var odef = OrderDefinitionUtilities.create_limit_order_def(1, Side.Buy, ("bts", 1), ("ACC A", 1));
var ctx = new ServiceContext();
var mdrelay = ctx.locate<bts.co2.MarketDataRelay>();
bts.co2.ProductListReply products = null;
for(int i = 0; i < 10; i++) {
var tmpp = await mdrelay.request_products_async(null);
if( tmpp.value != null) {
Console.WriteLine(i);
products = tmpp.value;
break;
}
}
bts.test.Assert.IsTrue(products != null, "No products found");
var filtered_products = products.Products.Where(z => z.Exchange == Venue.Sim && z.Type == SecurityType.Future);
bts.test.Assert.IsTrue(filtered_products.Count() > 0, "No suitable products found");
var test_security = await MarketDataUtilities.get_security(mdrelay, filtered_products.First().Symbol, SecurityType.Future, f => true);
bts.test.Assert.IsTrue(test_security.HasValue, "No suitable security found");
var odef = OrderDefinitionUtilities.create_limit_order_def(test_security.Value.Id, Side.Buy, ("ACC A", 1), ("bts", 1));
Update<OrderRecordImmutable, uint> service_value = null;
while(service_value == null && watch.Elapsed < timeout) {
@@ -1,10 +1,10 @@
#!/bin/bash
if [ -d ~/sparkdata/ ]
if [ -d /sparkdata/ ]
then
sparkdata_dir=~/sparkdata
else
sparkdata_dir=/sparkdata
else
sparkdata_dir=~/sparkdata
fi
if [ -d "$sparkdata_dir/data" ]
@@ -0,0 +1,52 @@
#!/bin/bash
if [ -d /sparkdata ]
then
sparkdata_dir=/sparkdata
else
sparkdata_dir=~/sparkdata
fi
./delete_dbs.sh
config=$sparkdata_dir/conf/spark.conf
bak=$sparkdata_dir/conf/spark.conf.bak
[ ! -d "$sparkdata_dir/conf" ] && mkdir $sparkdata_dir/conf/
[ -f "$conf" ] && mv $conf $bak
cat << EOF > $sparkdata_dir/conf/spark.conf
ExchangeSim {
value {
merge_with_md:false
}
}
Logging {
value {
console { default_level: "Error" }
syslog { default_level: "Error" }
file { default_level: "Error" }
}
}
SymbolList {
value {
symbol: "SI"
}
}
EOF
nohup ./sparkd run &
pid=$!
echo "sparkd pid: " $pid
dotnet sparkcmd.dll test spreader_lean_qty_factor
exit_status=$?
pkill -P $$
[ -f "$bak" ] && mv $bak $conf
[ $exit_status -eq 0 ] && echo "Test Finished" || echo "Test failed"
exit $exit_status
@@ -1,10 +1,10 @@
#!/bin/bash
if [ -d ~/sparkdata/ ]
if [ -d /sparkdata ]
then
sparkdata_dir=~/sparkdata
else
sparkdata_dir=/sparkdata
else
sparkdata_dir=~/sparkdata
fi
./delete_dbs.sh
@@ -28,7 +28,6 @@ cat << EOF > $sparkdata_dir/conf/spark.conf
file { default_level: "Error" }
}
}
MarketDataConfig { value { use_onixs: false; } }
EOF
@@ -1,10 +1,10 @@
#!/bin/bash
if [ -d ~/sparkdata/ ]
if [ -d /sparkdata/ ]
then
sparkdata_dir=~/sparkdata
else
sparkdata_dir=/sparkdata
else
sparkdata_dir=~/sparkdata
fi
./delete_dbs.sh
@@ -28,7 +28,6 @@ cat << EOF > $sparkdata_dir/conf/spark.conf
file { default_level: "Error" }
}
}
MarketDataConfig { value { use_onixs: false; } }
EOF
nohup ./sparkd run &
@@ -5,11 +5,11 @@
# Stop script if unbound variable found (use ${var:-} if intentional)
set -u
if [ -d ~/sparkdata/ ]
if [ -d /sparkdata/ ]
then
sparkdata_dir=~/sparkdata
else
sparkdata_dir=/sparkdata
else
sparkdata_dir=~/sparkdata
fi
# Use in the the functions: eval $invocation
@@ -130,11 +130,6 @@ ExchangeSim {
merge_with_md: false
}
}
MarketDataConfig {
value {
use_onixs: false;
}
}
END_HEREDOC
)
@@ -1,10 +1,10 @@
#!/bin/bash
if [ -d ~/sparkdata/ ]
if [ -d /sparkdata ]
then
sparkdata_dir=~/sparkdata
else
sparkdata_dir=/sparkdata
else
sparkdata_dir=~/sparkdata
fi
./delete_dbs.sh
@@ -28,7 +28,6 @@ cat << EOF > $sparkdata_dir/conf/spark.conf
file { default_level: "Error" }
}
}
MarketDataConfig { value { use_onixs: false; } }
EOF
+2
View File
@@ -176,6 +176,8 @@ message CoverOrderDefinition {
CustomOrderDefinition hedge = 1;
uint32 hedge_ticks = 2;
CustomOrderDefinition child = 3;
bool cancel_on_external_hedge_cancel = 4;
bool cancel_hedges_on_cancel = 5;
}
message OffsetOrderDefinition {
uint32 tick_offset_on_deploy = 1;
@@ -93,6 +93,12 @@ struct AlgoWrapperOrder::PImpl {
_state.set_avg_price(avg_price.value());
}
void set_ladder_visibility(bool is_visible) {
is_state_dirty = true;
_state.set_display_status(is_visible ? OrderState::VISIBLE
: OrderState::HIDDEN);
}
private:
OrderState _state;
};
@@ -135,9 +141,9 @@ void AlgoWrapperOrder::on_init_new(OrderDefinition const &def,
if (can_consume_attachment(me->definition.custom_def().custom_case())) {
me->attach_target = OrderKey(me->definition.attach_target_order_key());
me->definition.clear_attach_target_order_key();
}
else {
terminate(ORDER_STATUS_REJECTED_BY_SPARK, "Algo does not support attachment");
} else {
terminate(ORDER_STATUS_REJECTED_BY_SPARK,
"Algo does not support attachment");
return;
}
}
@@ -167,7 +173,7 @@ void AlgoWrapperOrder::on_init_recovered(
terminate(ORDER_STATUS_ERROR, "System restarted with active algo order");
return;
// Terminal states
// Terminal states
case ORDER_STATUS_ERROR:
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_COMPLETED:
@@ -175,7 +181,7 @@ void AlgoWrapperOrder::on_init_recovered(
terminate(rec.state().status(), rec.state().last_msg());
break;
// It should not be possible to reach these
// It should not be possible to reach these
case ORDER_STATUS_DISCONNECTED:
case ORDER_STATUS_INACTIVE:
case OrderStatus_INT_MIN_SENTINEL_DO_NOT_USE_:
@@ -290,9 +296,19 @@ orderman::OrderOpResult AlgoWrapperOrder::on_cancel() {
switch (me->status) {
case Status::W_ATTACH:
case Status::WORKING:
terminate(ORDER_STATUS_CANCELED);
break;
case Status::WORKING:
switch (me->algo->on_cancel()) {
case IAlgoOrder::OnCancelResponse::HONOR:
cancel();
break;
case IAlgoOrder::OnCancelResponse::IGNORE:
LOG(OrderMan, Info, "Algo order with key {} ignored cancel request",
key().value());
break;
}
break;
case Status::COMPLETED:
break;
case Status::INACTIVE:
@@ -491,6 +507,14 @@ void AlgoWrapperOrder::update_fill_state(Quantity q, Price p) {
}
}
void AlgoWrapperOrder::set_ladder_visibility(bool is_visible) {
if (!is_working())
return;
ReportStateGuard _(*this);
me->set_ladder_visibility(is_visible);
}
void AlgoWrapperOrder::cancel(std::string const &msg) {
if (!is_working())
return;
@@ -58,7 +58,8 @@ class AlgoWrapperOrder : public Order,
void terminate_error(std::string const &msg) override;
void complete() override;
void update_fill_state(Quantity total_fills, Price last_price) override;
void set_ladder_visibility (bool is_visibile) override;
// Private
struct ReportStateGuard;
struct ChildRecord;
@@ -64,6 +64,14 @@ class IAlgoOrder {
// implementation should validate the update and either apply it,
// if valid or terminate with an error otherwise
virtual void do_update(api::orderman::Update const &) {}
// Override this method to provide custom handling of a cancel
// request. The default behaviour is to cancel both this order and
// recursively any of its children. Algos may override this method
// for example to detach from specific children before canceling or
// to implement custom cleanup behaviour when canceled.
enum class OnCancelResponse {IGNORE, HONOR};
virtual OnCancelResponse on_cancel() {return OnCancelResponse::HONOR;}
};
} // namespace orderman
@@ -80,6 +80,13 @@ class IAlgoServices : public IBeforeLaunchAlgoServices {
// active children.
virtual void complete() = 0;
// --------------------------------------------------------------
// Algo State Update
// --------------------------------------------------------------
// Set wheter this algo instance should be displayed in the Spark UI ladder
virtual void set_ladder_visibility(bool is_visible) = 0;
// Update this algos's filled quantity and last price
virtual void update_fill_state(Quantity total_fills, Price last_price) = 0;
};
@@ -26,6 +26,8 @@ struct CoverAlgo::PImpl {
IAlgoServices *algo;
OrderKey child_key = null_order_key();
Price price_improvement_delta;
bool cancel_on_external_hedge_cancel = false;
bool cancel_hedges_on_cancel = false;
ChildTemplate *child_template = nullptr;
ChildTemplate *hedge_template = nullptr;
Quantity hedged_fills = Quantity(0);
@@ -64,7 +66,7 @@ OrderOpResult CoverAlgo::do_before_launch(IBeforeLaunchAlgoServices &serv) {
}
init_hedge_template(serv, cover.hedge());
set_price_improvement_delta(serv, cover);
update_definition(serv, cover);
return {};
}
@@ -134,16 +136,17 @@ void CoverAlgo::on_child_change(OrderKey k, ChildState const &st) {
switch (st.status) {
case ChildStatus::WORKING:
break;
case ChildStatus::COMPLETED:
if (auto it = std::find(me->hedges.begin(), me->hedges.end(), k);
it != me->hedges.end())
me->hedges.erase(it);
break;
case ChildStatus::CANCELED:
LOG(OrderMan, Info, "CoverAlgo {}. Hedge was canceled, terminating",
algo().order_key().value());
me->status = Status::DONE;
algo().terminate_error("Unexpected child cancel");
if (me->cancel_on_external_hedge_cancel) {
LOG(OrderMan, Info, "CoverAlgo {}. Hedge was canceled, terminating",
algo().order_key().value());
me->status = Status::DONE;
algo().terminate_error("Unexpected child cancel");
} else
std::remove(me->hedges.begin(), me->hedges.end(), k);
break;
case ChildStatus::COMPLETED:
std::remove(me->hedges.begin(), me->hedges.end(), k);
break;
}
}
@@ -167,7 +170,7 @@ void CoverAlgo::do_update(api::orderman::Update const &update) {
// process custom part of the udpate if any
if (update.has_custom()) {
auto &cover_update = update.custom().cover();
set_price_improvement_delta(algo(), cover_update);
update_definition(algo(), cover_update);
if (cover_update.has_child()) {
*child_update.mutable_custom() = cover_update.child();
}
@@ -194,11 +197,14 @@ void orderman::CoverAlgo::init_hedge_template(
me->hedge_template = &(algo.make_child_template(hedge_def));
}
void CoverAlgo::set_price_improvement_delta(
void CoverAlgo::update_definition(
IBeforeLaunchAlgoServices &serv,
api::orderman::CoverOrderDefinition const &cover) {
me->price_improvement_delta = Price(
securities::tick_size(serv.security()).value() * cover.hedge_ticks());
me->cancel_hedges_on_cancel = cover.cancel_hedges_on_cancel();
me->cancel_on_external_hedge_cancel =
cover.cancel_on_external_hedge_cancel();
}
void CoverAlgo::check_terminate() {
@@ -214,5 +220,12 @@ void CoverAlgo::check_terminate() {
}
}
IAlgoOrder::OnCancelResponse CoverAlgo::on_cancel() {
if (!me->cancel_hedges_on_cancel)
for (auto &k : me->hedges)
algo().detach_child(k);
return IAlgoOrder::OnCancelResponse::HONOR;
}
} // namespace orderman
} // namespace bts
@@ -18,6 +18,7 @@ public:
void do_launch_attached(IAlgoServices &, OrderKey, ChildState) override;
void do_update(api::orderman::Update const &) override;
void on_child_change(OrderKey, ChildState const &) override;
IAlgoOrder::OnCancelResponse on_cancel() override;
private:
struct PImpl;
@@ -25,7 +26,7 @@ private:
std::unique_ptr<PImpl> me;
IAlgoServices &algo() const;
void
set_price_improvement_delta(IBeforeLaunchAlgoServices &,
update_definition(IBeforeLaunchAlgoServices &,
api::orderman::CoverOrderDefinition const &);
void init_hedge_template(IBeforeLaunchAlgoServices &,
api::orderman::CustomOrderDefinition const &);
@@ -153,6 +153,7 @@ void JoinAlgo::try_to_join() {
child_update.set_price(my_side_psz.price());
child_update.set_quantity(algo().quantity().value());
algo().update_child(me->child_key, child_update);
algo().set_ladder_visibility(false);
me->status = Status::JOINED;
} else {
LOG(OrderMan, Diag,
@@ -329,8 +329,9 @@ void LeanAlgo::_udpate_out_price_qty(Price price, Quantity qty){
}
bool LeanAlgo::_modify_price_price_qty(Price price, Quantity qty){
if(me->out_price.value()!=price.value() ||
me->out_qty.value()!=qty.value()){
me->out_qty.value()!=qty.value()){
_udpate_out_price_qty(price,qty);
bool first_cross = os::is_nan(me->cross_price.value());
me->cross_price = price;
Update child_update;
child_update.set_price(price.value()),
@@ -340,6 +341,8 @@ bool LeanAlgo::_modify_price_price_qty(Price price, Quantity qty){
algo().order_key().value(),me->child_key,
child_update.price(),child_update.quantity());
algo().update_child(me->child_key, child_update);
if(first_cross)
algo().set_ladder_visibility(false);
return true;
}
return false;
+1
View File
@@ -46,6 +46,7 @@ struct Proxy : public IAlgoServices {
void terminate_error(std::string const &) {}
void complete() {}
void update_fill_state(Quantity , Price ) {}
void set_ladder_visibility(bool) {}
};
int QuickTest::execute(std::vector<std::string> const &) {
@@ -97,7 +97,7 @@ bts::api::orderman::Fill PositionServiceServer::to_fill(bts::api::position::Manu
result.set_last_price(src.price());
result.set_side(src.side());
result.set_last_shares(src.quantity());
result.set_fill_kind(Fill::FILL_KIND_SOD);
result.set_fill_kind(Fill::FILL_KIND_STANDARD);
result.set_fill_key(std::string("manual:")+std::to_string(src.record_id()));
return result;
}
+57
View File
@@ -51,5 +51,62 @@ A(attach)/D(etach) buttons
Verify the limit row's D button has now changed to an A
Verify the limit row is no longer a child to the IB
Verify the IB order is now canceled
Multi-selection specific tests
------------------------------
Prerequisites
Place 10 1-lots at a specific price in the ladder
Have the mini ob open
Cancel
------
Select any 2 rows by however you feel like it - click and drag, ctrl + click, clicking on checkbox column
Note the rows you have chosen, perhaps by time
Click the red cancel icon and the your selected orders should be cancelled
Attach
------
Select any 2 rows
Click the attach icon and then OK to attach to an IB
If you're feeling adventurous, attach to a different Algo
The following should happen to your selected rows:
Update buttons should be visible
The black attach icon should change to the red detach icon
The root algo column should reflect IB (the root algo badge as well)
Detach
------
Select the previously attached rows from our prior attach step
Click the detach icon
The following should happen to your selected rows:
Update buttons should disappear
The red detach icon should change to the black attach icon
The root algo column should reflect a standard Limit(the root algo badge as well)
For extra credit, repeat the detach step here but also include some non-attached rows as well
Update
------
Perform the following WITHOUT closing the mini ob:
Attach an IB with show qty 1 to any 2 rows
Click update (...) button, modify the show quantity to 2, and hit ok
Uncheck one of the selected rows
Hit the update button in the currently selected row and verify the show quantity reads 2, hit cancel
Uncheck your current row, so there should be no rows currently selected
Hit the update button in the *other* row and verify the show quantity reads 2 there as well, now change the show quantity to 3
Uncheck your current row
Hit the update button in the *other* row and verify the show quantity *still* reads 2.
Check both rows and hit the update button
Show quantity should display as '-' signifying that the 2 rows have differing show quantities
Uncheck all rows
Select one of the currently IB-controlled rows and a regular limit order and hit the update button
You should see the param popup effectively display as empty as these are incompatible order types selected
Cancel to return back to mini ob
+5 -5
View File
@@ -128,14 +128,14 @@ Buy a 1 lot at the current bid in ACCA via Trading -> Manual Fills
Click OK to state the fill
Click the Save icon to publish it out
The manual fill will be published as part of the SOD so ACC A should reflect as follows:
The manual fill will be published as part of the Day PnL so ACC A should reflect as follows:
ACC A:
Start Net Pos 0
Start PnL 0.00
Start Net Pos -1 (no change)
Start PnL -37.5
Day Long 0
Day Short 1
Day PnL -37.5
Day Short 0
Day PnL 0
Total Net Pos -1
Total PnL -37.5
PnL Price 14.0125 (displayed as 14.015)
@@ -2,9 +2,9 @@ This test verifies that fractional hedges work. That is, when a fill in a quotin
not equate to one full contract in the hedging leg, we accumulate the unhedged
delta, until we can send one or more hedging contracts.
1. Create a new synthetic spread. For the legs choose SIF9 and SIH9 (if you dont
1. Create a new synthetic spread. For the legs choose SIF9 and SIH9 (if you don't
have these contracts, other contracts can be chosen too) and for the quantities choose 1 and -1.5
respectively (and same for the Price multiplier).
respectively (and same for the Price multiplier).
Enable quoting for SIH9, and disable all quoting, pre-hedge and post-hedge parameters.
Name the synthetic SIF9-1.5SIH9.
@@ -18,13 +18,13 @@ to enter orders). The quoting order will lean against this.
4. Verify that a 15 lot quoting order is sent for SIH9 at 19.935.
5. Now we will start filling the quoting order and verify the hedges. A 1 lot fill in the
quoting leg means a 2/3 contract in the hedging leg. Since we can not send 2/3 constracts,
quoting leg means a 2/3 contract in the hedging leg. Since we can not send 2/3 contracts,
we will add it to the "unhedged delta" till the unhedged delta > 1, and then we will send one
or more orders to get the unhedged delta < 1.
Force quoting fills based on the left most column (by lifting the quoting offer)
and verify that hedge orders of size "hedge_order_sent" (3rd column) are sent as a result.
The "unhedged_delta" column shows the unhedged delta immediatly after the quoting fill
The "unhedged_delta" column shows the unhedged delta immediately after the quoting fill
and the "remaining_unhedged_delta" column is the unhedged delta after the hedge order
has been sent.
You can check the hedge orders being sent easily by looking at the order reduction
@@ -10,7 +10,7 @@ ExchangeSim {
}
}
1. Open up the mview and find a security with with both direct and implied markets, on the ask side.
1. Open up the mview and find a security with with both direct and implied markets, on the ask side.
Make sure those markets are stable and you can rely on them.
2. Create a synthetic with the security in 1. being the hedge leg (buy) and choose a quoting
@@ -19,11 +19,11 @@ use "Merged"
3. Disable all spreader params.
4. Now enter a spreader order so that it doesnt get filled immediatly. Note the quoting order.
4. Now enter a spreader order so that it doesn't get filled immediately. Note the quoting order.
quoting leg price = hedge_price - spreader_price.
hedge_price is where it can buy the hedge order (which since its a buy will be on the ask side of
the hedging market).
Make sure thta its correct and its using the merged book in the hedging market.
Make sure that its correct and its using the merged book in the hedging market.
5. Cancel the order and change the spreader so its using Direct prices.
Repeat 4, and make sure its using direct price on the hedging market.
+3 -3
View File
@@ -5,8 +5,8 @@ with 1 quoting leg.
1. Create a 4 legged synthetic spread with legs SIF9, SIH9, SIK9, SIN9, with leg quantities and
price multipliers of 1,1,1 and -1 respectively. Leg SIN9 is the only quoting leg.
Disable all Quote, Pre-Hedge and Post-Hedge paramaters (leg contracts are arbitrary, so if you
dont have those contracts, choose any set of 4 contracts).
Disable all Quote, Pre-Hedge and Post-Hedge parameters (leg contracts are arbitrary, so if you
don't have those contracts, choose any set of 4 contracts).
2. Enter a synthetic buy order of 10 lots at 40.00. The ladders will most likely be empty, so
use the market view to enter orders.
@@ -16,7 +16,7 @@ Now enter:
SIH9 10 lot sell @ 19.950
SIK9 10 lot sell @ 20.200
There should still be no quoting order for SIN9 since the SIF9 hedge leg still doesnt have a market.
There should still be no quoting order for SIN9 since the SIF9 hedge leg still doesn't have a market.
Now Enter:
SIF9 1 lot sell @ 20.000