Compare commits

...
60 Commits
Author SHA1 Message Date
Eric Harding 6cc1b38358 Update release notes 2018-08-08 17:28:30 -04:00
Eric Harding 0f3169ef05 merge SPARK-1515-OnixS. Updated onixs for CME precision extension 2018-08-08 13:31:41 -04:00
Eric Harding f72753cd77 Onixs debug logging depends on 3 other settings. awesome. 2018-08-08 10:26:59 -04:00
Taha Afzal ea180d8ebc In case of a state of position violation, Limiter lets orders in if they are closing the position 2018-08-06 22:32:26 -04:00
Pedro Pinto 9937fc7cd2 Updated release notes. 2018-08-03 23:15:01 +00:00
Pedro Pinto f3f53d05c8 Fixed spreader order state update. From the middle of the Atlantic.
Go BTS.
2018-08-03 23:13:30 +00:00
Eric Harding b49b7f01d5 Updated linked onixs version. Not sure how we linked with new headers and old version. 2018-08-03 17:31:23 -04:00
Eric Harding a699865342 SPARK-1515 Add specializations to make things build 2018-08-03 16:54:07 -04:00
Michael Harding 1b5f58c572 SparkAdmin: The return of wildcards and other tweaks 2018-08-03 14:16:20 -04:00
Eric Harding bae0b797e9 advance externals pointer for onixs 4.8 2018-08-02 17:15:08 -04:00
Eric Harding 79a69e29a0 SPARK-1515 Switch MDP3Listener to new templates 2018-08-02 16:37:13 -04:00
Pedro Pinto 38bf38c62d Fixed price conversion for spread leg fill. 2018-08-02 20:22:58 +00:00
Jake Norbut 4e08a43d0c Cpp - updating HO to match RB per Kev 2018-08-02 14:12:13 -05:00
Pedro Pinto 4f912f99bd release_notes.txt edited online with Bitbucket 2018-08-01 21:18:45 +00:00
John Colvin ae7e1761a7 SPARK-1527 Production client crash (ListBoxEx) 2018-08-01 17:10:30 -04:00
Jake Norbut 4891eea5ba Merged in SPARK-1166 (pull request #52)
SPARK-1166

Approved-by: John Colvin <john.colvin@bluetradesys.com>
2018-08-01 19:06:39 +00:00
Jake Norbut bc36db0480 TimeAndSales - Replacing 444 with calculations made from the the DefaultColumnWidths 2018-08-01 14:03:42 -05:00
Jake Norbut cdaba74c06 Fixing RB cpp; moving known good cpps to a different file just so that future cpp updates will update this other file and not the main script 2018-07-30 10:21:52 -05:00
Jake Norbut b045307f30 updating SI and HG cpp per Taha 2018-07-27 17:23:23 -05:00
Pedro Pinto 60a7b504db SPARK-1530, Iceberg cancels itself (rather than error) if a child is canceled 2018-07-27 22:04:25 +00:00
Jake Norbut 0f62f14a1d Adding Agressor as a column to TaS as well as setting row bg color/opacity based on agg side 2018-07-27 11:17:52 -05:00
Eric Harding 87030dbb88 SPARK-1199 TradeMessage should include AggressorSide 2018-07-26 10:55:45 -05:00
Jake Norbut e209ec59e4 pnl: changing format string for pnl columns from F2 to N0, which removes cents and adds commas 2018-07-26 10:27:02 -05:00
Jake Norbut 92dbedf28f pnl - FillKind out, Security Type in 2018-07-25 17:36:51 -05:00
Jake Norbut 7993f75fb1 security picker - replacing naive comparison logic with the same Comparer mview uses 2018-07-25 10:07:37 -05:00
Jake Norbut 1cddd2bcf3 fixing typos in comment; fings numb from ac 2018-07-25 09:42:41 -05:00
Eric Harding 9f7e5846b8 Remove linebreak in support request log message so description will show up in slack 2018-07-25 10:42:01 -04:00
Eric Harding f7b3aac11a Reduce web apigateway request/response logging to diag level 2018-07-25 10:39:29 -04:00
Jake Norbut ec32101cef pnl: no longer logging when exchanged traded spread has legs with differing cpps 2018-07-25 09:36:39 -05:00
Jake Norbut 4e0cf68fa3 Pnl - pnl prices should not show in ticks 2018-07-24 09:28:44 -05:00
Jake Norbut 4e9a7d576e Merge branch 'qa' into prod 2018-07-23 19:03:39 -05:00
Jake Norbut 5e056dfff4 pnl - account for current time in calculating start of day time 2018-07-23 17:18:22 -05:00
Jake Norbut 4029ccf8e6 pnl - using actual mid and not a tick-rounded one 2018-07-23 16:06:49 -05:00
Pedro Pinto 22911d582b Merge branch 'qa' of bitbucket.org:bluetradesys/spark into qa 2018-07-23 20:35:30 +00:00
Pedro Pinto 6ef7a2ccb5 More release_notes 2018-07-23 20:32:40 +00:00
Jake Norbut 737a07cecb added notes 2018-07-23 14:57:45 -05:00
Eric Harding 1cbea3d1ee SPARK-1467 Favorites misbehaving 2018-07-23 15:47:12 -04:00
Pedro Pinto 4dbedfa1f7 Added ops_notes.txt 2018-07-23 19:41:09 +00:00
Pedro Pinto 074f87dd37 Release notes 2018-07-23 15:38:16 -04:00
Pedro Pinto 6ee0ca9589 Tweaked release_notes.txt 2018-07-23 14:48:33 -04:00
Michael Harding 5745c13355 Sim Order Routing 2018-07-23 11:22:51 -04:00
Kevin Darby 5f99edde0e small typo in test, 0.005 vs 0.05 2018-07-20 17:45:50 -04:00
Pedro Pinto d39bc5c73c Merge branch 'qa' of bitbucket.org:bluetradesys/spark into qa 2018-07-20 21:40:50 +00:00
Pedro Pinto 9cb6d5ab88 Fixed up tests to reflect lack of wild cards in Admin UI. 2018-07-20 21:40:44 +00:00
Pedro Pinto 278432a35b Fixed bootstraping of admin data to avoid wild cards everywhere. 2018-07-20 21:37:23 +00:00
Kevin Darby 13c414f301 fix small typo in Taha's test 2018-07-20 17:33:39 -04:00
Eric Harding 34f5265a42 Update test instructions 2018-07-20 17:13:37 -04:00
Pedro Pinto 83103e6dc4 Merge branch 'qa' of bitbucket.org:bluetradesys/spark into qa 2018-07-20 12:54:09 -04:00
Pedro Pinto add631b04d Fixed test configuration. 2018-07-20 12:53:56 -04:00
Pedro Pinto e08dc5dfba Add back the option to run sim without replay. 2018-07-20 12:53:34 -04:00
John Colvin 6a8e995c9c SPARK-1452 Synth grid is not filterable by sec key 2018-07-20 11:41:19 -04:00
John Colvin d7c460ac98 SPARK-1440 Creating > 2 legs from MD View 2018-07-20 11:22:20 -04:00
Eric Harding 7871dc5e4f Update 2 tests' instructions 2018-07-19 21:48:52 -04:00
Eric Harding 1aab1db4ca Update cmakedeps 2018-07-19 21:48:44 -04:00
John Colvin 373187c091 SPARK-1464 Couple of small things in the trigger UI 2018-07-19 18:35:06 -04:00
Jake Norbut 423d127ee9 Updating order book order to test new Recreate funcionality 2018-07-19 17:08:43 -05:00
Jake Norbut 14f306d50d SPARK-1471 Adding FillKind to PnL; also will always pass 0 as the time to md query 2018-07-19 16:38:49 -05:00
Eric Harding 71fe863f1b Add server_info http endpoint to serve http://versions 2018-07-19 15:12:39 -04:00
Pedro Pinto ac47f0246f Merge branch 'master' into qa 2018-07-19 18:41:34 +00:00
Kevin Darby 8cef60b5ab top test case, might not have pushed in time 2018-06-18 10:20:44 -04:00
78 changed files with 2635 additions and 6372 deletions

No files matched your search

+6
View File
@@ -0,0 +1,6 @@
1.1.0
- With this release we dropped wild cards from limits, so any user
that has limits expressed in terms of wild cards will have to have
those re-entered explicitly
- With this release we add per user location and smp id tags. At least
the location will have to be set through the admin UI for every user
+27 -4
View File
@@ -1,5 +1,28 @@
1.1.0
1.1.20
- Update CME market data handler for price precision extension.
https://www.cmegroup.com/confluence/display/EPICSANDBOX/Price+Precision+Extension
Added self match protection, location and self match protection
instructions tags, these will have to be set in the UI for the user
for orders to be entered.
1.1.8
- Enabled wild cards in risk management UI
- Fixed spreader order updates
1.1.7
- Fixed spread leg price fill
- Fixed HO cash per point value
1.1.6
- Fixed occasional crash when filtering fills
- Fixed several cash per point multipliers
- Colored time of sales row with aggressor side
- Iceberg orders now cancel (rathern than error) when a child is canceled
1.1.0
- Added per user self match protection, location and self match protection FIX tag settings
- Implemented a new "Trigger Order" algo
- Corrected tick formatting for a number of products
- Added the hability to recreate canceled orders
- Added leg fills to facilitate futured based PnL
- PnL report now has PnL columns calculated based on your start of day, current day, and total position
- Start, Day and Total PnL columns are painted with a red or green background color based on if the pnl value is negative or positive respectively
- Corrected cash per point values, used in pnl calculations, for a number of products
- PnL report will now remember any customizations you make to filtering and/or sorting criteria
@@ -55,7 +55,7 @@ namespace mbts.spark {
})
),
SparkCommands.ShowTimeAndSales.complete(_vm.selected_securities_observable(), _ => true, secs => secs.Count > 0 ? new SecurityCriteria(secs) : _state.security_criteria),
SparkCommands.ShowSyntheticCreate.complete(_vm.selected_securities_observable(), secs => secs.Count > 0 && secs.Count < 3, secs => new SecurityCriteria(secs))
SparkCommands.ShowSyntheticCreate.complete(_vm.selected_securities_observable(), secs => secs.Count > 0 && secs.Count <= 24, secs => new SecurityCriteria(secs))
};
_subscriptions = _bus.subscribe(update_securities_tag).OnDispatcher().Subscribe(c =>
_state_changed?.Invoke(_state = new MarketViewWindowFactory.StartupData(c, _vm.rows_view.GetSortingCriteria(), _vm.get_filter_states())));
@@ -67,4 +67,4 @@ namespace mbts.spark {
Commands.OfType<IDisposable>().DisposeAll();
}
}
}
}
@@ -6,11 +6,14 @@ using mbts.ui.controls;
using mbts.ui.spark;
using mbts.ui.utility;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows.Media;
using static bts.shell.TimeAndSalesWindowFactory;
using static mbts.ui.controls.DIYGrid;
namespace mbts.spark {
class TimeAndSalesVM : SecurityGrid<TimeAndSalesVM.Row, TradeInfo> {
@@ -26,23 +29,32 @@ namespace mbts.spark {
security_filter.load_state(filters.security);
price_filter.load_state(filters.price);
size_filter.load_state(filters.size);
aggressor_filter.load_state(filters.aggressor_sides);
trade_key_filter.load_state(filters.trade_key);
security_key_filter.load_state(filters.security_key);
}
// Columns
add_column(TimeAndSalesView.Columns.Security, "Security", DIYGrid.DefaultColumnWidths.Security, security_filter, DataGridFilterKnownTemplates.Regex);
add_column(TimeAndSalesView.Columns.Time, "Time", DIYGrid.DefaultColumnWidths.Time, time_filter, DataGridFilterKnownTemplates.TimeFilter);
add_column(TimeAndSalesView.Columns.Price, "Price", DIYGrid.DefaultColumnWidths.Price, price_filter, DataGridFilterKnownTemplates.DoubleMinMax);
add_column(TimeAndSalesView.Columns.Size, "Size", DIYGrid.DefaultColumnWidths.Size, size_filter, DataGridFilterKnownTemplates.UIntMinMax);
add_column(TimeAndSalesView.Columns.TradeKey, "Trade Key", DIYGrid.DefaultColumnWidths.TradeKey, trade_key_filter, DataGridFilterKnownTemplates.Regex);
add_column(TimeAndSalesView.Columns.SecurityKey, "Security Key", DIYGrid.DefaultColumnWidths.SecurityKey, security_key_filter, DataGridFilterKnownTemplates.Regex);
void add_column(TimeAndSalesView.Columns col_key, string header, double width, IDataGridColumnFilter filter, string filter_template) =>
columns.Add(new DIYGrid.RenderTextColumn<Row>(r => r[col_key], filter, filter_template) { Header = header, Width = width });
//
add_column(TimeAndSalesView.Columns.Security, DefaultColumnHeaders.Security, DefaultColumnWidths.Security, security_filter, DataGridFilterKnownTemplates.Regex);
add_column(TimeAndSalesView.Columns.Time, DefaultColumnHeaders.Time, DefaultColumnWidths.Time, time_filter, DataGridFilterKnownTemplates.TimeFilter);
add_column(TimeAndSalesView.Columns.Price, DefaultColumnHeaders.Price, DefaultColumnWidths.Price, price_filter, DataGridFilterKnownTemplates.DoubleMinMax, System.Windows.HorizontalAlignment.Right);
add_column(TimeAndSalesView.Columns.Size, DefaultColumnHeaders.Size, DefaultColumnWidths.Size, size_filter, DataGridFilterKnownTemplates.UIntMinMax, System.Windows.HorizontalAlignment.Right);
add_column(TimeAndSalesView.Columns.Aggressor, DefaultColumnHeaders.Aggressor, DIYGrid.DefaultColumnWidths.Aggressor, aggressor_filter, DataGridFilterKnownTemplates.EnumValues);
add_column(TimeAndSalesView.Columns.TradeKey, DefaultColumnHeaders.TradeKey, DIYGrid.DefaultColumnWidths.TradeKey, trade_key_filter, DataGridFilterKnownTemplates.Regex);
add_column(TimeAndSalesView.Columns.SecurityKey, DefaultColumnHeaders.SecurityKey, DIYGrid.DefaultColumnWidths.SecurityKey, security_key_filter, DataGridFilterKnownTemplates.Regex);
void add_column(TimeAndSalesView.Columns col_key, string header, double width, IDataGridColumnFilter filter, string filter_template, System.Windows.HorizontalAlignment h_alignment = System.Windows.HorizontalAlignment.Left) =>
columns.Add(new TimeAndSalesColumn(
r => r[col_key]
, (r) => _get_aggressor_brush(r)
, filter
, filter_template
)
{ Header = header, Width = width, horizontal_alignment = h_alignment }
);
_resources.AddRange(
show_ladder,
DataGridFilterHelper.hook_filters(
rows_view, time_filter, security_filter, price_filter, size_filter, trade_key_filter, security_key_filter
rows_view, time_filter, security_filter, price_filter, size_filter, aggressor_filter, trade_key_filter, security_key_filter
)
);
}
@@ -50,11 +62,22 @@ namespace mbts.spark {
public ObservableCollection<DIYGrid.ColumnBase> columns { get; } = new ObservableCollection<DIYGrid.ColumnBase>();
public DelegateCommandParamObserver<Row> show_ladder { get; }
private Brush _get_aggressor_brush(Row r) {
BTSColor c;
Brush b;
if (r.aggressor_side == AggressorSide.Buy) c = BTSColors.MarketData.bid;
else if (r.aggressor_side == AggressorSide.Sell) c = BTSColors.MarketData.ask;
else c = Brushes.Transparent;
(b = new SolidColorBrush(c) { Opacity = 0.33 }).Freeze();
return b;
}
#region Filters
public IDataGridColumnPersistentFilter<Row, TimeFilterTuple> time_filter { get; } = new TimeFilterVM<Row>(r => r.time, nameof(Row.time));
public IDataGridColumnPersistentFilter<Row, string> security_filter { get; }
public IDataGridColumnPersistentFilter<Row, DoubleMinMaxState> price_filter { get; } = new DoubleMinMax<Row>(r => r.price, nameof(Row.price));
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> size_filter { get; } = new UIntMinMax<Row>(r => r.size, nameof(Row.size));
public IDataGridColumnPersistentFilter<Row, AggressorSide[]> aggressor_filter { get; } = DiscreteValuesFilterVM.Create<Row, AggressorSide>(EnumHelper.get_values<AggressorSide>().ToArray(), r => r.aggressor_side, nameof(Row.aggressor_side));
public IDataGridColumnPersistentFilter<Row, string> security_key_filter { get; } = new RegexFilterVM<Row>(r => r.security_key.ToString(), nameof(Row.security_key));
public IDataGridColumnPersistentFilter<Row, string> trade_key_filter { get; } = new RegexFilterVM<Row>(r => r.trade_key.ToString(), nameof(Row.trade_key));
@@ -65,7 +88,8 @@ namespace mbts.spark {
price = price_filter.get_state(),
size = size_filter.get_state(),
trade_key = trade_key_filter.get_state(),
security_key = security_key_filter.get_state()
security_key = security_key_filter.get_state(),
aggressor_sides = aggressor_filter.get_state()
};
#endregion
@@ -90,6 +114,7 @@ namespace mbts.spark {
_time_text,
_price_text,
_size_text,
_aggressor_text,
_trade_key_text,
_security_key_text;
@@ -98,11 +123,13 @@ namespace mbts.spark {
time = trade.Time.lldatetime();
price = trade.Mantissa * Math.Pow(10, trade.Exponent);
size = trade.Size;
aggressor_side = trade.AggressorSide;
show_ladder = new DelegateCommand(() => parent._show_ladder_async(this).ignore());
_security_text = security.ToString();
_time_text = time.ToString("M/d h:mm:ss tt");
_price_text = security.ContractSpec.format(price);
_size_text = size.ToString();
_aggressor_text = aggressor_side.ToString();
_trade_key_text = _trade_key.ToString();
_security_key_text = security_key.ToString();
}
@@ -113,6 +140,7 @@ namespace mbts.spark {
public DateTime time { get; }
public double price { get; }
public uint size { get; }
public AggressorSide aggressor_side { get; }
public ICommand show_ladder { get; }
public string this[TimeAndSalesView.Columns col] {
@@ -122,6 +150,7 @@ namespace mbts.spark {
case TimeAndSalesView.Columns.Time: return _time_text;
case TimeAndSalesView.Columns.Price: return _price_text;
case TimeAndSalesView.Columns.Size: return _size_text;
case TimeAndSalesView.Columns.Aggressor: return _aggressor_text;
case TimeAndSalesView.Columns.TradeKey: return _trade_key_text;
case TimeAndSalesView.Columns.SecurityKey: return _security_key_text;
default: return null;
@@ -7,7 +7,7 @@ namespace mbts.ui.spark {
/// Interaction logic for TimeAndSalesView.xaml
/// </summary>
partial class TimeAndSalesView : UserControl {
public enum Columns { Time, Security, Price, Size, OrderType, TradeKey, SecurityKey }
public enum Columns { Time, Security, Price, Size, OrderType, TradeKey, SecurityKey, Aggressor }
public TimeAndSalesView() =>
InitializeComponent();
@@ -12,6 +12,7 @@ using System.Reactive.Linq;
using System.Windows;
using System.Windows.Media;
using static bts.shell.TimeAndSalesWindowFactory;
using static mbts.ui.controls.DIYGrid;
namespace mbts.spark {
class TimeAndSalesWindow : SparkWindow<StartupData>, ISlowWindow {
@@ -36,7 +37,16 @@ namespace mbts.spark {
public override string window_type => _window_type;
public override IEnumerable<SparkCommand> Commands => _commands;
public override UIElement Content => _view;
public override double MinWidth => 444 + SPARK_MENU_COLLAPSED_WIDTH + LAUNCHER_BUTTON_BORDER_WIDTH;
public override double MinWidth => DefaultColumnWidths.Security
+ DefaultColumnWidths.Time
+ DefaultColumnWidths.Price
+ DefaultColumnWidths.Size
+ DefaultColumnWidths.Aggressor
+ DefaultColumnWidths.TradeKey
+ DefaultColumnWidths.SecurityKey
+ SPARK_MENU_COLLAPSED_WIDTH
+ LAUNCHER_BUTTON_BORDER_WIDTH;
public override StartupData SaveState => _state = new StartupData(_state.security_criteria, _vm.value.rows_view.GetSortingCriteria(), _vm.value.get_filter_states());
public override void Dispose() =>
@@ -70,6 +70,8 @@ namespace bts.shell {
public string trade_key;
[ProtoMember(6)]
public string security_key;
[ProtoMember(7)]
public co2.AggressorSide[] aggressor_sides;
}
}
}
@@ -72,9 +72,9 @@
c:DataGridFilterProperties.Filter="{Binding DataContext.security_key_filter, Source={u:DirectReference grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.security_key_filter.active, Source={u:DirectReference grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.security_key_filter.open, Source={u:DirectReference grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource IntMinMaxTemplate}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource RegexTemplate}"
/>
</DataGrid.Columns>
</c:DataGridEx>
</Grid>
</UserControl>
</UserControl>
@@ -53,6 +53,8 @@ namespace bts.shell {
public IntMinMaxState n_legs;
[ProtoMember(5)]
public UIntMinMaxState n_working_orders;
[ProtoMember(6)]
public string security_key;
}
}
}
}
@@ -26,8 +26,9 @@ namespace mbts.spark {
description_filter.load_state(filters.description);
n_legs_filter.load_state(filters.n_legs);
n_working_orders_filter.load_state(filters.n_working_orders);
security_key_filter.load_state(filters.security_key);
}
_dispose = DataGridFilterHelper.hook_filters(rows_view, create_time_filter, name_filter, description_filter, n_legs_filter, n_working_orders_filter);
_dispose = DataGridFilterHelper.hook_filters(rows_view, create_time_filter, name_filter, description_filter, n_legs_filter, n_working_orders_filter, security_key_filter);
}
protected override Row row_factory((ExecutionStrategyImmutable? strategy, SecurityMD md) row_model) =>
@@ -41,6 +42,7 @@ namespace mbts.spark {
public IDataGridColumnPersistentFilter<Row, string> description_filter { get; } = new RegexFilterVM<Row>(r => r.description, nameof(Row.description));
public IDataGridColumnPersistentFilter<Row, IntMinMaxState> n_legs_filter { get; } = new IntMinMax<Row>(r => r.n_legs, nameof(Row.n_legs));
public IDataGridColumnPersistentFilter<Row, UIntMinMaxState> n_working_orders_filter { get; } = new UIntMinMax<Row>(r => r.n_working_orders, nameof(Row.n_legs));
public IDataGridColumnPersistentFilter<Row, string> security_key_filter { get; } = new RegexFilterVM<Row>(r => r.security_key.ToString(), nameof(Row.security_key));
public FilterStates get_filter_states() =>
new FilterStates {
@@ -48,7 +50,8 @@ namespace mbts.spark {
create_time = create_time_filter.get_state(),
name = name_filter.get_state(),
n_legs = n_legs_filter.get_state(),
n_working_orders = n_working_orders_filter.get_state()
n_working_orders = n_working_orders_filter.get_state(),
security_key = security_key_filter.get_state()
};
#endregion
@@ -104,4 +107,4 @@ namespace mbts.spark {
});
}
}
}
}
@@ -1,4 +1,5 @@
using bts.api;
using bts.api.orderman;
using bts.spark;
using mbts.spark;
using mbts.spark.filters;
@@ -84,7 +85,10 @@ namespace bts.shell {
[ProtoMember(12)]
public DoubleMinMaxState pnl_price;
// [ProtoMember(13)]
// ProtoMember 13 cannot be used further
[ProtoMember(14)]
public SecurityType[] security_types;
}
}
@@ -21,10 +21,9 @@ namespace mbts.spark {
public ExistingOrderTicketVM(OrdersModel model, IObservable<OrderRecordTuple> order_source, IObservable<int[]> calculator_buttons) {
uint? key = null;
var security_md_source = order_source.Where(ot => ot.security_md.HasValue).Select(ot => ot.security_md.Value);
var security_source = security_md_source.Select(smd => smd.security);
//
_security = backing(nameof(security), security_source, SecurityDataHelper.Defaults.SecurityImmutable);
properties_vm = new OrderPropertiesEditorVM(model, security_source.OnDispatcher(), order_source.Select(ot => new InlineOrderProperties(model, ot.order.Def)));
_security = backing(nameof(security), security_md_source.Select(smd => smd.security), SecurityDataHelper.Defaults.SecurityImmutable);
properties_vm = new OrderPropertiesEditorVM(model, security_md_source, order_source.Select(ot => new InlineOrderProperties(model, ot.order.Def)));
_price = backing(nameof(price), double.NaN);
size_calculator = new CalculatorLogic(null, calculator_buttons);
_current_price = backing(nameof(current_price), order_source.Select(ort => ort.order.State.Price));
+2 -3
View File
@@ -47,9 +47,8 @@ namespace mbts.spark {
IObservable<InlineOrderTicketProperties> props_source,
IObservable<int[]> calculator_buttons
) {
var security_source = security_md_source.Select(smd => smd.security);
_security = backing(nameof(security), security_source, SecurityDataHelper.Defaults.SecurityImmutable);
properties_vm = new OrderPropertiesEditorVM(model, security_source, props_source.Select(p => p.order_props));
_security = backing(nameof(security), security_md_source.Select(smd => smd.security), SecurityDataHelper.Defaults.SecurityImmutable);
properties_vm = new OrderPropertiesEditorVM(model, security_md_source, props_source.Select(p => p.order_props));
bbo = new BBOVM(security_md_source);
send_order = new DelegateCommand<Side>(side => {
bool price_valid = _validate_price(), size_valid = size_calculator.validate();
@@ -8,7 +8,6 @@ using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Reactive.Subjects;
namespace mbts.spark {
class InlineOrderProperties {
@@ -44,8 +43,9 @@ namespace mbts.spark {
readonly SelectorProperty<IOrderTypeVM> _order_type;
IDisposable _order_type_param_errors_sub;
public OrderPropertiesEditorVM(OrdersModel model, IObservable<SecurityImmutable> security_source, IObservable<InlineOrderProperties> order_properties) {
public OrderPropertiesEditorVM(OrdersModel model, IObservable<SecurityMD> security_md_source, IObservable<InlineOrderProperties> order_properties) {
_model = model;
var security_source = security_md_source.Select(smd => smd.security);
_security = backing(nameof(security), security_source.OnDispatcher(), SecurityDataHelper.Defaults.SecurityImmutable);
// guarentee that "this.security" will always be set before observers are notified
// this is important bc some observers will reference "this.security" in their callbacks
@@ -75,7 +75,7 @@ namespace mbts.spark {
_dispose = Disposable.Create(() => _order_type.Changed -= on_selected_order_type_changed);
// local methods
IOrderTypeVM create_order_type_vm(CustomOrderDefinitionImmutable cd) {
var vm = OrderTypeVMFactory.create(cd.CustomCase, model, security_source);
var vm = OrderTypeVMFactory.create(cd.CustomCase, model, security_md_source);
vm.load_from(cd);
return vm;
}
@@ -136,6 +136,7 @@ namespace mbts.spark {
protected override void Dispose(bool disposing) {
base.Dispose(disposing);
Disposable.dispose(ref _order_type_param_errors_sub);
_order_type.items.OfType<IDisposable>().DisposeAll();
}
}
}
@@ -26,7 +26,7 @@ namespace mbts.spark {
}
class IcebergOrderVM : OrderTypeVMBase<IcebergOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable {
readonly IObservable<SecurityImmutable> _security_source;
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
@@ -34,18 +34,18 @@ namespace mbts.spark {
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public IcebergOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source)
: this(model, security_source, security_source.Select(s =>
new InlineIcebergOrderProperties(model.factory.default_order_type(s), model.factory.default_order_types(s).ToList()))) { }
public IcebergOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineIcebergOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList()))) { }
public IcebergOrderVM(OrdersModel model,
IObservable<SecurityImmutable> security_source,
IObservable<SecurityMD> security_md_source,
IObservable<InlineIcebergOrderProperties> inline_properties)
: base(model) {
_security_source = security_source;
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_source.OnDispatcher()
.Subscribe(s => _security = s),
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override) {
@@ -68,7 +68,7 @@ namespace mbts.spark {
public ICollection<IOrderTypeVM> child_order_types {
get {
if (_child_order_choices == null) {
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
}
return _child_order_choices;
}
@@ -53,7 +53,7 @@ namespace mbts.spark
class JoinOrderVM : OrderTypeVMBase<JoinOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityImmutable> _security_source;
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
@@ -79,17 +79,17 @@ namespace mbts.spark
}
public int hedge_ticks { get; set; } = 1;
public JoinOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source)
: this(model, security_source, security_source.Select(s =>
new InlineJoinOrderProperties(model.factory.default_order_type(s), model.factory.default_order_types(s).ToList()))) { }
public JoinOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineJoinOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList()))) { }
public JoinOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source,
public JoinOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineJoinOrderProperties> inline_properties) : base(model)
{
_security_source = security_source;
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_source.OnDispatcher()
.Subscribe(s => _security = s),
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
@@ -157,7 +157,7 @@ namespace mbts.spark
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _child_order_choices;
}
}
@@ -167,7 +167,7 @@ namespace mbts.spark
get
{
if (_hedge_order_choices == null)
_hedge_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_hedge_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _hedge_order_choices;
}
}
@@ -35,7 +35,7 @@ namespace mbts.spark
class LeanOrderVM : OrderTypeVMBase<LeanOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityImmutable> _security_source;
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
@@ -46,17 +46,17 @@ namespace mbts.spark
public bts.spark.QuantityMeasure cross_threshold { get; set; } = new bts.spark.QuantityMeasure() { Ratio = 1.0, Absolute = 1 };
public uint max_chase_ticks { get; set; } = 10;
public LeanOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source)
: this(model, security_source, security_source.Select(s =>
new InlineLeanOrderProperties(model.factory.default_order_type(s), model.factory.default_order_types(s).ToList()))) { }
public LeanOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineLeanOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList()))) { }
public LeanOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source,
public LeanOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineLeanOrderProperties> inline_properties) : base(model)
{
_security_source = security_source;
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_source.OnDispatcher()
.Subscribe(s => _security = s),
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
@@ -104,7 +104,7 @@ namespace mbts.spark
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _child_order_choices;
}
}
@@ -4,6 +4,7 @@ using bts.spark;
using mbts.spark.utilities;
using mbts.ui.shell;
using System;
using System.Reactive.Linq;
using System.Windows.Input;
using static bts.api.orderman.CustomOrderDefinition;
@@ -12,33 +13,30 @@ namespace mbts.spark {
public static IOrderTypeVM market(OrdersModel model) => new MarketOrderVM(model);
public static IOrderTypeVM limit(OrdersModel model) => new LimitOrderVM(model);
public static IOrderTypeVM stop(OrdersModel model) => new StopOrderVM(model);
public static IOrderTypeVM stop_limit(OrdersModel model) => new StopLimitOrderVM(model);
public static IOrderTypeVM time_box(OrdersModel model, IObservable<SecurityImmutable> security_source) => new TimeBoxOrderVM(model, security_source);
public static IOrderTypeVM tick(OrdersModel model, IObservable<SecurityImmutable> security_source) => new TickOrderVM(model, security_source);
public static IOrderTypeVM lean(OrdersModel model, IObservable<SecurityImmutable> security_source) => new LeanOrderVM(model, security_source);
public static IOrderTypeVM join(OrdersModel model, IObservable<SecurityImmutable> security_source) => new JoinOrderVM(model, security_source);
public static IOrderTypeVM top(OrdersModel model, IObservable<SecurityImmutable> security_source) => new TopOrderVM(model, security_source);
public static IOrderTypeVM trigger(OrdersModel model, IObservable<SecurityImmutable> security_source) => new TriggerOrderVM(model, security_source);
public static IOrderTypeVM iceberg(OrdersModel model, IObservable<SecurityImmutable> security_source) => new IcebergOrderVM(model, security_source);
public static IOrderTypeVM stop_limit(OrdersModel model, IObservable<SecurityMD> security_md_source) => new StopLimitOrderVM(model, security_md_source);
public static IOrderTypeVM time_box(OrdersModel model, IObservable<SecurityMD> security_md_source) => new TimeBoxOrderVM(model, security_md_source);
public static IOrderTypeVM tick(OrdersModel model, IObservable<SecurityMD> security_md_source) => new TickOrderVM(model, security_md_source);
public static IOrderTypeVM lean(OrdersModel model, IObservable<SecurityMD> security_md_source) => new LeanOrderVM(model, security_md_source);
public static IOrderTypeVM join(OrdersModel model, IObservable<SecurityMD> security_md_source) => new JoinOrderVM(model, security_md_source);
public static IOrderTypeVM top(OrdersModel model, IObservable<SecurityMD> security_md_source) => new TopOrderVM(model, security_md_source);
public static IOrderTypeVM trigger(OrdersModel model, IObservable<SecurityMD> security_md_source) => new TriggerOrderVM(model, security_md_source);
public static IOrderTypeVM iceberg(OrdersModel model, IObservable<SecurityMD> security_md_source) => new IcebergOrderVM(model, security_md_source);
public static IOrderTypeVM spreader(OrdersModel model, IObservable<SecurityImmutable> security_source) => new SpreaderOrderVM(model, security_source);
static Func<CustomOneofCase, IOrderTypeVM> _get_factory(OrdersModel orders_model, IObservable<SecurityImmutable> security_source) =>
new Func<CustomOneofCase, IOrderTypeVM>(ot => create(ot, orders_model, security_source));
public static IOrderTypeVM create(CustomOneofCase order_type, OrdersModel model, IObservable<SecurityImmutable> security_source) {
public static IOrderTypeVM create(CustomOneofCase order_type, OrdersModel model, IObservable<SecurityMD> security_md_source) {
switch (order_type) {
case CustomOneofCase.Market: return market(model);
case CustomOneofCase.Limit: return limit(model);
case CustomOneofCase.Stop: return stop(model);
case CustomOneofCase.StopLimit: return stop_limit(model);
case CustomOneofCase.TimeBox: return time_box(model, security_source);
case CustomOneofCase.Tick: return tick(model, security_source);
case CustomOneofCase.Lean: return lean(model, security_source);
case CustomOneofCase.Join: return join(model, security_source);
case CustomOneofCase.Top: return top(model, security_source);
case CustomOneofCase.Trigger: return trigger(model, security_source);
case CustomOneofCase.Iceberg: return iceberg(model, security_source);
case CustomOneofCase.Spreader: return spreader(model, security_source);
case CustomOneofCase.StopLimit: return stop_limit(model, security_md_source);
case CustomOneofCase.TimeBox: return time_box(model, security_md_source);
case CustomOneofCase.Tick: return tick(model, security_md_source);
case CustomOneofCase.Lean: return lean(model, security_md_source);
case CustomOneofCase.Join: return join(model, security_md_source);
case CustomOneofCase.Top: return top(model, security_md_source);
case CustomOneofCase.Trigger: return trigger(model, security_md_source);
case CustomOneofCase.Iceberg: return iceberg(model, security_md_source);
case CustomOneofCase.Spreader: return spreader(model, security_md_source.Select(smd => smd.security));
default: throw new NotImplementedException();
}
}
@@ -1,18 +1,61 @@
using bts.api;
using bts.api.orderman;
using mbts.spark.utilities;
using mbts.utils;
using mbts.co2;
using mbts.ui;
using System;
using System.Reactive.Linq;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
private class StopLimitOrderVM : OrderTypeVMBase<StopLimitOrderDefinition> {
double _stop_price = 0;
class InlineStopLimitOrderProperties {
readonly Func<InlineUserProperty<double>> _get_stop_price;
internal StopLimitOrderVM(OrdersModel model) : base(model) { }
public static IObservable<InlineStopLimitOrderProperties> subscribe(IObservable<SecurityMD> security_md_source) {
ulong time = 0;
return security_md_source.Select(smd => new InlineStopLimitOrderProperties(() => {
smd.md.get_bbo(ref time, out NativePriceSize bid, out NativePriceSize ask);
return new InlineUserProperty<double>(bid.price);
}));
}
public InlineStopLimitOrderProperties(Func<InlineUserProperty<double>> get_stop_price) =>
_get_stop_price = get_stop_price;
public InlineUserProperty<double> stop_price => _get_stop_price();
}
private class StopLimitOrderVM : OrderTypeVMBase<StopLimitOrderDefinition>, IDisposable {
UserProperty<double> _stop_price;
InlineStopLimitOrderProperties _inline_props;
IDisposable _dispose;
internal StopLimitOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source.Select(smd => smd.security.spec_or_default()), InlineStopLimitOrderProperties.subscribe(security_md_source)) { }
internal StopLimitOrderVM(OrdersModel model, IObservable<ContractSpecificationImmutable> spec_source, IObservable<InlineStopLimitOrderProperties> inline_properties) : base(model) {
_stop_price = new UserProperty<double>(backing(nameof(stop_price), double.NaN));
_dispose = Disposable.Create(
spec_source.OnDispatcher().Subscribe(s => {
spec = s;
RaisePropertyChanged(nameof(spec));
}), inline_properties.OnDispatcher().Subscribe(p => _inline_props = p));
}
public override bool editable_properties_open {
get => base.editable_properties_open;
set {
if (value) {
if (_update_inline_props())
_validate();
}
base.editable_properties_open = value;
}
}
public double stop_price {
get => _stop_price;
get => _stop_price.Value;
set {
_stop_price = value;
_stop_price.Value = value;
_validate();
}
}
@@ -21,6 +64,8 @@ namespace mbts.spark {
SecurityDataHelper.Defaults.ContractSpecificationImmutable;
public override void assign_to(CustomOrderDefinition value) {
_update_inline_props();
_validate();
if (!HasErrors) {
var sl = factory.stop_limit_order();
sl.StopPrice = stop_price;
@@ -28,9 +73,22 @@ namespace mbts.spark {
}
}
public void Dispose() => Disposable.dispose(ref _dispose);
// no need to constantly poll the md, just check the inline props when the popup opens, and right before sending an order
// (if the user never looks at the popup, assume that the bid_price will be used)
// TODO: add settings so the trigger-price can default to something relative to the md, e.g "bid-price" or "ask-price - nticks" or "best-bid-price with a minimum size of 10"
bool _update_inline_props() {
var inline_stop_price = _inline_props.stop_price;
if (inline_stop_price.has_value && (inline_stop_price.force_override || !_stop_price.setter_called)) {
_stop_price.bypass_setter(inline_stop_price.value);
return true;
} else return false;
}
void _validate() {
using (validation())
validation_assert(!DoubleHelper.IsNaNOrInfinity(_stop_price), string.Empty, nameof(stop_price));
validation_assert(!DoubleHelper.IsNaNOrInfinity(stop_price), string.Empty, nameof(stop_price));
}
}
}
@@ -41,7 +41,7 @@ namespace mbts.spark
class TickOrderVM : OrderTypeVMBase<TickOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityImmutable> _security_source;
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
@@ -55,17 +55,17 @@ namespace mbts.spark
public uint max_chase_ticks { get; set; } = 10;
public bool detach_on_toward { get; set; } = true;
public TickOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source)
: this(model, security_source, security_source.Select(s =>
new InlineTickOrderProperties(model.factory.default_order_type(s), model.factory.default_order_types(s).ToList()))) { }
public TickOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineTickOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList()))) { }
public TickOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source,
public TickOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineTickOrderProperties> inline_properties) : base(model)
{
_security_source = security_source;
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_source.OnDispatcher()
.Subscribe(s => _security = s),
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
@@ -131,7 +131,7 @@ namespace mbts.spark
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _child_order_choices;
}
}
@@ -28,7 +28,7 @@ namespace mbts.spark {
class TimeBoxOrderVM : OrderTypeVMBase<TimeBoxOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable {
const double _start_immediately_delay_ms = 500;
readonly IObservable<SecurityImmutable> _security_source;
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
@@ -40,18 +40,18 @@ namespace mbts.spark {
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public TimeBoxOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source)
: this(model, security_source, security_source.Select(s =>
new InlineTimeBoxOrderProperties(model.factory.default_order_type(s), model.factory.default_order_types(s).ToList()))) { }
public TimeBoxOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineTimeBoxOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList()))) { }
public TimeBoxOrderVM(OrdersModel model,
IObservable<SecurityImmutable> security_source,
IObservable<SecurityMD> security_md_source,
IObservable<InlineTimeBoxOrderProperties> inline_properties)
: base(model) {
_security_source = security_source;
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_source.OnDispatcher()
.Subscribe(s => _security = s),
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override) {
@@ -94,7 +94,7 @@ namespace mbts.spark {
public ICollection<IOrderTypeVM> child_order_types {
get {
if (_child_order_choices == null) {
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
}
return _child_order_choices;
}
@@ -51,7 +51,7 @@ namespace mbts.spark
class TopOrderVM : OrderTypeVMBase<TopOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityImmutable> _security_source;
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
@@ -77,18 +77,18 @@ namespace mbts.spark
}
public int hedge_ticks { get; set; } = 1;
public TopOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source)
: this(model, security_source, security_source.Select(s =>
new InlineTopOrderProperties(model.factory.default_order_type(s), model.factory.default_order_types(s).ToList())))
public TopOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineTopOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList())))
{ }
public TopOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source,
public TopOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineTopOrderProperties> inline_properties) : base(model)
{
_security_source = security_source;
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_source.OnDispatcher()
.Subscribe(s => _security = s),
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p =>
{
@@ -157,7 +157,7 @@ namespace mbts.spark
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _child_order_choices;
}
}
@@ -167,7 +167,7 @@ namespace mbts.spark
get
{
if (_hedge_order_choices == null)
_hedge_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_hedge_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _hedge_order_choices;
}
}
@@ -35,7 +35,7 @@ namespace mbts.spark
class TriggerOrderVM : OrderTypeVMBase<TriggerOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityImmutable> _security_source;
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
@@ -46,17 +46,17 @@ namespace mbts.spark
public TriggerPriceType trigger_price_type { get; set; } = TriggerPriceType.Bid;
public double order_price { get; set; } = double.NaN;
public TriggerOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source)
: this(model, security_source, security_source.Select(s =>
new InlineTriggerOrderProperties(model.factory.default_order_type(s), model.factory.default_order_types(s).ToList()))) { }
public TriggerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineTriggerOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList()))) { }
public TriggerOrderVM(OrdersModel model, IObservable<SecurityImmutable> security_source,
public TriggerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineTriggerOrderProperties> inline_properties) : base(model)
{
_security_source = security_source;
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_source.OnDispatcher()
.Subscribe(s => _security = s),
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
@@ -124,7 +124,7 @@ namespace mbts.spark
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_source));
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _child_order_choices;
}
}
@@ -22,7 +22,8 @@ namespace mbts.ui.controls {
Time = 100,
TimeInForce = 47,
TradeKey = 76,
User = 53;
User = 53,
Aggressor = 80;
}
public static class DefaultColumnHeaders {
@@ -40,7 +41,9 @@ namespace mbts.ui.controls {
Size = "Qty",
TimeInForce = "TIF",
TradeKey = "Trade Key",
User = "User";
User = "User",
Time = "Time",
Aggressor = "Aggressor";
}
internal interface IKeyedColumn<TColKey> {
@@ -0,0 +1,36 @@
using mbts.spark;
using mbts.spark.filters;
using mbts.ui.utility.text;
using System;
using System.Windows;
using System.Windows.Media;
namespace mbts.ui.controls {
public partial class DIYGrid {
internal class TimeAndSalesColumn : RenderTextColumn<TimeAndSalesVM.Row> {
readonly Func<TimeAndSalesVM.Row, string> _get_text;
readonly Func<TimeAndSalesVM.Row, Brush> _get_brush;
public TimeAndSalesColumn(Func<TimeAndSalesVM.Row, string> get_text, Func<TimeAndSalesVM.Row, Brush> get_brush, IDataGridColumnFilter filter = null, string filter_template = null, GlyphContext glyph_context = null) : base(get_text, filter, filter_template, glyph_context) {
_get_text = get_text;
_get_brush = get_brush;
}
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
, foreground
, _get_brush(row)
, horizontal_alignment
, vertical_alignment
, padding);
}
}
}
}
@@ -190,17 +190,21 @@ namespace mbts.ui.controls
}
}
void item_Unselected(object sender, RoutedEventArgs e) {
if (_selection_changing) return;
var item = ((ListBoxItem)sender).DataContext;
var selected_items = Selection;
if (selected_items.Contains(item)) {
using (_selection_change()) {
selected_items.Remove(item);
_update_is_all_selected();
}
}
}
void item_Unselected(object sender, RoutedEventArgs e) {
if (!_selection_changing && sender is ListBoxItem container) {
// the [ListBoxItem] sender may be "Disconnected" https://stackoverflow.com/questions/14282894/wpf-listbox-virtualization-creates-disconnecteditems/14358688
var item = ItemContainerGenerator.ItemFromContainer(container);
if (item != DependencyProperty.UnsetValue) {
var selected_items = Selection;
if (selected_items.Contains(item)) {
using (_selection_change()) {
selected_items.Remove(item);
_update_is_all_selected();
}
}
}
}
}
void item_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) {
using (_selection_change()) ((ListBoxItem)sender).IsSelected = Selection.Contains(e.NewValue);
@@ -368,4 +372,4 @@ namespace mbts.ui.controls
}
}
}
}
}
@@ -93,7 +93,9 @@ namespace mbts.ui.shell
_recently_closed_windows.Push(() => { undoaction(); });
}
}
_bookmark.save_bookmark(document.Model);
if (document.HasCustomTitle) {
_bookmark.save_bookmark(document.Model);
}
}
public void remove_document(TabDocument document) {
@@ -376,7 +376,7 @@ namespace mbts.spark
return x is SecurityImmutable && y is SecurityImmutable ? Compare((SecurityImmutable)x, (SecurityImmutable)y) : -1;
}
public int Compare(SecurityImmutable x, SecurityImmutable y) {
return x.EarliestExpiration().CompareTo(y.EarliestExpiration());
return SecurityHelper.Comparer.Compare(x, y);
}
@@ -1,5 +1,4 @@
using bts.api;
using bts.api.orderman;
using mbts.co2;
using System.Threading.Tasks;
@@ -8,15 +7,15 @@ namespace mbts.spark {
readonly OrdersModel _order_gateway;
public LadderModel(SecurityMD source, OrdersModel ordergw) {
security = source.security;
md = source.md;
security_md = source;
_order_gateway = ordergw;
}
public enum CancelType { All, Bids, Asks }
public SecurityImmutable security { get; }
public MDConsumerHandle md { get; }
public SecurityMD security_md { get; }
public SecurityImmutable security => security_md.security;
public MDConsumerHandle md => security_md.md;
public OrdersModel order_gateway => _order_gateway;
public Task cancel_orders(CancelType ct) {
@@ -71,7 +71,7 @@ namespace mbts.spark {
_dispose = Disposable.Create(
settings_command,
order_properties_vm = new OrderPropertiesEditorVM(model.order_gateway, Observable.Return(security), _settings_manager.subscribe_current().Select(s => new InlineOrderProperties(model.order_gateway, s))),
order_properties_vm = new OrderPropertiesEditorVM(model.order_gateway, Observable.Return(model.security_md), _settings_manager.subscribe_current().Select(s => new InlineOrderProperties(model.order_gateway, s))),
size_calculator = new CalculatorLogic(0, _settings_manager.subscribe_current().Select(s => s.calculator_buttons)),
bus.subscribe(SparkTags.LogActivity).OnDispatcher().Subscribe(status_update),
model.order_gateway.working_orders.OnDispatcher().Subscribe(working => {
+7 -2
View File
@@ -11,6 +11,7 @@ using System.Linq;
using System.Reactive.Linq;
using System.Windows.Data;
using static bts.shell.PAndLWindowFactory;
using static bts.api.orderman.Fill.Types;
namespace mbts.spark {
class PAndLVM : DisposableViewModelBase {
@@ -58,6 +59,7 @@ namespace mbts.spark {
total_net_position_filter.load_state(fs.total_net_pos);
total_pnl_filter.load_state(fs.total_pnl);
pnl_price_filter.load_state(fs.pnl_price);
security_type_filter.load_state(fs.security_types);
}
// restore sort state or supply default value
if (startup_data?.sort_criteria?.Any() == true) {
@@ -89,7 +91,8 @@ namespace mbts.spark {
total_pnl_filter,
pnl_price_filter,
weighted_average_buy_filter,
weighted_average_sell_filter),
weighted_average_sell_filter,
security_type_filter),
WorkLoop.Start("PAndL", _UPDATE_PERIOD, _calculate_pnl)
);
}
@@ -194,6 +197,7 @@ namespace mbts.spark {
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> pnl_price_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.pnl_price, nameof(PnLSummaryRow.pnl_price));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> weighted_average_buy_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.weighted_average_buy, nameof(PnLSummaryRow.weighted_average_buy));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> weighted_average_sell_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.weighted_average_sell, nameof(PnLSummaryRow.weighted_average_sell));
public IDataGridColumnPersistentFilter<PnLSummaryRow, SecurityType[]> security_type_filter { get; } = DiscreteValuesFilterVM.Create<PnLSummaryRow, SecurityType>(EnumHelper.get_values_except<SecurityType>(SecurityType.Option, SecurityType.Stock, SecurityType.Synthetic).ToArray(), r => r.security_type, nameof(PnLSummaryRow.security_type));
public FilterStates get_filters_states() => new FilterStates {
account_regex = account_filter.get_state(),
@@ -207,7 +211,8 @@ namespace mbts.spark {
day_pnl = day_pnl_filter.get_state(),
total_net_pos = total_net_position_filter.get_state(),
total_pnl = total_pnl_filter.get_state(),
pnl_price = pnl_price_filter.get_state()
pnl_price = pnl_price_filter.get_state(),
security_types = security_type_filter.get_state()
};
#endregion
@@ -19,7 +19,7 @@
<Setter Property="TextAlignment" Value="Right" />
</Style>
<convert:NumericSignBrushConverter x:Key="PnLBackgroundColorConverter" Opacity="0.33"/>
<convert:DoubleTextConverter x:Key="DoubleWithNaNHiddenConverter" Format="F2" />
<convert:DoubleTextConverter x:Key="DoubleWithNaNHiddenConverter" Format="N0" />
</ResourceDictionary>
</UserControl.Resources>
<Grid>
@@ -64,6 +64,12 @@
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.security_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource RegexTemplate}"
/>
<DataGridTextColumn x:Name="security_type" Header="Security Type" Binding="{Binding security_type}" IsReadOnly="true"
c:DataGridFilterProperties.Filter="{Binding DataContext.security_type_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.security_type_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.security_type_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DiscreteValuesTemplate}"
/>
<DataGridTextColumn x:Name="start_net_pos" Header="Start Net Pos" Binding="{Binding start_net_position}" IsReadOnly="true"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.start_position_filter, Source={uc:DirectReference _grid}}"
@@ -72,16 +78,11 @@
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="start_pnl" Header="Start PnL" IsReadOnly="true" SortMemberPath="start_pnl"
Binding="{Binding start_pnl, Converter={StaticResource DoubleWithNaNHiddenConverter}}"
c:DataGridFilterProperties.Filter="{Binding DataContext.start_pnl_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.start_pnl_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.start_pnl_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="start_pnl"/>
<Binding Path="security"/>
</MultiBinding>
</DataGridTextColumn.Binding>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextAlignment" Value="Right" />
@@ -104,16 +105,11 @@
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="day_pnl" Header="Day PnL" IsReadOnly="true" SortMemberPath="day_pnl"
Binding="{Binding day_pnl, Converter={StaticResource DoubleWithNaNHiddenConverter}}"
c:DataGridFilterProperties.Filter="{Binding DataContext.day_pnl_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.day_pnl_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.day_pnl_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="day_pnl"/>
<Binding Path="security"/>
</MultiBinding>
</DataGridTextColumn.Binding>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextAlignment" Value="Right" />
@@ -129,16 +125,11 @@
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="total_pnl" Header="Total PnL" IsReadOnly="true" SortMemberPath="total_pnl"
Binding="{Binding total_pnl, Converter={StaticResource DoubleWithNaNHiddenConverter}}"
c:DataGridFilterProperties.Filter="{Binding DataContext.total_pnl_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.total_pnl_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.total_pnl_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="total_pnl"/>
<Binding Path="security"/>
</MultiBinding>
</DataGridTextColumn.Binding>
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextAlignment" Value="Right" />
@@ -86,12 +86,16 @@ namespace mbts.spark {
// Note that this isn't the acutal start of the trading day
// but it's close enough for pnl purposes.
// In reality, instruments have different schedules
_start_of_trading_day_utc = DateTime.Now.Date.Add(start_of_day_ts).AddDays(-1).ToUniversalTime();
var _start_of_trading_day_local = DateTime.Now.Date.Add(start_of_day_ts);
if (_start_of_trading_day_local >= DateTime.Now) {
_start_of_trading_day_local = _start_of_trading_day_local.AddDays(-1);
}
_start_of_trading_day_utc = _start_of_trading_day_local.ToUniversalTime();
}
public IEnumerable<PnLSummaryRow> get_summary_position() {
return (from pnl_item in _data
group pnl_item by (pnl_item.account, pnl_item.exchange, pnl_item.symbol, pnl_item.security, pnl_item.sec_md) into grouping
group pnl_item by (pnl_item.account, pnl_item.exchange, pnl_item.symbol, pnl_item.security, pnl_item.sec_md, pnl_item.security_type) into grouping
/* let start_of_day = _get_start_of_day(grouping.Key.symbol) */
select new PnLSummaryRow(_calc_type, _start_of_trading_day_utc, grouping.Key,
grouping.Where(y => y.fill.Timestamp.ToDateTime() >= _start_of_trading_day_utc).Sum(y => (uint)y.buy_quantity),
@@ -105,8 +109,11 @@ namespace mbts.spark {
);
}
public static bool get_driver(ref ulong bbo_time, ref ulong last_trade_time, SecurityMD sec_md, pnl_calc_type pnl_request, ref double driver_price) {
// check with eric as I'm not sure if i was every querying md correctly
public static bool get_driver(SecurityMD sec_md, pnl_calc_type pnl_request, ref double driver_price) {
// we always want to pass in 0 to the md query so that we don't get back NaN if the market
// data hasn't changed between query periods
ulong bbo_time = 0;
ulong last_trade_time = 0;
if (!sec_md.md.get_bbo(ref bbo_time, out NativePriceSize bid, out NativePriceSize ask)) return false;
if (!sec_md.md.get_last_trade(ref last_trade_time, out NativePriceSize last, out DateTime unused1, out ulong unused2)) return false;
@@ -188,7 +195,7 @@ namespace mbts.spark {
if (pnl_request.HasFlag(pnl_calc_type.last)) { driver_price = last.price; return true; }
// note that bid_or_ask is not considered here since this method only
// supports returning a single driver price; see update_pnl
if (pnl_request.HasFlag(pnl_calc_type.midpoint)) { driver_price = TickUtils.mid_tick(sec_md.security.ContractSpec, bid.price, ask.price); return true; }
if (pnl_request.HasFlag(pnl_calc_type.midpoint)) { driver_price = (bid.price + ask.price) / 2.0; return true; }
if (pnl_request.HasFlag(pnl_calc_type.open)) { driver_price = sec_md.md.open_price; return true; }
if (pnl_request.HasFlag(pnl_calc_type.close)) { driver_price = sec_md.md.close_price; return true; }
if (pnl_request.HasFlag(pnl_calc_type.settle)) { driver_price = sec_md.md.settlement_price; return true; }
@@ -42,6 +42,7 @@ namespace mbts.spark {
public SecurityImmutable? security => sec_md?.security;
public double buy_quantity => (fill.Side == Side.Buy) ? fill.LastShares : 0;
public double sell_quantity => (fill.Side == Side.Sell) ? fill.LastShares : 0;
public SecurityType? security_type => security?.security_type();
public override string ToString() {
return $"Fill: ( {account} {exchange} {security.ToString()} buy: {buy_quantity} sell: {sell_quantity} ) Security: {security.ToString()}";
@@ -13,19 +13,18 @@ namespace mbts.spark {
internal class PnLSummaryRow : ViewModelBase, IEquatable<PnLSummaryRow> {
DateTime _start_of_day;
(string account, Venue? exchange, string symbol, SecurityImmutable? security, SecurityMD? sec_md) key;
(string account, Venue? exchange, string symbol, SecurityImmutable? security, SecurityMD? sec_md, SecurityType? sec_type) key;
int _start_net_position, _total_net_position;
uint _day_long_quantity, _day_short_quantity;
double _total_pnl, _sod_pnl, _start_pnl, _pnl_price, _weighted_average_buy, _weighted_average_sell;
IEnumerable<FillImmutable> _fills;
ulong _bbo_ref, _last_ref;
double _driver;
static readonly Dictionary<string, double> cpp_dict = config.Configuration.get<bts.config.CppConfig>().cpp_entry;
public PnLSummaryRow(pnl_calc_type calc_type,
DateTime start_of_day,
(string, Venue?, string, SecurityImmutable?, SecurityMD?) key,
(string, Venue?, string, SecurityImmutable?, SecurityMD?, SecurityType?) key,
uint day_buy_quant, uint day_sell_quant, int net_pos, int sod_pos, double wavg_buy, double wavg_sell, IEnumerable<FillImmutable> fills) {
this._start_of_day = start_of_day;
this.key = key;
@@ -42,19 +41,21 @@ namespace mbts.spark {
update_pnl(calc_type);
}
/// <summary>
/// Looks up the cash per point (cpp) for the given SecurityImmutable.
/// If the SecurityImmutable is a cross-product exchange-traded spread,
/// such as a crack spread, where the legs have differing cpps, then
/// we'll return Double.Nan;
/// </summary>
/// <param name="s">The SecurityImmutable for which we will look up a cpp</param>
/// <returns>The found cpp, else Double.NaN</returns>
private double _get_cpp_for_security(SecurityImmutable s) {
if (s.security_type() == SecurityType.Spread) {
var distinct_cpps = s.Spread.Legs
.Select(l => get_cpp_for_symbol(l.Security))
.Distinct();
bool all_legs_have_same_cpp = distinct_cpps.Count() < 2;
if (all_legs_have_same_cpp) {
return distinct_cpps.First();
} else {
Logger.error(bts.log.Subsystem.Ui,
$"Security {s} contains legs with the following cash multipliers: { string.Join(",", distinct_cpps.Select(d => d.ToString())) } ");
return Double.NaN;
}
return all_legs_have_same_cpp ? distinct_cpps.First() : Double.NaN;
} else {
return get_cpp_for_symbol(s);
}
@@ -63,8 +64,6 @@ namespace mbts.spark {
double get_cpp_for_symbol(SecurityImmutable si) {
if (cpp_dict.TryGetValue(si.Symbol, out double cpp_out)) {
return cpp_out;
} else {
Logger.error(bts.log.Subsystem.Ui, $"No cash multiplier found for Security {si}, Symbol {si.Symbol}");
}
return double.NaN;
}
@@ -75,7 +74,8 @@ namespace mbts.spark {
if (key.sec_md.HasValue) {
double cpp = _get_cpp_for_security(key.security.Value);
if (pnl_request.HasFlag(pnl_calc_type.bid_or_ask)) {
key.sec_md.Value.md.get_bbo(ref _bbo_ref, out NativePriceSize bid, out NativePriceSize ask);
ulong bbo_ref = 0;
key.sec_md.Value.md.get_bbo(ref bbo_ref, out NativePriceSize bid, out NativePriceSize ask);
double summary_pnl = 0.0;
double start_pnl_total = 0.0;
@@ -94,7 +94,7 @@ namespace mbts.spark {
start_pnl = start_pnl_total;
pnl_price = Double.NaN;
} else {
if (PnLCalculator.get_driver(ref _bbo_ref, ref _last_ref, key.sec_md.Value, pnl_request, ref _driver)) {
if (PnLCalculator.get_driver(key.sec_md.Value, pnl_request, ref _driver)) {
double summary_pnl = 0.0;
double start_pnl_total = 0.0;
double day_pnl_total = 0.0;
@@ -170,6 +170,7 @@ namespace mbts.spark {
}
public SecurityImmutable? security => key.security;
public SecurityType security_type => key.sec_type.GetValueOrDefault();
public string security_text {
get => security.HasValue ? security.Value.ToString() : "Unknown Security";
@@ -224,7 +225,6 @@ namespace mbts.spark {
}
public int total_net_position {
get => _total_net_position;
set {
@@ -124,8 +124,8 @@ namespace mbts.co2
public double session_high { get { return _cold->session_high;} }
public double session_low { get { return _cold->session_low; } }
public double open_interest { get { return _cold->open_interest; } }
public double session_high_bid { get { return _cold->session_high_bid; } }
public double session_low_offer { get { return _cold->session_low_offer; } }
// public double session_high_bid { get { return _cold->session_high_bid; } }
// public double session_low_offer { get { return _cold->session_low_offer; } }
public double fixing_price { get { return _cold->fixing_price; } }
//
@@ -1114,7 +1114,7 @@ api::SecurityType AdminServiceUtils::security_type(const api::Security& security
// boostrapping ////////////////////////////
////////////////////////////////////////////
void add_product_position_limits(bts::api::admin::BTSAccount* to_account, api::Venue venue, api::SecurityType sec_type)
void add_product_position_limits(bts::api::admin::BTSAccount* to_account, api::Venue venue, api::SecurityType sec_type, uint32_t limit)
{
std::vector<md::UserSymbol> symbols;
md::get_system_md_symbols(venue, sec_type,&symbols);
@@ -1124,12 +1124,12 @@ void add_product_position_limits(bts::api::admin::BTSAccount* to_account, api::V
acct_a_prod_limit->mutable_product()->set_exchange(s.exchange());
acct_a_prod_limit->mutable_product()->set_security_type(s.type());
acct_a_prod_limit->mutable_product()->set_security_symbol(s.symbol());
acct_a_prod_limit->set_long_position_limit(500000);
acct_a_prod_limit->set_short_position_limit(500000);
acct_a_prod_limit->set_long_position_limit(limit);
acct_a_prod_limit->set_short_position_limit(limit);
}
}
void add_security_clip_sizes_to_account(bts::api::admin::BTSAccount* to_account, api::Venue venue, api::SecurityType sec_type)
void add_security_clip_sizes_to_account(bts::api::admin::BTSAccount* to_account, api::Venue venue, api::SecurityType sec_type,uint32_t limit)
{
std::vector<md::UserSymbol> symbols;
md::get_system_md_symbols(venue, sec_type,&symbols);
@@ -1139,21 +1139,31 @@ void add_security_clip_sizes_to_account(bts::api::admin::BTSAccount* to_account,
acct_a_clip_size->mutable_security()->set_exchange(s.exchange());
acct_a_clip_size->mutable_security()->set_security_type(s.type());
acct_a_clip_size->mutable_security()->set_security_symbol(s.symbol());
acct_a_clip_size->set_clip_size(50);
acct_a_clip_size->set_clip_size(limit);
}
}
void add_security_position_limits (bts::api::admin::BTSAccount* to_account, api::Venue venue, api::SecurityType sec_type)
{
auto acct_a1_sec_limit = to_account->add_security_position_limits();
acct_a1_sec_limit->mutable_security()->set_exchange(venue);
acct_a1_sec_limit->mutable_security()->set_security_type(sec_type);
acct_a1_sec_limit->mutable_security()->set_security_symbol("*");
acct_a1_sec_limit->set_long_position_limit (10000);
acct_a1_sec_limit->set_short_position_limit (10000);
}
void AdminServiceUtils::bootstrap_data (bts::api::admin::AdminData& data){
data.set_id(1);
bts::api::admin::AdminServiceOperationResult result;
bts::api::admin::AdminServiceCreateAccountResult account_result;
bts::api::admin::AdminServiceCreateEntityResult user_result;
// adding accounts
auto parent_account = create_account(data, 0, std::string("acc a"), std::string("description"), true, account_result);
auto account_1 = create_account(data, parent_account->id(), std::string("acc a1"), std::string("description"), true, account_result); account_1->set_is_active(true);
auto account_2 = create_account(data, parent_account->id(), std::string("acc a2"), std::string("description"), true, account_result); account_2->set_is_active(true);
auto account_3 = create_account(data, parent_account->id(), std::string("acc a3"), std::string("description"), true, account_result); account_3->set_is_active(true);
create_account(data, parent_account->id(), std::string("acc a4"), std::string("description"), true, account_result);
auto parent_account = create_account(data, 0, std::string("ACC A"), std::string("description"), true, account_result);
auto account_1 = create_account(data, parent_account->id(), std::string("ACC A1"), std::string("description"), true, account_result); account_1->set_is_active(true);
auto account_2 = create_account(data, parent_account->id(), std::string("ACC A2"), std::string("description"), true, account_result); account_2->set_is_active(true);
auto account_3 = create_account(data, parent_account->id(), std::string("ACC A3"), std::string("description"), true, account_result); account_3->set_is_active(true);
create_account(data, parent_account->id(), std::string("ACC A4"), std::string("description"), true, account_result);
// add group
auto def_group = create_group(data, 0, std::string("default"), result);
// adding users to the group
@@ -1225,65 +1235,36 @@ void AdminServiceUtils::bootstrap_data (bts::api::admin::AdminData& data){
data.mutable_accounts(j)->mutable_connections()->add_exchange_connection_names(conn_name);
}
// add prod limit for acc a
add_product_position_limits(parent_account, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_FUTURE);
add_product_position_limits(parent_account, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_SPREAD);
add_product_position_limits(parent_account, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_FUTURE);
add_product_position_limits(parent_account, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_SPREAD);
// add prod limit for ACC A
add_product_position_limits(parent_account, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_FUTURE,50000);
add_product_position_limits(parent_account, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_SPREAD,50000);
add_product_position_limits(parent_account, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_FUTURE,50000);
add_product_position_limits(parent_account, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_SPREAD,50000);
// security clip sizes for ACC A
add_security_clip_sizes_to_account(parent_account, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_FUTURE);
add_security_clip_sizes_to_account(parent_account, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_SPREAD);
add_security_clip_sizes_to_account(parent_account, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_FUTURE);
add_security_clip_sizes_to_account(parent_account, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_SPREAD);
add_security_clip_sizes_to_account(parent_account, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_FUTURE,50);
add_security_clip_sizes_to_account(parent_account, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_SPREAD,50);
add_security_clip_sizes_to_account(parent_account, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_FUTURE,50);
add_security_clip_sizes_to_account(parent_account, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_SPREAD,50);
// add sec limit for ACC A1
// cme
auto acct_a1_sec_limit = account_1->add_security_position_limits();
acct_a1_sec_limit->mutable_security()->set_exchange(api::Venue::VENUE_GLBX);
acct_a1_sec_limit->mutable_security()->set_security_type(api::SecurityType::SECURITYTYPE_FUTURE);
acct_a1_sec_limit->mutable_security()->set_security_symbol("*");
acct_a1_sec_limit->set_long_position_limit (10000);
acct_a1_sec_limit->set_short_position_limit (10000);
acct_a1_sec_limit = account_1->add_security_position_limits();
// sim
acct_a1_sec_limit = account_1->add_security_position_limits();
acct_a1_sec_limit->mutable_security()->set_exchange(api::Venue::VENUE_SIM);
acct_a1_sec_limit->mutable_security()->set_security_type(api::SecurityType::SECURITYTYPE_FUTURE);
acct_a1_sec_limit->mutable_security()->set_security_symbol("*");
acct_a1_sec_limit->set_long_position_limit (10000);
acct_a1_sec_limit->set_short_position_limit (10000);
acct_a1_sec_limit = account_1->add_security_position_limits();
add_security_position_limits(account_1, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_FUTURE);
add_security_position_limits(account_1, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_SPREAD);
add_security_position_limits(account_1, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_FUTURE);
add_security_position_limits(account_1, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_SPREAD);
// add prod limit for ACC A1
// cme
auto acct_a1_prod_limit = account_1->add_product_position_limits();
acct_a1_prod_limit->mutable_product()->set_exchange(api::Venue::VENUE_GLBX);
acct_a1_prod_limit->mutable_product()->set_security_type(api::SecurityType::SECURITYTYPE_FUTURE);
acct_a1_prod_limit->mutable_product()->set_security_symbol("*");
acct_a1_prod_limit->set_long_position_limit(1000000);
acct_a1_prod_limit->set_short_position_limit(1000000);
// sim
acct_a1_prod_limit = account_1->add_product_position_limits();
acct_a1_prod_limit->mutable_product()->set_exchange(api::Venue::VENUE_SIM);
acct_a1_prod_limit->mutable_product()->set_security_type(api::SecurityType::SECURITYTYPE_FUTURE);
acct_a1_prod_limit->mutable_product()->set_security_symbol("*");
acct_a1_prod_limit->set_long_position_limit(1000000);
acct_a1_prod_limit->set_short_position_limit(1000000);
add_product_position_limits(account_1, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_FUTURE,100000);
add_product_position_limits(account_1, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_SPREAD,100000);
add_product_position_limits(account_1, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_FUTURE,100000);
add_product_position_limits(account_1, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_SPREAD,100000);
// security clip sizes for ACC A1
// cme
auto acct_a1_clip_size = account_1->mutable_security_clip_limits()->add_limit();
acct_a1_clip_size->mutable_security()->set_exchange(api::Venue::VENUE_GLBX);
acct_a1_clip_size->mutable_security()->set_security_type(api::SecurityType::SECURITYTYPE_FUTURE);
acct_a1_clip_size->mutable_security()->set_security_symbol("*");
acct_a1_clip_size->set_clip_size(100);
// sim
acct_a1_clip_size = account_1->mutable_security_clip_limits()->add_limit();
acct_a1_clip_size->mutable_security()->set_exchange(api::Venue::VENUE_SIM);
acct_a1_clip_size->mutable_security()->set_security_type(api::SecurityType::SECURITYTYPE_FUTURE);
acct_a1_clip_size->mutable_security()->set_security_symbol("*");
acct_a1_clip_size->set_clip_size(100);
add_security_clip_sizes_to_account(account_1, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_FUTURE,100);
add_security_clip_sizes_to_account(account_1, api::Venue::VENUE_GLBX, api::SecurityType::SECURITYTYPE_SPREAD,100);
add_security_clip_sizes_to_account(account_1, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_FUTURE,100);
add_security_clip_sizes_to_account(account_1, api::Venue::VENUE_SIM, api::SecurityType::SECURITYTYPE_SPREAD,100);
}
bool AdminServiceUtils::has_id (uint32_t id){return id>0;}
bool AdminServiceUtils::is_symbol_set (const std::string& symbol){
File diff suppressed because it is too large. Load diff
+4 -2
View File
@@ -28,8 +28,10 @@ double dump(TimeStamp time) {
string dump(PriceSize ps) {
stringstream res;
res << "{";
res << "'price': " << ps.price() << ", ";
res << "'size': " << ps.size();
res << "'price': " << std::setprecision(11) << ps.price() << ", ";
res << "'size': " << ps.size() << " ";
// res << "'mant': " << ps.mantissa() << ", ";
// res << "'exp': " << (int)ps.exponent() << " ";
res << "}";
return res.str();
}
+2 -1
View File
@@ -115,7 +115,7 @@ void MDProducerHandle::set_status(CoconutSecurityStatus status) {
}
}
void MDProducerHandle::add_trade(TimeStamp time, const PriceSize price, LLDateTime tradetime, uint32_t volume) {
void MDProducerHandle::add_trade(TimeStamp time, const PriceSize price, LLDateTime tradetime, co2::AggressorSide agside, uint32_t volume) {
cdata().last_trade.store(price);
cdata().last_trade_time = tradetime;
cdata().total_volume = volume;
@@ -127,6 +127,7 @@ void MDProducerHandle::add_trade(TimeStamp time, const PriceSize price, LLDateTi
trade.set_mantissa(price.mantissa());
trade.set_size(price.size());
trade.set_time(tradetime);
trade.set_aggressor_side(agside);
if (volume > 0) trade.set_total_volume(volume);
trade.set_key(key());
_channel.add_trade(trade);
+1 -1
View File
@@ -56,7 +56,7 @@ public:
void set_status(co2::CoconutSecurityStatus status); // hot
// Updates trade log and last trade
void add_trade(TimeStamp time, const PriceSize pricesize, datetime::LLDateTime date, uint32_t total_volume=0); // cold
void add_trade(TimeStamp time, const PriceSize pricesize, datetime::LLDateTime date, co2::AggressorSide agside, uint32_t total_volume=0); // cold
// Update last_trade without updating trade log
void set_last_trade(TimeStamp time, const PriceSize ps, datetime::LLDateTime date, uint32_t total_volume);
void add_rfq(TimeStamp time, const co2::QuoteRequestMessage& rfq); // cold
+7
View File
@@ -119,6 +119,12 @@ message MiscMessage {
double session_low_offer = 12;
double fixing_price = 13;
}
enum AggressorSide {
AGGRESSOR_SIDE_NONE = 0;
AGGRESSOR_SIDE_BUY = 1;
AGGRESSOR_SIDE_SELL = 2;
}
message TradeMessage {
uint32 key = 1;
@@ -130,6 +136,7 @@ message TradeMessage {
uint32 size = 6;
uint32 total_volume = 7;
bool gap = 8;
AggressorSide aggressor_side = 9;
}
message QuoteRequestMessage {
enum Side {
+1 -1
View File
@@ -24,7 +24,7 @@ target_link_libraries( sparkd
tbb
double-conversion
pugixml
onixs-cmemdh-all-4.5.2
onixs-cmemdh-all-4.8.0
quickfix
benchmark
lttng-ust
@@ -474,7 +474,8 @@ void ExchangeSimApplication::update_md(std::string const &sec_desc) {
utils::TimeStamp::now(),
md::PriceSize::from_double<7>(t.price.value() * price_factor,
t.quantity.value()),
datetime::ll_now());
datetime::ll_now(),
co2::AGGRESSOR_SIDE_NONE);
}
}
@@ -526,6 +527,9 @@ void ExchangeSimApplication::on_depth(
if (sec.has_synthetic())
return ;
if (!me->do_merge_with_md)
return;
auto it = me->md_consumer_recs.find(sec.glbx().security_desc());
bts_assert(it != me->md_consumer_recs.end());
+31 -2
View File
@@ -4,6 +4,7 @@
#include "lib/api/public/ApiUtils.h"
#include "lib/api/core/ApiClientInterop.h"
#include "lib/api/services/UserService.client.pb.h"
#include "lib/api/services/AdminService.client.pb.h"
#include "lib/utils/bts_assert.h"
#include <vector>
#include <unordered_map>
@@ -98,7 +99,7 @@ struct ApiGatewayImpl {
// buffer = [size][ResponseHeader][Payload].
GatewayResponse response;
response.set_call_result(buffer, length);
LOG(Api,Info, "Gateway Result: {}", api::toJSON(response));
LOG(Api,Diag, "Gateway Result: {}", api::toJSON(response));
// in response send to client
const Responder* r = static_cast<const Responder*>(extra);
if (r != nullptr) {
@@ -123,7 +124,7 @@ ApiGatewaySession::~ApiGatewaySession(){}
void ApiGatewaySession::handle(const api::gateway::GatewayRequest& request, const Responder& reply) {
GatewayResponse response;
LOG(Api,Info, "Gateway Request: {}", api::toJSON(request));
LOG(Api,Diag, "Gateway Request: {}", api::toJSON(request));
switch(request.request_case()) {
case GatewayRequest::kLogin:
_me->handle_login(request.login(), reply);
@@ -138,4 +139,32 @@ void ApiGatewaySession::handle(const api::gateway::GatewayRequest& request, cons
}
}
std::string get_server_info(const api::ServiceContext& ctx) {
using namespace api::admin;
using std::endl;
api::VoidMessage vod;
AdminService admin(ctx.locate<api::admin::AdminService>());
auto response = admin.get_admin_data(vod, 100);
std::stringstream ss;
ss << "{" << endl;
if (response.success()) {
ss << " \"users\": [" << endl;
for (const auto& user : response.result()->users()) {
ss << " ";
if (&user != &response.result()->users()[0]) ss << ",";
ss << "{ ";
ss << "\"name\": \"" << user.name() << "\", ";
ss << "\"operator_id\": \"" << user.user_data().exchange_user_data().cme_data().operator_id() << "\"";
ss << "}" << endl;
}
ss << " ]" << endl;
}
ss << "}" << endl;
return ss.str();
}
}}
+4
View File
@@ -20,6 +20,10 @@ class ApiGatewaySession {
~ApiGatewaySession();
void handle(const api::gateway::GatewayRequest& request, const Responder&);
};
std::string get_server_info(const api::ServiceContext&);
}}
+31
View File
@@ -156,6 +156,34 @@ namespace http {
_mtimer->observe((utils::TimeStamp::now() - start).microseconds() / 1000.0);
}
bool require_authentication(connection_ptr& con, const std::string& username, const std::string& password) {
auto auth = con->get_request_header("Authorization");
if (!auth.empty() && auth.size() >= 7 && boost::iequals(auth.substr(0, 6), "Basic ")) {
auto b64 = auth.substr(6);
auto decoded = websocketpp::base64_decode(b64);
auto colon = decoded.find(':');
if (colon != std::string::npos) {
auto user = decoded.substr(0, colon);
auto pass = decoded.substr(colon+1);
if (user == username && pass == password) return true;
}
}
// Failed
con->append_header("WWW-Authenticate", "Basic realm=\"BTS\"");
con->set_status(websocketpp::http::status_code::unauthorized);
con->set_body("Not Authorized");
return false;
}
void check_auth_and_return_info(connection_ptr& con) {
if (require_authentication(con, "bts", "bbb835af-b1ea-42d3-8be1-fd9d5555530d")) {
auto horrible_json = get_server_info(_ctx);
con->set_body(horrible_json);
con->set_status(websocketpp::http::status_code::ok);
}
}
void directory_index(connection_ptr& con, const std::string& resource, const boost::filesystem::path& path) {
// directory listing
std::string body = "<!doctype html>\n";
@@ -256,6 +284,9 @@ namespace http {
else if (boost::iequals(resource, "/metrics")) {
return_metrics(con);
}
else if (boost::iequals(resource, "/server_info")) {
check_auth_and_return_info(con);
}
else if (boost::iequals(resource, "/bts_installer.exe") && boost::filesystem::is_regular_file(_www+"/bts_installer.exe")) {
return_bts_installer(con);
}
@@ -3,6 +3,7 @@
#include <vector>
#include "lib/utils/helper_macros.h"
#include "lib/config/protos/MarketData.pb.h"
#include "lib/md/protos/co2.pb.h"
using namespace std;
using namespace bts::co2;
@@ -10,74 +11,6 @@ using namespace bts::co2;
namespace bts {
namespace md {
void decode_ticks(int vtt, double mintick, FixedSecurity& dest) {
switch(vtt) {
default:
case 0:
dest.low_tick = mintick;
dest.high_tick = mintick;
dest.price_break = 0;
break;
case 1:
dest.price_break = 500;
dest.low_tick = 5;
dest.high_tick = 10;
break;
case 2:
dest.price_break = 5;
dest.low_tick = 0.5;
dest.high_tick = 1;
break;
case 3:
dest.price_break = 10;
dest.low_tick = 1;
dest.high_tick = 2;
break;
case 4:
dest.price_break = 500;
dest.low_tick = 5;
dest.high_tick = 25;
break;
case 10:
dest.price_break = 300;
dest.low_tick = 5;
dest.high_tick = 25;
break;
case 11:
dest.price_break = 300;
dest.low_tick = 5;
dest.high_tick = 10;
break;
case 12:
dest.price_break = 5;
dest.low_tick = 0.25;
dest.high_tick = 0.5;
break;
}
}
int floorlog10(int64_t m) {
bts_assert(m >= 0);
if (m < 10) return 0;
if (m < 100) return 1;
if (m < 1000) return 2;
if (m < 10000) return 3;
if (m < 100000) return 4;
if (m < 1000000) return 5;
if (m < 10000000) return 6;
if (m < 100000000) return 7;
if (m < 1000000000) return 8;
if (m < 10000000000) return 9;
if (m < 100000000000) return 10;
if (m < 1000000000000) return 11;
if (m < 10000000000000) return 12;
if (m < 100000000000000) return 13;
if (m < 1000000000000000) return 14;
if (m < 10000000000000000) return 15;
if (m < 100000000000000000) return 16;
if (m < 1000000000000000000) return 17;
return 19;
}
MDP3Listener::MDP3Listener(
CMESecurityIndex& index,
@@ -181,159 +114,6 @@ void MDP3Listener::onEndOfPacket(onixs::Handler&, const onixs::PacketArgs&) {
//
// Security discovery
template <class Price>
double double_of_price(const Price& price, int8_t display_factor) {
// order of multiplication is important because of floating point error
return (price.mantissa() * pow10(price.exponent())) * pow10(display_factor);
}
inline datetime::LLDateTime ll_of_timestamp(const onixs::Timestamp& ts) {
return datetime::ll_from_parts(ts.year(), (int)ts.month(), ts.day(), ts.hour(), ts.minute(), ts.second(), ts.millisecond());
}
datetime::Date date_of_timestamp(const onixs::Timestamp& ts) {
return datetime::Date(ts.year(), (int)ts.month(), ts.day());
}
template <class Definition>
datetime::Date date_of_maturity(const Definition& def) {
for (const auto& event : def.events()) {
if (event.eventType() == onixs::EventType::LastEligibleTradeDate) {
return date_of_timestamp(event.eventTime());
}
}
return datetime::Date();
}
template <class Definition>
void set_security_common(const Definition& def, FixedSecurity& fsec) {
fsec.numeric_id = def.securityId();
fsec.symbol(def.asset().items(), def.asset().size());
fsec.cfi_code(def.cfiCode().items(), def.cfiCode().size());
fsec.alt_symbol(def.securityGroup().items(), def.securityGroup().size());
fsec.security_desc(def.symbol().items(), def.symbol().size());
fsec.exchange = api::Venue::VENUE_GLBX;
// tickRule not present in futures
fsec.cme_market_segment_id = def.marketSegmentId();
fsec.display_factor = def.displayFactor().exponent() + floorlog10(def.displayFactor().mantissa());
def.mainFraction(fsec.cme_main_fraction);
def.subFraction(fsec.cme_sub_fraction);
def.priceDisplayFormat(fsec.cme_price_display_format);
}
void MDP3Listener::onDefinition(onixs::Handler&, const onixs::Security& osec, const onixs::InstrumentDefinitionFutureArgs& def) {
tracepoint (bts_trace,trace_order,(char*) "onDefinition.future", _latest_sequence, (uint16_t) _latest_sequence, 0);
const auto& sec = def.message();
auto exchange_id = sec.securityId();
// LOG(md, Info, "onDefinition future {} {}",
// std::string(sec.asset().items(), sec.asset().size()),
// std::string(sec.symbol().items(), sec.symbol().size()));
if (filter_security(exchange_id, sec) != ADD) return;
bts_assert(exchange_id == osec.id());
FixedFutureSecurity fsec;
set_security_common(sec, fsec);
fsec.price_break = 0;
// low/high tick are stored non-premultiplied and multiplied in conversion to api::Secutity
double min_tick = double_of_price(sec.minPriceIncrement(), 0);
fsec.low_tick = fsec.high_tick = min_tick;
onixs::PRICE min_tick_amount;
sec.minPriceIncrementAmount(min_tick_amount);
double min_tick_dbl = double_of_price(min_tick_amount, 0);
fsec.cash_per_point = min_tick_dbl / min_tick / pow10(fsec.display_factor);
auto expiration = date_of_maturity(sec);
fsec.expiration_year = expiration.year;
fsec.expiration_month = expiration.month;
fsec.expiration_day = expiration.day;
add_security(fsec);
}
void MDP3Listener::onDefinition(onixs::Handler&, const onixs::Security&, const onixs::InstrumentDefinitionOptionArgs& def) {
tracepoint (bts_trace,trace_order,(char*) "onDefinition.option", _latest_sequence, (uint16_t) _latest_sequence, 0);
const auto& sec = def.message();
auto exchange_id = sec.securityId();
// LOG(Info, MarketData) << "onDefinition option " << exchange_id;
if (filter_security(exchange_id, sec) != ADD) return;
FixedOptionSecurity fsec;
set_security_common(sec, fsec);
auto expiration = date_of_maturity(sec);
fsec.expiration_year = expiration.year;
fsec.expiration_month = expiration.month;
fsec.expiration_day = expiration.day;
onixs::PRICE strike_price;
bts_assert(sec.strikePrice(strike_price));
fsec.strike = double_of_price(strike_price, fsec.display_factor);
onixs::PRICE min_tick, min_tick_amount;
sec.minPriceIncrement(min_tick);
sec.minPriceIncrementAmount(min_tick_amount);
int8_t tick_rule;
if (sec.tickRule(tick_rule)) {
decode_ticks(tick_rule, double_of_price(min_tick, 0), fsec);
}
fsec.cash_per_point = double_of_price(min_tick_amount, 0) / fsec.low_tick / pow10(fsec.display_factor);
fsec.call_put = sec.putOrCall() == onixs::PutOrCall::Call ? api::PUTORCALL_CALL : api::PUTORCALL_PUT;
add_security(fsec);
}
void MDP3Listener::onDefinition(onixs::Handler&, const onixs::Security&, const onixs::InstrumentDefinitionSpreadArgs& spread_args) {
tracepoint (bts_trace,trace_order,(char*) "onDefinition.spread", _latest_sequence, (uint16_t) _latest_sequence, 0);
const auto& sec = spread_args.message();
auto exchange_id = sec.securityId();
// LOG(md, Info, "onDefinition spread {} {}",
// std::string(sec.asset().items(), sec.asset().size()),
// std::string(sec.symbol().items(), sec.symbol().size()));
if (filter_security(exchange_id, sec) != ADD) return;
// Filter out any already expired spreads
auto expiration = date_of_maturity(sec);
if (expiration < datetime::today()) return;
FixedSpreadSecurityL fsec;
set_security_common(sec, fsec);
vector<uint32_t> leg_exchange_ids;
leg_exchange_ids.reserve(sec.legs().size());
onixs::PRICE min_tick = sec.minPriceIncrement();
int8_t tick_rule;
if (sec.tickRule(tick_rule)) {
decode_ticks(tick_rule, double_of_price(min_tick, 0), fsec);
}
else {
double mintick = double_of_price(min_tick, 0);
fsec.low_tick = mintick;
fsec.high_tick = mintick;
fsec.price_break = 0;
}
fsec.set_leg_count(sec.legs().size());
for(size_t x = 0; x < fsec.leg_count(); ++x) {
const auto& leg = sec.legs()[x];
onixs::PRICE price;
if (leg.legPrice(price)) {
fsec.legs[x].leg_price = double_of_price(price, fsec.display_factor);
}
onixs::DecimalQty qty;
if (leg.legOptionDelta(qty)) {
fsec.legs[x].leg_delta = double_of_price(qty, 0);
}
fsec.legs[x].leg_quantity = leg.legRatioQty();
fsec.legs[x].leg_side = leg.legSide() == onixs::LegSide::BuySide ? api::SIDE_BUY : api::SIDE_SELL;
leg_exchange_ids.push_back(leg.legSecurityId());
}
add_security(fsec);
_index.add_spread_legs(fsec.numeric_id, leg_exchange_ids);
}
void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, const onixs::DirectBook& book) {
if (_booktype == CMEOptions::BOOKTYPE_DIRECT) {
onBookUpdate(sec, book);
@@ -349,48 +129,28 @@ void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, con
//
// Trades
void on_trade(SecurityData* data, const onixs::PRICE& price, int size, const onixs::Timestamp& onixs_date) {
AggressorSide map_aggressor(onixs::AggressorSide::Enum agside) {
switch(agside) {
default:
case onixs::AggressorSide::NoAggressor:
return AGGRESSOR_SIDE_NONE;
case onixs::AggressorSide::Buy:
return AGGRESSOR_SIDE_BUY;
case onixs::AggressorSide::Sell:
return AGGRESSOR_SIDE_SELL;
}
}
void on_trade(SecurityData* data, const onixs::Decimal& price, int size, onixs::AggressorSide::Enum agside, const onixs::Timestamp& onixs_date) {
auto ts = utils::TimeStamp::now();
PriceSize ps = pricesize_of_price_size(price, data->handle.security().display_factor, size);
auto date = ll_of_timestamp(onixs_date);
data->handle.add_trade(ts, ps, date, data->electronic_volume + size);
}
void MDP3Listener::onTrade(onixs::Handler&, const onixs::Security& sec, const onixs::RecoveryEntryArgs& arg) {
tracepoint (bts_trace,trace_order,(char*) "onTrade.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != NULL) {
int size = 0;
arg.entry().entrySize(size);
onixs::PRICE price;
arg.entry().entryPx(price);
on_trade(data, price, size, arg.message().transactTime());
}
}
void MDP3Listener::onTrade(onixs::Handler&, const onixs::Security& sec, const onixs::TradeSummaryArgs& arg) {
tracepoint (bts_trace,trace_order,(char*) "onTrade.summary", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != NULL) {
auto size = arg.entry().entrySize();
onixs::PRICE price = arg.entry().entryPx();
on_trade(data, price, size, arg.message().transactTime());
}
}
void MDP3Listener::onTrade(onixs::Handler&, const onixs::Security& sec, const onixs::TradeArgs& arg) {
tracepoint (bts_trace,trace_order,(char*) "onTrade.trade_args", _latest_sequence, (uint16_t) _latest_sequence, 0);
if (arg.entry().updateAction() == onixs::UpdateAction::New) {
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
int size = arg.entry().entrySize();
onixs::PRICE price = arg.entry().entryPx();
on_trade(data, price, size, arg.message().transactTime());
}
}
data->handle.add_trade(ts, ps, date, map_aggressor(agside), data->electronic_volume + size);
}
//
// RFQ
void MDP3Listener::onQuoteRequest(onixs::Handler&, const onixs::Security& sec, const onixs::QuoteRequestRelatedSymArgs& arg) {
void MDP3Listener::onQuoteRequest(onixs::Handler&, const onixs::Security& sec, const onixs::QuoteRequest39RelatedSymArgs& arg) {
tracepoint (bts_trace,trace_order,(char*) "onQuoteRequest", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
@@ -439,7 +199,7 @@ void MDP3Listener::onQuoteRequest(onixs::Handler&, const onixs::Security& sec, c
//
// Volume
void MDP3Listener::onElectronicVolume(onixs::Handler&, const onixs::Security& sec, const onixs::VolumeArgs& args) {
void MDP3Listener::onElectronicVolume(onixs::Handler&, const onixs::Security& sec, const onixs::Volume37Args& args) {
tracepoint (bts_trace,trace_order,(char*) "onElectronicVolume.volume", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
@@ -449,162 +209,6 @@ void MDP3Listener::onElectronicVolume(onixs::Handler&, const onixs::Security& se
data->electronic_volume = args.entry().entrySize();
}
}
void MDP3Listener::onElectronicVolume(onixs::Handler&, const onixs::Security& sec, const onixs::RecoveryEntryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onElectronicVolume.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data) {
int32_t size;
if (args.entry().entrySize(size)) {
data->electronic_volume = size;
}
}
}
//
// Misc
void MDP3Listener::onSettlementPrice(onixs::Handler&, const onixs::Security& sec, const onixs::DailyStatisticsArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onSettlementPrice.daily", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::PRICE price;
onixs::Timestamp time;
args.entry().entryPx(price);
args.entry().tradingReferenceDate(time);
auto display_factor = data->handle.security().display_factor;
data->handle.update_settlement(
utils::TimeStamp::now(),
double_of_price(price, display_factor),
date_of_timestamp(time));
}
}
void MDP3Listener::onSettlementPrice(onixs::Handler&, const onixs::Security& sec, const onixs::RecoveryEntryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onSettlementPrice.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::PRICE price;
onixs::Timestamp time;
args.entry().entryPx(price);
args.entry().tradingReferenceDate(time);
auto display_factor = data->handle.security().display_factor;
data->handle.update_settlement(
utils::TimeStamp::now(),
double_of_price(price, display_factor),
date_of_timestamp(time));
}
}
void MDP3Listener::onOpenInterest(onixs::Handler&, const onixs::Security& sec, const onixs::DailyStatisticsArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onOpenInterest.daily", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::PRICE price;
args.entry().entryPx(price);
auto display_factor = data->handle.security().display_factor;
data->handle.update_open_interest(utils::TimeStamp::now(), double_of_price(price, display_factor));
}
}
void MDP3Listener::onOpenInterest(onixs::Handler&, const onixs::Security& sec, const onixs::RecoveryEntryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onOpenInterest.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::PRICE price;
args.entry().entryPx(price);
auto display_factor = data->handle.security().display_factor;
data->handle.update_open_interest(utils::TimeStamp::now(), double_of_price(price, display_factor));
}
}
void MDP3Listener::onOpeningPrice(onixs::Handler&, const onixs::Security& sec, const onixs::SessionStatisticsArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onOpeningPrice.session", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::PRICE price = args.entry().entryPx();
onixs::Timestamp time = args.message().transactTime();
auto display_factor = data->handle.security().display_factor;
data->handle.update_opening(
utils::TimeStamp::now(),
double_of_price(price, display_factor),
date_of_timestamp(time));
}
}
void MDP3Listener::onOpeningPrice(onixs::Handler&, const onixs::Security& sec, const onixs::RecoveryEntryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onOpeningPrice.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::PRICE price;
args.entry().entryPx(price);
onixs::Timestamp time;
args.entry().tradingReferenceDate(time);
auto display_factor = data->handle.security().display_factor;
data->handle.update_opening(
utils::TimeStamp::now(),
double_of_price(price, display_factor),
date_of_timestamp(time));
}
}
void MDP3Listener::onHighTradePrice(onixs::Handler&, const onixs::Security& sec, const onixs::SessionStatisticsArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onHighTradePrice.session", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
data->handle.update_session_high(
utils::TimeStamp::now(),
double_of_price(args.entry().entryPx(), display_factor));
}
}
void MDP3Listener::onHighTradePrice(onixs::Handler&, const onixs::Security& sec, const onixs::RecoveryEntryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onHighTradePrice.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
onixs::PRICE price;
args.entry().entryPx(price);
data->handle.update_session_high(
utils::TimeStamp::now(),
double_of_price(price, display_factor));
}
}
void MDP3Listener::onLowTradePrice(onixs::Handler&, const onixs::Security& sec, const onixs::SessionStatisticsArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onLowTradePrice.session", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
data->handle.update_session_low(
utils::TimeStamp::now(),
double_of_price(args.entry().entryPx(), display_factor));
}
}
void MDP3Listener::onLowTradePrice(onixs::Handler&, const onixs::Security& sec, const onixs::RecoveryEntryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onLowTradePrice.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
onixs::PRICE price;
args.entry().entryPx(price);
data->handle.update_session_low(
utils::TimeStamp::now(),
double_of_price(price, display_factor));
}
}
void MDP3Listener::onHighestBid(onixs::Handler&, const onixs::Security& sec, const onixs::SessionStatisticsArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onHighestBid.session", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
data->handle.update_session_high_bid(
utils::TimeStamp::now(),
double_of_price(args.entry().entryPx(), display_factor));
}
}
void MDP3Listener::onLowestOffer(onixs::Handler&, const onixs::Security& sec, const onixs::SessionStatisticsArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onLowestOffer.session", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
data->handle.update_session_low_offer(
utils::TimeStamp::now(),
double_of_price(args.entry().entryPx(), display_factor));
}
}
//
// Non-onixs calls
@@ -5,7 +5,9 @@
#include "CMESecurityIndex.h"
#include "server/sparkd/tracing/bts_trace.h"
#include "MDP3ListenerHelpers.h"
#include "onixs.h"
#include <tbb/concurrent_queue.h>
#include <vector>
#include <atomic>
@@ -14,11 +16,6 @@
namespace bts {
namespace md {
inline PriceSize pricesize_of_price_size(const onixs::PRICE price, int8_t display_factor, Size size) {
PriceSize result(price.mantissa(), price.exponent() + display_factor, size);
return result;
}
class MDP3Listener :
public onixs::HandlerListener,
public onixs::MarketDataListener,
@@ -54,9 +51,21 @@ public:
//
// Security discovery
void onDefinition(onixs::Handler&, const onixs::Security&, const onixs::InstrumentDefinitionFutureArgs&) override;
void onDefinition(onixs::Handler&, const onixs::Security&, const onixs::InstrumentDefinitionOptionArgs&) override;
void onDefinition(onixs::Handler&, const onixs::Security&, const onixs::InstrumentDefinitionSpreadArgs&) override;
template <typename InstrumentDefinitionFuture>
void onFuture(onixs::Handler&, const onixs::Security&, const InstrumentDefinitionFuture&);
template <typename InstrumentDefinition>
void onOption(onixs::Handler&, const onixs::Security&, const InstrumentDefinition&);
template <typename InstrumentDefinition>
void onSpread(onixs::Handler&, const onixs::Security&, const InstrumentDefinition&);
void onDefinition(onixs::Handler& h, const onixs::Security& s, const onixs::InstrumentDefinitionFuture27Args& def) override { onFuture(h, s, def); }
void onDefinition(onixs::Handler& h, const onixs::Security& s, const onixs::InstrumentDefinitionFuture54Args& def) override { onFuture(h, s, def); }
void onDefinition(onixs::Handler& h, const onixs::Security& s, const onixs::InstrumentDefinitionOption41Args& def) override { onOption(h, s, def); }
void onDefinition(onixs::Handler& h, const onixs::Security& s, const onixs::InstrumentDefinitionOption55Args& def) override { onOption(h, s, def); }
void onDefinition(onixs::Handler& h, const onixs::Security& s, const onixs::InstrumentDefinitionSpread29Args& def) override { onSpread(h, s, def); }
void onDefinition(onixs::Handler& h, const onixs::Security& s, const onixs::InstrumentDefinitionSpread56Args& def) override { onSpread(h, s, def); }
//
// Book
@@ -66,79 +75,74 @@ public:
void onBookUpdate(onixs::Handler&, const onixs::Security&, const onixs::ConsolidatedBook&) override;
template <class TBook>
void onBookUpdate(const onixs::Security& sec, const TBook& book) {
tracepoint (bts_trace,trace_order,(char*) "onBookUpdate", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto data = _index.get_security(sec.id());
if (data == nullptr) return;
bts_assert(data->id == (uint32_t)sec.id());
auto display_factor = data->handle.security().display_factor;
// Put the data into the cache. Flush at the end of the packet.
auto key = data->handle.key();
auto find_iter = std::find_if(_book_updates.begin(), _book_updates.end(), [key](const BookData& entry) {
return key == entry.handle.key();
});
bool found = find_iter != _book_updates.end();
if (!found) {
_book_updates.emplace_back(data->handle);
}
BookData& cache = found ? *find_iter : _book_updates.back();
// Overwrite all entries every time
size_t bids_size = book.bids().size();
size_t asks_size = book.offers().size();
if (!data->handle.has_depth()) {
bids_size = std::min(bids_size, size_t { 1 });
asks_size = std::min(asks_size, size_t { 1 });
}
for (size_t x = 0; x < bids_size; ++x) {
cache.bids[x] = pricesize_of_price_size(book.bids()[x].price(), display_factor, book.bids()[x].quantity());
}
for (size_t x = 0; x < asks_size; ++x) {
cache.asks[x] = pricesize_of_price_size(book.offers()[x].price(), display_factor, book.offers()[x].quantity());
}
// NaN out the remaining depth
for (size_t x = bids_size; x < COCONUT_MAX_DEPTH; ++x) {
cache.bids[x] = PriceSize::NO_MARKET;
}
for (size_t x = asks_size; x < COCONUT_MAX_DEPTH; ++x) {
cache.asks[x] = PriceSize::NO_MARKET;
}
}
void onBookUpdate(const onixs::Security& sec, const TBook& book);
//
// Trades
void onTrade(onixs::Handler&, const onixs::Security&, const onixs::RecoveryEntryArgs&) override;
void onTrade(onixs::Handler&, const onixs::Security&, const onixs::TradeArgs&) override;
void onTrade(onixs::Handler&, const onixs::Security&, const onixs::TradeSummaryArgs&) override;
template <typename TradeRecovery>
void onTradeRecovery(const onixs::Security&, const TradeRecovery&);
void onTrade(onixs::Handler&, const onixs::Security& s, const onixs::Recovery52EntryArgs& arg) override { onTradeRecovery(s, arg); }
void onTrade(onixs::Handler&, const onixs::Security& s, const onixs::Recovery38EntryArgs& arg) override { onTradeRecovery(s, arg); }
template <typename Trade>
void onTradeSummary(const onixs::Security&, const Trade&);
void onTrade(onixs::Handler&, const onixs::Security& s, const onixs::TradeSummary48Args& arg) override { onTradeSummary(s, arg); }
void onTrade(onixs::Handler&, const onixs::Security& s, const onixs::TradeSummary42Args& arg) override { onTradeSummary(s, arg); }
//
// RFQ
void onQuoteRequest(onixs::Handler&, const onixs::Security&, const onixs::QuoteRequestRelatedSymArgs&) override;
void onQuoteRequest(onixs::Handler&, const onixs::Security&, const onixs::QuoteRequest39RelatedSymArgs&) override;
//
// Volume
void onElectronicVolume(onixs::Handler&, const onixs::Security&, const onixs::VolumeArgs&) override;
void onElectronicVolume(onixs::Handler&, const onixs::Security&, const onixs::RecoveryEntryArgs&) override;
void onElectronicVolume(onixs::Handler&, const onixs::Security&, const onixs::Volume37Args&) override;
template <typename RecoveryEntry>
void onElectronicVolume(const onixs::Security&, const RecoveryEntry&);
void onElectronicVolume(onixs::Handler&, const onixs::Security& s, const onixs::Recovery52EntryArgs& arg) override { onElectronicVolume(s, arg); }
void onElectronicVolume(onixs::Handler&, const onixs::Security& s, const onixs::Recovery38EntryArgs& arg) override { onElectronicVolume(s, arg); }
//
// Misc
void onSettlementPrice(onixs::Handler&, const onixs::Security&, const onixs::DailyStatisticsArgs&) override;
void onSettlementPrice(onixs::Handler&, const onixs::Security&, const onixs::RecoveryEntryArgs&) override;
void onOpenInterest(onixs::Handler&, const onixs::Security&, const onixs::DailyStatisticsArgs&) override;
void onOpenInterest(onixs::Handler&, const onixs::Security&, const onixs::RecoveryEntryArgs&) override;
void onOpeningPrice(onixs::Handler&, const onixs::Security&, const onixs::SessionStatisticsArgs&) override;
void onOpeningPrice(onixs::Handler&, const onixs::Security&, const onixs::RecoveryEntryArgs&) override;
void onHighTradePrice(onixs::Handler&, const onixs::Security&, const onixs::SessionStatisticsArgs&) override;
void onHighTradePrice(onixs::Handler&, const onixs::Security&, const onixs::RecoveryEntryArgs&) override;
void onLowTradePrice(onixs::Handler&, const onixs::Security&, const onixs::SessionStatisticsArgs&) override;
void onLowTradePrice(onixs::Handler&, const onixs::Security&, const onixs::RecoveryEntryArgs&) override;
template <typename StatisticsArgs>
void onSettlementPrice(const onixs::Security& sec, const StatisticsArgs& args);
void onSettlementPrice(onixs::Handler&, const onixs::Security& s, const onixs::DailyStatistics49Args& arg) override { onSettlementPrice(s, arg); }
void onSettlementPrice(onixs::Handler&, const onixs::Security& s, const onixs::DailyStatistics33Args& arg) override { onSettlementPrice(s, arg); }
void onSettlementPrice(onixs::Handler&, const onixs::Security& s, const onixs::Recovery52EntryArgs& arg) override { onSettlementPrice(s, arg); }
void onSettlementPrice(onixs::Handler&, const onixs::Security& s, const onixs::Recovery38EntryArgs& arg) override { onSettlementPrice(s, arg); }
void onHighestBid(onixs::Handler&, const onixs::Security&, const onixs::SessionStatisticsArgs&) override;
void onLowestOffer(onixs::Handler&, const onixs::Security&, const onixs::SessionStatisticsArgs&) override;
template <typename InterestArgs>
void onOpenInterest(const onixs::Security& sec, const InterestArgs& args);
void onOpenInterest(onixs::Handler&, const onixs::Security& s, const onixs::DailyStatistics49Args& arg) override { onOpenInterest(s, arg); }
void onOpenInterest(onixs::Handler&, const onixs::Security& s, const onixs::DailyStatistics33Args& arg) override { onOpenInterest(s, arg); }
void onOpenInterest(onixs::Handler&, const onixs::Security& s, const onixs::Recovery52EntryArgs& arg) override { onOpenInterest(s, arg); }
void onOpenInterest(onixs::Handler&, const onixs::Security& s, const onixs::Recovery38EntryArgs& arg) override { onOpenInterest(s, arg); }
template <typename SessionArgs>
void onSessionOpeningPrice(const onixs::Security&, const SessionArgs&);
template <typename RecoveryArgs>
void onRecoveryOpeningPrice(const onixs::Security& sec, const RecoveryArgs& args);
void onOpeningPrice(onixs::Handler&, const onixs::Security& s, const onixs::SessionStatistics51Args& arg) override { onSessionOpeningPrice(s, arg); }
void onOpeningPrice(onixs::Handler&, const onixs::Security& s, const onixs::SessionStatistics35Args& arg) override { onSessionOpeningPrice(s, arg); }
void onOpeningPrice(onixs::Handler&, const onixs::Security& s, const onixs::Recovery52EntryArgs& arg) override { onRecoveryOpeningPrice(s, arg); }
void onOpeningPrice(onixs::Handler&, const onixs::Security& s, const onixs::Recovery38EntryArgs& arg) override { onRecoveryOpeningPrice(s, arg); }
template <typename SessionArgs>
void onSessionHighTradePrice(const onixs::Security&, const SessionArgs&);
template <typename RecoveryArgs>
void onRecoveryHighTradePrice(const onixs::Security&, const RecoveryArgs&);
void onHighTradePrice(onixs::Handler&, const onixs::Security& s, const onixs::SessionStatistics51Args& arg) override { onSessionHighTradePrice(s, arg); }
void onHighTradePrice(onixs::Handler&, const onixs::Security& s, const onixs::SessionStatistics35Args& arg) override { onSessionHighTradePrice(s, arg); }
void onHighTradePrice(onixs::Handler&, const onixs::Security& s, const onixs::Recovery52EntryArgs& arg) override { onRecoveryHighTradePrice(s, arg); }
void onHighTradePrice(onixs::Handler&, const onixs::Security& s, const onixs::Recovery38EntryArgs& arg) override { onRecoveryHighTradePrice(s, arg); }
template <typename SessionArgs>
void onSessionLowTradePrice(const onixs::Security&, const SessionArgs&);
template <typename RecoveryArgs>
void onRecoveryLowTradePrice(const onixs::Security&, const RecoveryArgs&);
void onLowTradePrice(onixs::Handler&, const onixs::Security& s, const onixs::SessionStatistics51Args& arg) override { onSessionLowTradePrice(s, arg); }
void onLowTradePrice(onixs::Handler&, const onixs::Security& s, const onixs::SessionStatistics35Args& arg) override { onSessionLowTradePrice(s, arg); }
void onLowTradePrice(onixs::Handler&, const onixs::Security& s, const onixs::Recovery52EntryArgs& arg) override { onRecoveryLowTradePrice(s, arg); }
void onLowTradePrice(onixs::Handler&, const onixs::Security& s, const onixs::Recovery38EntryArgs& arg) override { onRecoveryLowTradePrice(s, arg); }
//
// Discover securities
@@ -190,4 +194,345 @@ private:
};
//////////////////////////////////////////
// Template Member Function Definitions
//////////////////////////////////////////
template <class Definition>
void set_security_common(const Definition& def, FixedSecurity& fsec) {
fsec.numeric_id = def.securityId();
fsec.symbol(def.asset().items(), def.asset().size());
fsec.cfi_code(def.cfiCode().items(), def.cfiCode().size());
fsec.alt_symbol(def.securityGroup().items(), def.securityGroup().size());
fsec.security_desc(def.symbol().items(), def.symbol().size());
fsec.exchange = api::Venue::VENUE_GLBX;
// tickRule not present in futures
fsec.cme_market_segment_id = def.marketSegmentId();
fsec.display_factor = def.displayFactor().exponent() + floorlog10(def.displayFactor().mantissa());
def.mainFraction(fsec.cme_main_fraction);
def.subFraction(fsec.cme_sub_fraction);
def.priceDisplayFormat(fsec.cme_price_display_format);
}
template <typename InstrumentDefinition>
void MDP3Listener::onFuture(onixs::Handler&, const onixs::Security& osec, const InstrumentDefinition& def) {
tracepoint (bts_trace,trace_order,(char*) "onDefinition.future", _latest_sequence, (uint16_t) _latest_sequence, 0);
const auto& sec = def.message();
auto exchange_id = sec.securityId();
// LOG(md, Info, "onDefinition future {} {}",
// std::string(sec.asset().items(), sec.asset().size()),
// std::string(sec.symbol().items(), sec.symbol().size()));
if (filter_security(exchange_id, sec) != ADD) return;
bts_assert(exchange_id == osec.id());
FixedFutureSecurity fsec;
set_security_common(sec, fsec);
fsec.price_break = 0;
// low/high tick are stored non-premultiplied and multiplied in conversion to api::Secutity
double min_tick = double_of_price(sec.minPriceIncrement(), 0);
fsec.low_tick = fsec.high_tick = min_tick;
onixs::Decimal min_tick_amount;
sec.minPriceIncrementAmount(min_tick_amount);
double min_tick_dbl = double_of_price(min_tick_amount, 0);
fsec.cash_per_point = min_tick_dbl / min_tick / pow10(fsec.display_factor);
auto expiration = date_of_maturity(sec);
fsec.expiration_year = expiration.year;
fsec.expiration_month = expiration.month;
fsec.expiration_day = expiration.day;
add_security(fsec);
}
template <typename InstrumentDefinition>
void MDP3Listener::onOption(onixs::Handler&, const onixs::Security&, const InstrumentDefinition& def) {
tracepoint (bts_trace,trace_order,(char*) "onDefinition.option", _latest_sequence, (uint16_t) _latest_sequence, 0);
const auto& sec = def.message();
auto exchange_id = sec.securityId();
// LOG(Info, MarketData) << "onDefinition option " << exchange_id;
if (filter_security(exchange_id, sec) != ADD) return;
FixedOptionSecurity fsec;
set_security_common(sec, fsec);
auto expiration = date_of_maturity(sec);
fsec.expiration_year = expiration.year;
fsec.expiration_month = expiration.month;
fsec.expiration_day = expiration.day;
onixs::Decimal strike_price;
bts_assert(sec.strikePrice(strike_price));
fsec.strike = double_of_price(strike_price, fsec.display_factor);
onixs::Decimal min_tick, min_tick_amount;
sec.minPriceIncrement(min_tick);
sec.minPriceIncrementAmount(min_tick_amount);
int8_t tick_rule;
if (sec.tickRule(tick_rule)) {
decode_ticks(tick_rule, double_of_price(min_tick, 0), fsec);
}
fsec.cash_per_point = double_of_price(min_tick_amount, 0) / fsec.low_tick / pow10(fsec.display_factor);
fsec.call_put = sec.putOrCall() == onixs::PutOrCall::Call ? api::PUTORCALL_CALL : api::PUTORCALL_PUT;
add_security(fsec);
}
// min_tick specializations
inline onixs::Decimal tick_rule(const onixs::InstrumentDefinitionSpread29& sec) {
return sec.minPriceIncrement();
}
inline onixs::Decimal tick_rule(const onixs::InstrumentDefinitionSpread56& sec) {
onixs::Decimal min_tick;
sec.minPriceIncrement(min_tick);
return min_tick;
}
template <typename InstrumentDefinition>
void MDP3Listener::onSpread(onixs::Handler&, const onixs::Security&, const InstrumentDefinition& spread_args) {
tracepoint (bts_trace,trace_order,(char*) "onDefinition.spread", _latest_sequence, (uint16_t) _latest_sequence, 0);
const auto& sec = spread_args.message();
auto exchange_id = sec.securityId();
// LOG(md, Info, "onDefinition spread {} {}",
// std::string(sec.asset().items(), sec.asset().size()),
// std::string(sec.symbol().items(), sec.symbol().size()));
if (filter_security(exchange_id, sec) != ADD) return;
// Filter out any already expired spreads
auto expiration = date_of_maturity(sec);
if (expiration < datetime::today()) return;
FixedSpreadSecurityL fsec;
set_security_common(sec, fsec);
std::vector<uint32_t> leg_exchange_ids;
leg_exchange_ids.reserve(sec.legs().size());
onixs::Decimal min_tick = tick_rule(sec);
int8_t tick_rule;
if (sec.tickRule(tick_rule)) {
decode_ticks(tick_rule, double_of_price(min_tick, 0), fsec);
}
else {
double mintick = double_of_price(min_tick, 0);
fsec.low_tick = mintick;
fsec.high_tick = mintick;
fsec.price_break = 0;
}
fsec.set_leg_count(sec.legs().size());
for(size_t x = 0; x < fsec.leg_count(); ++x) {
const auto& leg = sec.legs()[x];
onixs::Decimal price;
if (leg.legPrice(price)) {
fsec.legs[x].leg_price = double_of_price(price, fsec.display_factor);
}
onixs::Decimal qty;
if (leg.legOptionDelta(qty)) {
fsec.legs[x].leg_delta = double_of_price(qty, 0);
}
fsec.legs[x].leg_quantity = leg.legRatioQty();
fsec.legs[x].leg_side = leg.legSide() == onixs::LegSide::BuySide ? api::SIDE_BUY : api::SIDE_SELL;
leg_exchange_ids.push_back(leg.legSecurityId());
}
add_security(fsec);
_index.add_spread_legs(fsec.numeric_id, leg_exchange_ids);
}
template <class TBook>
void MDP3Listener::onBookUpdate(const onixs::Security& sec, const TBook& book) {
tracepoint (bts_trace,trace_order,(char*) "onBookUpdate", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto data = _index.get_security(sec.id());
if (data == nullptr) return;
bts_assert(data->id == (uint32_t)sec.id());
auto display_factor = data->handle.security().display_factor;
// Put the data into the cache. Flush at the end of the packet.
auto key = data->handle.key();
auto find_iter = std::find_if(_book_updates.begin(), _book_updates.end(), [key](const BookData& entry) {
return key == entry.handle.key();
});
bool found = find_iter != _book_updates.end();
if (!found) {
_book_updates.emplace_back(data->handle);
}
BookData& cache = found ? *find_iter : _book_updates.back();
// Overwrite all entries every time
size_t bids_size = book.bids().size();
size_t asks_size = book.offers().size();
if (!data->handle.has_depth()) {
bids_size = std::min(bids_size, size_t { 1 });
asks_size = std::min(asks_size, size_t { 1 });
}
for (size_t x = 0; x < bids_size; ++x) {
cache.bids[x] = pricesize_of_price_size(book.bids()[x].price(), display_factor, book.bids()[x].quantity());
}
for (size_t x = 0; x < asks_size; ++x) {
cache.asks[x] = pricesize_of_price_size(book.offers()[x].price(), display_factor, book.offers()[x].quantity());
}
// NaN out the remaining depth
for (size_t x = bids_size; x < COCONUT_MAX_DEPTH; ++x) {
cache.bids[x] = PriceSize::NO_MARKET;
}
for (size_t x = asks_size; x < COCONUT_MAX_DEPTH; ++x) {
cache.asks[x] = PriceSize::NO_MARKET;
}
}
void on_trade(SecurityData* data, const onixs::Decimal& price, int size, onixs::AggressorSide::Enum agside, const onixs::Timestamp& onixs_date);
template <typename TradeRecovery>
void MDP3Listener::onTradeRecovery(const onixs::Security& sec, const TradeRecovery& arg) {
tracepoint (bts_trace,trace_order,(char*) "onTrade.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != NULL) {
int size = 0;
arg.entry().entrySize(size);
onixs::Decimal price;
arg.entry().entryPx(price);
on_trade(data, price, size, onixs::AggressorSide::NoAggressor, arg.message().transactTime());
}
}
template <typename TradeSummary>
void MDP3Listener::onTradeSummary(const onixs::Security& sec, const TradeSummary& arg) {
tracepoint (bts_trace,trace_order,(char*) "onTrade.summary", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != NULL) {
auto size = arg.entry().entrySize();
onixs::Decimal price = arg.entry().entryPx();
onixs::AggressorSide::Enum agside = onixs::AggressorSide::NoAggressor;
arg.entry().aggressorSide(agside);
on_trade(data, price, size, agside, arg.message().transactTime());
}
}
template <typename RecoveryEntryArgs>
void MDP3Listener::onElectronicVolume(const onixs::Security& sec, const RecoveryEntryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onElectronicVolume.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data) {
int32_t size;
if (args.entry().entrySize(size)) {
data->electronic_volume = size;
}
}
}
template <typename StatisticsArgs>
void MDP3Listener::onSettlementPrice(const onixs::Security& sec, const StatisticsArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onSettlementPrice.daily", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::Decimal price;
onixs::Timestamp time;
args.entry().entryPx(price);
args.entry().tradingReferenceDate(time);
auto display_factor = data->handle.security().display_factor;
data->handle.update_settlement(
utils::TimeStamp::now(),
double_of_price(price, display_factor),
date_of_timestamp(time));
}
}
template <typename InterestArgs>
void MDP3Listener::onOpenInterest(const onixs::Security& sec, const InterestArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onOpenInterest.daily", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::Decimal price;
args.entry().entryPx(price);
auto display_factor = data->handle.security().display_factor;
data->handle.update_open_interest(utils::TimeStamp::now(), double_of_price(price, display_factor));
}
}
template <typename SessionArgs>
void MDP3Listener::onSessionOpeningPrice(const onixs::Security& sec, const SessionArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onOpeningPrice.session", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::Decimal price = args.entry().entryPx();
onixs::Timestamp time = args.message().transactTime();
auto display_factor = data->handle.security().display_factor;
data->handle.update_opening(
utils::TimeStamp::now(),
double_of_price(price, display_factor),
date_of_timestamp(time));
}
}
template <typename RecoveryArgs>
void MDP3Listener::onRecoveryOpeningPrice(const onixs::Security& sec, const RecoveryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onOpeningPrice.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
onixs::Decimal price;
args.entry().entryPx(price);
onixs::Timestamp time;
args.entry().tradingReferenceDate(time);
auto display_factor = data->handle.security().display_factor;
data->handle.update_opening(
utils::TimeStamp::now(),
double_of_price(price, display_factor),
date_of_timestamp(time));
}
}
template <typename SessionArgs>
void MDP3Listener::onSessionHighTradePrice(const onixs::Security& sec, const SessionArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onHighTradePrice.session", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
data->handle.update_session_high(
utils::TimeStamp::now(),
double_of_price(args.entry().entryPx(), display_factor));
}
}
template <typename RecoveryArgs>
void MDP3Listener::onRecoveryHighTradePrice(const onixs::Security& sec, const RecoveryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onHighTradePrice.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
onixs::Decimal price;
args.entry().entryPx(price);
data->handle.update_session_high(
utils::TimeStamp::now(),
double_of_price(price, display_factor));
}
}
template <typename SessionArgs>
void MDP3Listener::onSessionLowTradePrice(const onixs::Security& sec, const SessionArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onLowTradePrice.session", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
data->handle.update_session_low(
utils::TimeStamp::now(),
double_of_price(args.entry().entryPx(), display_factor));
}
}
template <typename RecoveryArgs>
void MDP3Listener::onRecoveryLowTradePrice(const onixs::Security& sec, const RecoveryArgs& args) {
tracepoint (bts_trace,trace_order,(char*) "onLowTradePrice.recovery", _latest_sequence, (uint16_t) _latest_sequence, 0);
auto* data = _index.get_security(sec.id());
if (data != nullptr) {
auto display_factor = data->handle.security().display_factor;
onixs::Decimal price;
args.entry().entryPx(price);
data->handle.update_session_low(
utils::TimeStamp::now(),
double_of_price(price, display_factor));
}
}
}}//namespace
@@ -0,0 +1,112 @@
#include "lib/utils/bts_assert.h"
#include "lib/md/coconut2.h"
#include "onixs.h"
#include <vector>
#include <atomic>
#include <array>
namespace bts {
namespace md {
inline PriceSize pricesize_of_price_size(const onixs::Decimal price, int8_t display_factor, Size size) {
PriceSize result(price.mantissa(), price.exponent() + display_factor, size);
return result;
}
template <class Price>
double double_of_price(const Price& price, int8_t display_factor) {
// order of multiplication is important because of floating point error
return (price.mantissa() * pow10(price.exponent())) * pow10(display_factor);
}
inline void decode_ticks(int vtt, double mintick, FixedSecurity& dest) {
switch(vtt) {
default:
case 0:
dest.low_tick = mintick;
dest.high_tick = mintick;
dest.price_break = 0;
break;
case 1:
dest.price_break = 500;
dest.low_tick = 5;
dest.high_tick = 10;
break;
case 2:
dest.price_break = 5;
dest.low_tick = 0.5;
dest.high_tick = 1;
break;
case 3:
dest.price_break = 10;
dest.low_tick = 1;
dest.high_tick = 2;
break;
case 4:
dest.price_break = 500;
dest.low_tick = 5;
dest.high_tick = 25;
break;
case 10:
dest.price_break = 300;
dest.low_tick = 5;
dest.high_tick = 25;
break;
case 11:
dest.price_break = 300;
dest.low_tick = 5;
dest.high_tick = 10;
break;
case 12:
dest.price_break = 5;
dest.low_tick = 0.25;
dest.high_tick = 0.5;
break;
}
}
inline int floorlog10(int64_t m) {
bts_assert(m >= 0);
if (m < 10) return 0;
if (m < 100) return 1;
if (m < 1000) return 2;
if (m < 10000) return 3;
if (m < 100000) return 4;
if (m < 1000000) return 5;
if (m < 10000000) return 6;
if (m < 100000000) return 7;
if (m < 1000000000) return 8;
if (m < 10000000000) return 9;
if (m < 100000000000) return 10;
if (m < 1000000000000) return 11;
if (m < 10000000000000) return 12;
if (m < 100000000000000) return 13;
if (m < 1000000000000000) return 14;
if (m < 10000000000000000) return 15;
if (m < 100000000000000000) return 16;
if (m < 1000000000000000000) return 17;
return 19;
}
inline datetime::LLDateTime ll_of_timestamp(const onixs::Timestamp& ts) {
return datetime::ll_from_parts(ts.year(), (int)ts.month(), ts.day(), ts.hour(), ts.minute(), ts.second(), ts.millisecond());
}
inline datetime::Date date_of_timestamp(const onixs::Timestamp& ts) {
return datetime::Date(ts.year(), (int)ts.month(), ts.day());
}
template <class Definition>
datetime::Date date_of_maturity(const Definition& def) {
for (const auto& event : def.events()) {
if (event.eventType() == onixs::EventType::LastEligibleTradeDate) {
return date_of_timestamp(event.eventTime());
}
}
return datetime::Date();
}
}}//namespace
@@ -299,6 +299,12 @@ unique_ptr<onixs::Handler> MDP3Main::prepare_handler(const string& channel_id) {
loggerSettings.filename(log_path() + "/log_" + channel_id);
loggerSettings.severityLevel((onixs::LogSeverity::Enum)options.onixs_log_mode());
logger = new onixs::FileLogger(loggerSettings);
if (options.onixs_log_mode() == CMEOptions::Debug) {
// trace all the things
settings.debugLogging().traceBooks(true);
settings.debugLogging().traceFeeds(true);
settings.debugLogging().traceMessages(onixs::MessageTracing::FixFormat);
}
}
@@ -218,9 +218,14 @@ void ExecutionGateway::on_exe_report(
: api::orderman::MANUAL_ORDER_INDICATOR_YES;
str_to(msg.get<fix::OrderID>(), &data->exchange_order_id);
if (msg.has<fix::Price>())
data->price = securities::decode_exchange_price(
*sec, Price(msg.get<fix::Price>()));
if (msg.has<fix::Price>()) {
if (data->leg_security)
data->price = securities::decode_exchange_price(
*data->leg_security, Price(msg.get<fix::Price>()));
else
data->price = securities::decode_exchange_price(
*sec, Price(msg.get<fix::Price>()));
}
else
data->price = Price(os::nan());
@@ -21,14 +21,14 @@ public:
net_pos_new = net_pos + quantity.value();
else if(side == api::Side::SIDE_SELL)
net_pos_new = net_pos - quantity.value();
if (net_pos_new > long_pos_limit){
if (net_pos_new > long_pos_limit && side==api::Side::SIDE_BUY){
out_res.ok = false;
if (is_security_level)
out_res.error_msg = fmt::format("Security Long Position (Max {} Current {})", long_pos_limit, net_pos);
else
out_res.error_msg = fmt::format("Product Long Position (Max {} Current {})", long_pos_limit, net_pos);
}
else if (net_pos_new < short_pos_limit){
else if (net_pos_new < short_pos_limit && side==api::Side::SIDE_SELL){
out_res.ok = false;
if (is_security_level)
out_res.error_msg = fmt::format("Security Short Position (Max {} Current {})", short_pos_limit, net_pos);
@@ -271,9 +271,17 @@ void IcebergOrder::on_child_order_update(OrderStateUpdateEvent const &ev) {
break;
}
case ORDER_STATUS_CANCELED:
LOG(OrderMan, Info,
"Unexpected cancel of child {} in Iceberg Order {}. Canceling "
"parent",
ev.key.value(),
key().value());
transition(ORDER_STATUS_CANCELED);
break;
case ORDER_STATUS_DISCONNECTED:
case ORDER_STATUS_REJECTED_BY_SPARK:
case ORDER_STATUS_CANCELED:
case ORDER_STATUS_ERROR:
me->child.clear();
transition(ORDER_STATUS_ERROR, "Unexpected child order state");
@@ -588,6 +588,12 @@ void NativeOrder::on_exe_report(const NewExecutionReportEvent &er) {
auto &state = me->state;
auto &native_state = get_native_state(state);
if (er.data->leg_security) {
LOG(OrderMan, Diag,
"Ignoring leg execution report for order {}", key().value());
return;
}
if (native_state.last_msg_seq_num() > er.data->msg_seq_num) {
LOG(OrderMan, Warn,
"Ignoring already seen execution report {} in order {}",
@@ -73,7 +73,7 @@ void ErrorReportServer::send_report(
}
// log error for visibility
LOG(Gen, Error, "Support request from {} - {} \n{}", request.user(), request.contact(), request.user_description());
LOG(Gen, Error, "Support request from {} - {} {}", request.user(), request.contact(), request.user_description());
ErrorResponse r;
reply(r);
+1 -1
View File
@@ -139,7 +139,7 @@ body {
.is-main-control-bar {
margin:2rem 3rem 0 0;
overflow: hidden;
text-align: center;
//text-align: center;
.button {
margin-left: 1em;
}
+2 -2
View File
@@ -24,8 +24,8 @@ let init (context:ServiceContext.ServiceContext) =
mdRelayExpNameData = Array.empty<ExpirationNameList>
scratch = emptyAccount
previousScratch = emptyAccount
AllValue = ""
AllValueDisplay = ""
AllValue = "*"
AllValueDisplay = "All"
OptionsMenuOpen = ""
ConfirmModal = "", (Msg.SelectTab General)
SelectedClipLimits = []
+21 -11
View File
@@ -69,10 +69,12 @@ let GetSymbolArray (model:Model) =
|> Array.distinct
let GetFilteredSymbolArray (model:Model) (remove:string []) =
Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|> Array.filter (fun elm -> (not <| Array.exists (fun e -> elm = e) remove))
|> Array.distinct
let a = (Array.map<bts.api.Product, string> (fun a -> a.symbol ) model.mdRelayProductData
|> Array.filter (fun elm -> (not <| Array.exists (fun e -> elm = e) remove))
|> Array.distinct)
match a.Length with
| 0 -> a
| _ -> [ a; [|model.AllValueDisplay|] ] |> Array.concat
let limitFilter (positionLimit:AccountSecurityPositionLimitUnit option) (clipLimit:AccountSecurityClipLimitUnit option) allValueDisplay (array:'a []) =
match positionLimit, clipLimit with
@@ -193,7 +195,11 @@ let clipLimitsView model dispatch =
&& (elm.security.securityType = limit.security.securityType)
)
model.scratch.securityClipLimits.limit
|> Array.map (fun (elm:AccountSecurityClipLimitUnit) -> elm.security.securitySymbol)
|> Array.map (fun (elm:AccountSecurityClipLimitUnit) ->
match (elm.security.securitySymbol = model.AllValue) with
| true -> model.AllValueDisplay
| false -> elm.security.securitySymbol
)
@@ -223,7 +229,7 @@ let clipLimitsView model dispatch =
)
TableControl.Cell (Fields.enumSelect<string>
""
limit.security.securitySymbol
(match (limit.security.securitySymbol = model.AllValue) with | true -> model.AllValueDisplay | false -> limit.security.securitySymbol)
(GetFilteredSymbolArray model <| (getUsedSymbolNames limit))
[]
(fun value -> ((limit, (changeSymbol limit value)) |> ClipLimits |> dispatch))
@@ -262,7 +268,7 @@ let clipLimitsView model dispatch =
div [ ClassName "column is-size-7 has-text-grey-mid is-help-text"; ]
[str "Clip limits can be set for one security, for all securities in a product (by selecting \"All\" for securities), or for all products within a security type (by selecting \"All\" for both symbol and security)"]
]
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus" Button.Enabled addRow)
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus-circle" Button.Enabled addRow)
]
let productLimits model dispatch =
@@ -362,7 +368,11 @@ let productLimits model dispatch =
&& (elm.product.securityType = limit.product.securityType)
)
model.scratch.productPositionLimits
|> Array.map (fun (elm:AccountProductPositionLimitUnit) -> elm.product.securitySymbol)
|> Array.map (fun (elm:AccountProductPositionLimitUnit) ->
match (elm.product.securitySymbol = model.AllValue) with
| true -> model.AllValueDisplay
| false -> elm.product.securitySymbol
)
let rws:TableControl.row list =
@@ -390,7 +400,7 @@ let productLimits model dispatch =
)
TableControl.Cell (Fields.enumSelect<string>
""
limit.product.securitySymbol
(match (limit.product.securitySymbol = model.AllValue) with | true -> model.AllValueDisplay | false -> limit.product.securitySymbol)
(GetFilteredSymbolArray model (getUsedSymbolNames limit))
[]
(fun value -> ((limit, (changeSymbol limit value)) |> ProductLimits |> dispatch))
@@ -433,7 +443,7 @@ let productLimits model dispatch =
div [ ClassName "column is-size-7 has-text-grey-mid is-help-text" ]
[str "This limits the net position for a product (i.e. accumulated position over all securities belonging to a product). This can be set for one product, or for all products within a security type by selecting \"All\" for symbol"]
]
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus" Button.Enabled addRow)
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus-circle" Button.Enabled addRow)
br []
]
@@ -551,7 +561,7 @@ let securityLimitsView model dispatch =
div [ ClassName "column is-size-7 has-text-grey-mid is-help-text" ]
[str "Optionally, the net position for one or more securities can also be limited. For example, the Product Limits can be set to restrict the Max Net Long Position across all ES futures to 10,000 contracts, but Security Limits can be used to restrict the ES Jun future to 500 only"]
]
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus" Button.Enabled addRow)
TableControl.createDataTable (Some headerRow) rws (Button.button "Add" "" "plus-circle" Button.Enabled addRow)
]
let LimitsView model dispatch =
+5 -3
View File
@@ -176,10 +176,12 @@ let applyUpdate (field:UserField) (user:BTSUser) =
| Name n -> { user with name = n }
| Password p -> { user with password = p }
| IsActive ia -> { user with isActive = ia }
| OperatorID oid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with operatorId = oid }}}}
| ATSOperatorID atsoid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with atsOperatorId = atsoid }}}}
| CMEOperatorID oid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with operatorId = oid }}}}
| CMEATSOperatorID atsoid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with atsOperatorId = atsoid }}}}
| SimOperatorID oid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with simData = { user.userData.exchangeUserData.simData with operatorId = oid }}}}
| SMPID smpid -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with smpId = smpid }}}}
| Location loc -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with location = loc }}}}
| CMELocation loc -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with location = loc }}}}
| SimLocation loc -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with simData = { user.userData.exchangeUserData.simData with location = loc }}}}
| SMPInstruction smpi -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with smpInstruction = smpi }}}}
| MaxOrderRatePerConnection morpc -> { user with userData = { user.userData with exchangeUserData = { user.userData.exchangeUserData with cmeData = { user.userData.exchangeUserData.cmeData with maxOrderRatePerConnection = morpc }}}}
| MiscTags map ->
+5 -3
View File
@@ -13,10 +13,12 @@ type UserField =
| Name of string
| Password of string
| IsActive of bool
| OperatorID of string
| ATSOperatorID of string
| CMEOperatorID of string
| CMEATSOperatorID of string
| SimOperatorID of string
| SMPID of string
| Location of string
| CMELocation of string
| SimLocation of string
| SMPInstruction of string
| MaxOrderRatePerConnection of string
| MiscTags of JSMap<string>
+11 -2
View File
@@ -146,19 +146,28 @@ let mdEntitlementsTabView (model:Model) (dispatch:Msg->Unit) =
let orderRoutingTabView (model:Model) (dispatch:Msg->Unit) =
let cmeData = model.scratchUser.userData.exchangeUserData.cmeData
let simData = model.scratchUser.userData.exchangeUserData.simData
div []
[
h2 [Class "is-size-3"] [ str "CME" ]
div []
[
Fields.text "Operator ID" cmeData.operatorId [] (OperatorID >> UpdateField >> dispatch)
Fields.text "Operator ID" cmeData.operatorId [] (CMEOperatorID >> UpdateField >> dispatch)
//Fields.text "ATS Operator ID" cmeData.atsOperatorId [] (ATSOperatorID >> UpdateField >> dispatch)
Fields.text "SMP ID" cmeData.smpId [] (SMPID >> UpdateField >> dispatch)
Fields.mapSelect "SMP Instruction" State.SMPInstructionMap None (Some cmeData.smpInstruction) (SMPInstruction >> UpdateField >> dispatch)
Fields.text "Location" cmeData.location [] (Location >> UpdateField >> dispatch)
Fields.text "Location" cmeData.location [] (CMELocation >> UpdateField >> dispatch)
//Fields.text "Max Order Rate Per Connection" cmeData.maxOrderRatePerConnection [] (MaxOrderRatePerConnection >> UpdateField >> dispatch)
//Fields.map "Misc Tag Mapping" cmeData.miscTags [] (MiscTags >> UpdateField >> dispatch)
]
br []
h2 [Class "is-size-3"] [ str "Sim" ]
div []
[
Fields.text "Operator ID" simData.operatorId [] (SimOperatorID >> UpdateField >> dispatch)
Fields.text "Location" simData.location [] (SimLocation >> UpdateField >> dispatch)
]
]
let userControls (model:Model) (dispatch:Msg->Unit) =
@@ -1,12 +1,7 @@
This test verifies that security position limits are enforced correctly. (Position limits are
enforced (per account) at the product level and optionally at the security level)
0. Clear up your orders and fills so we don't have any lingering positions
(run rm -r orders and rm -r fills from /sparkdata/data/databases). Restart your sparkd
1. Pick a future, lets say ESU8 and an account, lets say ACC A1.
2. In the Spark Admin, select the default account for your user, and enter big clip limits so that
enter big clip limits so that
clip limits don't interfere with this test.
3. Go to the Position limits and remove all entries at both the product and security level
+1 -1
View File
@@ -15,7 +15,7 @@ e. Disable all Quote, Pre-Hedge, Post-Hedge Parameters for both legs
2. Make sure there is no market for these contracts. If there is, cancel those orders.
3. For the first leg (non quoting) enter 1 lot bid orders from 18.230 to 18.250 at 0.05 intervals, and 1 lot ask orders from 18.300 to 18.320.
3. For the first leg (non quoting) enter 1 lot bid orders from 18.230 to 18.250 at 0.005 intervals, and 1 lot ask orders from 18.300 to 18.320.
Make sure these are reflected in the ladder market data (when the ladder has no market, we will need to enter the first order via an Order Ticket)
4. For the second leg (quoting leg) enter a 5 lot bid order at 18.5 and a 5 lot sell order at 18.525. Make sure both the markets show up.
+10 -13
View File
@@ -1,24 +1,21 @@
This test verifies that clip limits are followed, and rule precedence works correctly
1. Pick a future, lets say SIZ1.
Use the SIM exchange for all steps.
2. In the Spark Admin, go to accounts and select the default account for your user (let say ACC A1).
Go to Position Limits and enter large values for the Product Limits and remove all rows for the Security Limits
0. Pick a future, let's say CLX8, and veryify you can enter orders for it
4. Now go to Clip Limits and delete all entries.
1. Pick another future, lets say BZQ8.
2. In the Spark Admin, go to accounts and select the default account for your user (let say ACC A).
4. Now go to Limits, Clip Limits and delete the BZ future rows in the SIM exchange
5. Enter an order and it should fail with a message that should tell exactly why. Make sure the orderbook and the
ladder show the message.
6. Now enter a Clip Limit for SIZ1.
6. Now enter a Clip Limit for BZ.
Enter a Clip Size of 10. Make sure orders > 10 are rejected and < 10 are allowed.
7. Now enter an order for another future, lets say SIN1. Enter a 1 lot and it should be rejected.
7. Delete the BZ spread clip limits row
8. Enter another rule, GLBX, FUTURES, All, All and enter a clip limit of 100.
9. Now try the SIN1 order again. Verify it does the right thing for the clip limit you entered in 8.
10. Verify that SIZ1 is still controlled by a clip size of 10.
11. Enter a future spread order. It should be rejected since we don't have any clip limits for futures.
8. Verify you can no longer enter BZ spread trades, but you can still enter BZ future trades
@@ -1,19 +1,21 @@
This test verifies that product position limits are enforced correctly. (Position limits are
enforced at both the security and account level)
0. Clear up your orders and fills so we don't have any lingering positions
(run rm -r orders and rm -r fills from /sparkdata/data/databases). Restart your sparkd
Use SIM for all steps of the test
0. Clear up your orders, fills and admin db so we don't have any lingering positions
(run rm -r orders fills admin from /sparkdata/data/databases). Restart your sparkd
1. Pick 2 futures, lets say SIU8 and SIZ8
2. In the Spark Admin, select the default account for your user (lets say ACC A1)
and enter big clip limits so that clip limits don't interfere with this test.
2. In the Spark Admin, select the default account for your user (lets say ACC A)
and enter a big clip, say 500000, so that clip limits don't interfere with this test.
3. Go to the Position limits and remove all entries at both the product and security level
4. Enter an SIU8 order. It should be rejected. Make sure the rejection message makes sense.
5. Enter a product level rule for GLBX, Future, SI, 60, 120.
5. Enter a product level rule for SIM, Future, SI, 60, 120.
6. Send 3 10 lot buys for both the futures. Make sure they go through.
@@ -18,19 +18,3 @@ fills). Cancel all the orders.
4. Verify that the limits set in 2. work for spreads. Cancel all the orders.
5. Make these product limits 1,000,000 to make them irrelevant
ii:
6. For security limits enter long 10 and short 20 for SIU8 and SIZ8 futures respectively and 50 and 60 for
the SIU8-SIZ8 spread.
7. Enter a 5 lot buy for SIU8-SIZ8. This 5 should count toward SIU8 long limit (which is 10). Enter
a 5 lot SIU8 buy, which should be allowed but a subsequent 1 lot buy should be rejected. Similiary, the
spreader order should count toward the SIZ8 short limit of 20. Enter a 15 lot sell on SIZ8, and a subsequent
1 lot should be rejected.
8. Cancel all orders
iii:
Enter a 11 lot spread order. It should be rejected because of the 10 lot limit on SIU8.
@@ -13,7 +13,7 @@ makes sense.
ladder dropdown and uncheck "Is Active").
6. Verify that orders going into that account are rejected and that the rejection message
is clear.
is clear .
7. Verify that the account's "Is Active" is correctly applying to that account only, i.e. you
can still enter orders into other accounts
+5 -1
View File
@@ -13,4 +13,8 @@ thresh then cancel the order else do nothing
- Verify that orders cancel if they end up working at an inside market with less than threshold size
Goto Label l and test a sell
Now do this test again with "Enable Hedge" checked and hedge ticks set to 1, hedge type set to limit
This should modify the behavior such that the algorithm will send a limit order on the opposite
side of the market, one tick away from fill price in a quantity equivalent to the amount of the fill
+1 -1
View File
@@ -1,7 +1,7 @@
0. This needs sim market data **not** to be merged with replay (or cert), so we can create our own markets.
1. Bring up a ladder, lets say in SIN1 (does not matter which security)
2. Enter a 5 lot limit order at 20.00 (if there are no markets use the M View and the ticket to enter the order)
2. Enter a 5 lot limit order at 20.00 (buy) (if there are no markets use the M View and the ticket to enter the order)
3. In the dropdown select Trigger. For the trigger details, enter the following :
a. Trigger Price Type : Bid
b. Order Price : 19.975
-2
View File
@@ -5,5 +5,3 @@ Go to Help -> About
Marvel at our About Box
Ask Michael to insert a link to our website
+6 -6
View File
@@ -13,9 +13,9 @@ JetFIX {
connection {
# Exchange simulator connection
name: "sim"
platform: GLBX
socket_connect_host_ip: "127.0.0.1"
socket_connect_port: @Ports.exchange_sim_fix_port
platform: SIM
socket_connect_host_ip: "127.0.0.1"
socket_connect_port: @Ports.exchange_sim_fix_port
sender_compid: "SPARK" # this is the FIX session name
sender_subid: "BTS"
target_compid: "BTS"
@@ -24,11 +24,11 @@ JetFIX {
start_time: "07:52:00"
raw_data: "1JE9X"
use_cme_secure_logon: false
seconds_to_pause : 1
seconds_to_pause : 1
# max of 3 order operations (creates or updates only) for each 5 second
max_order_msgs_per_window: 3
window_duration_msecs: 5000
max_order_msgs_per_window: 3
window_duration_msecs: 5000
}
}
}
+1 -1
View File
@@ -8,6 +8,6 @@ Type some stuff in the description box and a fake phone number, check include sc
Click send.
Verify that a folder was created on the server under ~/sparkdata/data/error_reports/ with the information you typed in.
If you left the screenshot checkmark checked copy the screenshot.jpeg to ~/www/ and look at it. Make sure it is your desktop not mine.
If you left the screenshot checkmark checked copy the screenshot.jpeg to ~/sparkdata/www/ and view it from http://sparkvm:8000/files/
+25
View File
@@ -11,3 +11,28 @@ Test modification: Change price, commit, change size, commit, change price and s
Test fill: Cross an order, make sure fill is accurately reflected
If you tested cancellation and modification through the side-bar, now do the same through the context menu
Test sorting
Recreate Testing
----------------
After the above, you should have a variety of order statuses in your order book.
Right click on a Completed order
The Recreate menu item should remain disabled
Left click and drag over over a series of orders, at least one of them being in Canceled status
The Recreate menu item should now be available
Click Recreate from the tool well
Orders should be submitted for all top-level orders (no children of any kind) that have a status of cancelled.
The Order should be placed at the same price as the original order
The order should be placed with a Qty of (Qty - Filled Qty)
Left click on a cancelled child order of a parent-child order type
The Recreate menu item should remain disabled
Left click on a cancelled parent order of a parent-child order type
Click Recreate from the tool well
The original order heirarchy will again be working
Orders should be placed at the same price as their respective original order
The top parent order should be placed with a Qty of (Qty - Filled Qty)
* Note, child orders will *NOT* be recreated with a Qty of (Qty - Filled Qty) at this time since their intermediate fill status is unknown to their parent.
+1 -1
View File
@@ -20,7 +20,7 @@ order for SIN9 since the SIF9 hedge leg still doesnt have a market. Enter a 1 lo
Re-enter the SIK9 order, 10 lots at 20.200 and the quoting order should appear as well.
5. Now lift the quoting leg ask with a 1 lot buy order at the same price. Make sure hedges are sent (and filled)
for all the 3 hedging legs. SIH9 should have no market now and hence we should have no quoting order.
for all the 3 hedging legs. SIF9 should have no market now and hence we should have no quoting order.
6. Enter a 10 lot sell order at 20.000 for SIF9. This should result in a 9 lot quoting order.
+36
View File
@@ -0,0 +1,36 @@
$known_good = @{
"6A" = 1000
"6B" = 625
"6D" = 1000
"6E" = 1250
"6J" = 1250
"CL" = 1000
"EMD" = 100
"ES" = 50
"GC" = 100
"GE" = 2500
"HE" = 400
"HG" = 5000
"HO" = 42000
"LE" = 400
"M6E" = 125
"NG" = 100
"NQ" = 20
"QM" = 500
"RB" = 42000
"RTY" = 50
"SI" = 5000
"VX" = 1000
"YI" = 10
"YM" = 5
"ZB" = 1000
"ZC" = 50
"ZF" = 1000
"ZL" = 600
"ZM" = 100
"ZN" = 1000
"ZQ" = 4167
"ZS" = 50
"ZT" = 2000
"ZW" = 50
}
+17 -39
View File
@@ -1,43 +1,9 @@
$known_good = @{
"6A" = 1000
"6B" = 625
"6D" = 1000
"6E" = 1250
"6J" = 1250
"M6E" = 125
"NQ" = 20
"ES" = 50
"YM" = 5
"RTY" = 50
"VX" = 1000
"EMD" = 100
"GE" = 2500
"ZB" = 1000
"ZN" = 1000
"ZF" = 1000
"ZT" = 2000
"ZQ" = 4167
"SI" = 50
"YI" = 10
"GC" = 100
"HG" = 250
"CL" = 1000
"NG" = 100
"HO" = 420
"QM" = 500
"RB" = 420
"ZC" = 50
"ZS" = 50
"ZW" = 50
"LE" = 400
"HE" = 400
"ZM" = 100
"ZL" = 600
}
# Dot sourcing the reqs file will make
. .\Generate-Cpps-reqs.ps1
$cme_file_url = "ftp://ftp.cmegroup.com/pub/fprf/csv/cmeg.fut.prf.csv"
$csv_save_path = ".\cmeg.fut.prf.csv"
$output_file = ".\cpp_out.txt"
$output_file = ".\cpp_config.conf"
# turn off console update progress while downloading
$CurrentProgressPref = $ProgressPreference;
@@ -47,11 +13,23 @@ $ProgressPreference = $CurrentProgressPref
$a = Import-Csv $csv_save_path
$b = $a | select Sym, Mult | Group Sym | Sort Name
@"
# Generated by automated script. DO NOT EDIT!
# source: tools/cpp_helper/generate-cpps.ps1
"@ | out-file -Encoding ascii $output_file
"CppConfig`n{`n`tvalue`n`t{" | out-file -Encoding ascii $output_file -Append
$b | % {
if ($known_good.ContainsKey($_.Group[0].Sym)) {
$cpp = $known_good[$_.Group[0].Sym]
} else {
$cpp = $_.Group[0].Mult
}
"cpp_entry {{ `n`tkey: `"{0}`"`n`tvalue: {1}`n}}" -f $_.Group[0].Sym, $cpp } `
| out-file -Encoding ascii $output_file
"`t`tcpp_entry {{ key: `"{0}`" value: {1} }}" -f $_.Group[0].Sym, $cpp } `
| out-file -Encoding ascii $output_file -Append
"`t}`n}" | out-file -Encoding ascii $output_file -Append
Remove-Item $csv_save_path -Force
# You can now copy the output file to defaults assuming all looks good
# Copy-Item .\cpp_config.conf ..\..\src\lib\config\defaults\ -Force
# Remove-Item cpp-config.conf