Compare commits

...
45 Commits
Author SHA1 Message Date
Taha Afzal b61e18d10e CPP logic 2020-06-19 00:44:13 -04:00
John Colvin 90b2607f86 pnl window symbol filter items are sorted 2020-06-18 13:06:41 -05:00
John Colvin e452697088 remove struct contraint on TKey in KeyedMultiSelector, and TableUpdateItemsFilter 2020-06-18 12:50:23 -05:00
John Colvin 1988443497 fix pnl symbol filter (was checking the security.Symbol instead of the 'pnl_symbol') 2020-06-18 12:40:07 -05:00
John Colvin 3f33627f00 add pnl_cpp_tuple extension method bones (taha will implement) 2020-06-18 12:14:44 -05:00
John Colvin 0610612ae6 make PNLData.with a member method instead of extension so it isn't
passed by value (it's a large struct)
2020-06-18 11:35:00 -05:00
John Colvin efcf78bb95 pnl window restores fill/market price decimal format when workspace loaded 2020-06-18 11:28:17 -05:00
John Colvin 03678e79a5 PNLSettings.cs line endings (need to figure out why they keep changing) 2020-06-18 11:00:32 -05:00
Taha Afzal c15a364496 Merge branch 'DJ_ICE_pnl_decimals' into DJ_ICE 2020-06-17 23:50:17 -04:00
Taha Afzal d8ec713dc5 Spreads in PNL show under a different symbol 2020-06-17 23:22:33 -04:00
Taha Afzal daaa7311a0 Merge branch 'DJ_ICE_pnl_symbol' into DJ_ICE_cpp_mult 2020-06-17 22:58:10 -04:00
Taha Afzal f893af1930 Strip Legs are not counted toward futures 2020-06-17 22:57:08 -04:00
Taha Afzal 6ec413c516 Dictinction bw spread legs and strip legs 2020-06-17 15:50:06 -04:00
John Colvin a2a0d88a81 pnl window disposes filters of type IDisposable 2020-06-17 12:39:59 -05:00
John Colvin 7a4dca9589 PNLWindow uses special pnl_symbol (taha will implement pnl_symbol method later, returns regular symbol in meantime) 2020-06-17 12:30:01 -05:00
John Colvin b21cd12cea copy AppendTable extension from another branch 2020-06-17 12:24:58 -05:00
John Colvin ec0b726751 ladder mid tick rounds down for negative numbers (still rounds up for positive) 2020-06-16 16:40:28 -05:00
John Colvin a9f2b4ad9a PNL window - setting for market/fill price column decimal places 2020-06-16 15:32:51 -05:00
Taha Afzal 9cb3a21e5a position service exposes both cpp and overridden cpp 2020-06-15 23:05:53 -04:00
Taha Afzal f381d536d6 Merge branch 'DJ_ICE' into DJ_ICE_cpp_mult 2020-06-15 09:53:32 -04:00
Pedro Pinto d8d5f3b93c Merge branch 'DJ_ICE' of bitbucket.org:bluetradesys/spark into DJ_ICE 2020-06-15 09:29:08 -04:00
Pedro Pinto 1d4dc47a62 Added missing update to session/high low. 2020-06-15 09:28:23 -04:00
Taha Afzal 482c300b72 Merge branch 'DJ_ICE_space_bar_recenter' into DJ_ICE 2020-06-14 21:08:51 -04:00
Pedro Pinto 69ad995ba9 Updated docker 2020-06-14 15:23:18 -04:00
Pedro Pinto 0b26ec1132 Added a few build tools. 2020-06-14 15:21:55 -04:00
John Colvin 3de494c80f recenter all ladders on spacebar (don't require shift) 2020-06-12 17:05:53 -05:00
John Colvin 7deb25dd1c fix ladder recenter on spacebar 2020-06-12 13:16:57 -05:00
Pedro Pinto 7a29ae1a83 Merge branch 'DJ_ICE' of bitbucket.org:bluetradesys/spark into DJ_ICE 2020-06-12 08:44:36 -04:00
Pedro Pinto 6da893128c Cleaned up logging. 2020-06-12 08:44:20 -04:00
Pedro Pinto 2cb458af2d Added OnBehalfofcompid tag to ICE as per cert. 2020-06-12 08:42:40 -04:00
Taha Afzal 04db38d627 Merge branch 'DJ_ICE_release_candidates' into DJ_ICE 2020-06-11 21:22:18 -04:00
John Colvin a144b03361 ladder recenter on spacebar (across thread barrier) 2020-06-11 18:28:37 -05:00
John Colvin 9c89a9a47e TabDocument forwards key press events to IShellWindows 2020-06-11 18:24:26 -05:00
John Colvin 007af71bb2 fix ladder center-on-settle behavior once and for all 2020-06-11 17:09:05 -05:00
John Colvin 7cfe8f4214 add override cpp context menu item in pnl window 2020-06-11 16:33:28 -05:00
John Colvin 24f8e66953 add IPositionModel (has function to override cpp) 2020-06-11 16:30:35 -05:00
John Colvin 90fc6d901f add PropertyEditor control/dialog 2020-06-11 16:29:45 -05:00
Taha Afzal a216d1cc81 Fixing sell order check for distance from settlement 2020-06-11 09:19:03 -04:00
Pedro Pinto f8395c11b5 Fixed application, vendor tags for DJ. 2020-06-11 08:26:26 -04:00
John Colvin 2b0e46ed38 fix ladder center around settle behavior 2020-06-11 00:36:11 -05:00
John Colvin 5f3b243265 'max settlement cross ticks limit' ladder setting 2020-06-10 18:16:52 -05:00
John Colvin c9ce2d18bf simplify 'Safety Checks' content alignment in ladder settings dialog 2020-06-10 17:33:13 -05:00
John Colvin 7b563ba66c ladder centers around settlement price if no bid/ask market 2020-06-10 13:17:01 -05:00
Taha Afzal 3e1be70923 Fix for HHD Balmo spreads 2020-06-10 13:57:19 -04:00
John Colvin aadd7df6c6 quantity divisor is 1 for 'ICE Lots' secs 2020-06-09 22:49:57 -05:00
59 changed files with 1724 additions and 668 deletions

No files matched your search

+2
View File
@@ -27,6 +27,7 @@ namespace mbts.ui {
CheckMarkGeometryKey = nameof(CheckMarkGeometryKey),
CopyWFGeometryKey = nameof(CopyWFGeometryKey),
CopyBoxesGeometryKey = nameof(CopyBoxesGeometryKey),
CurrencyExchangeGeometryKey = nameof(CurrencyExchangeGeometryKey),
DataEditGeometryKey = nameof(DataEditGeometryKey),
DetachAlgosKey = nameof(DetachAlgosKey),
DiskGeometryKey = nameof(DiskGeometryKey),
@@ -161,6 +162,7 @@ namespace mbts.ui {
public static ImageSource Clock { get { return load_resource_and_freeze("Clock"); } }
public static ImageSource CopyWF => create_icon(CopyWFGeometryKey);
public static ImageSource CopyBoxes => create_icon(CopyBoxesGeometryKey, null, _copy_boxes_pen);
public static ImageSource CurrencyExchange => create_icon(CurrencyExchangeGeometryKey);
public static ImageSource DataEdit => create_icon(DataEditGeometryKey);
public static ImageSource Defrag { get { return load_resource_and_freeze("Defrag"); } }
public static ImageSource DetachAlgos => create_icon_and_rotate(DetachAlgosKey, Brushes.Red);
@@ -62,6 +62,10 @@
M14.733902,12.084991L9.751783,17.388992 12.982842,17.436005C13.569886,17.462997 14.5229,17.350998 14.876848,17.005005 14.954852,16.929993 15.031879,16.824005 15.02486,16.593002 14.986895,15.457993 14.838883,13.438004 14.733902,12.084991z M22.507753,11.134453C22.480678,11.134323,22.467085,11.135494,22.469961,11.136993L20.64694,11.145004 16.291904,11.192993C16.388891,12.405991 16.596901,15.100998 16.647928,16.539001 16.668924,17.177994 16.448888,17.742004 16.007904,18.168991 15.210897,18.947998 13.893864,19.065002 13.179865,19.065002L9.2818066,19.005005 9.3258129,25.522003 9.3728109,25.528 9.3278271,25.882996 9.3317944,26.395996 9.3107983,26.397995C9.3167797,26.789993,9.3378369,27.552994,9.3958212,29.065994L9.4068075,29.393005C9.4207855,29.819992 9.5648295,29.994995 9.6707884,30.089005 9.9807898,30.365997 10.539817,30.390991 10.717799,30.369003L10.717799,30.375C10.88284,30.354996 11.280855,30.356003 12.823844,30.365997 13.867863,30.371002 15.206869,30.376999 16.594886,30.376999 20.757965,30.376999 23.270998,30.354996 23.862007,30.311005 24.454971,30.268005 24.661029,29.154999 24.690021,28.729996 24.690021,28.729996 24.677997,27.876999 24.661029,26.582993 24.612016,22.671005 24.51198,14.697998 24.472002,12.802002 24.461013,12.302994 24.316969,11.929993 24.034008,11.662003 23.547475,11.200003 22.697284,11.13536 22.507753,11.134453z M8.8867823,2.8410034L2.5417312,10.296997 6.4037791,10.356995C6.8917614,10.390991 8.3258005,10.341003 8.9567896,9.7299957 9.1738335,9.5189972 9.2667919,9.2659912 9.2558046,8.9089966 9.2067934,7.3889923 9.0258213,4.7480011 8.8867823,2.8410034z M10.424826,1.6239929C10.551842,3.302002 10.816799,6.951004 10.876797,8.8560028 10.903836,9.6750031 10.636804,10.360992 10.083818,10.897995 9.0667769,11.882004 7.3527657,11.987991 6.6627546,11.987991 6.4657918,11.987991 6.3367616,11.979004 6.3177796,11.977005L1.6477377,11.905991C1.6387044,14.278992 1.6236895,20.283997 1.6496909,22.358994 1.651705,22.569992 1.6437093,22.780991 1.6366904,22.992004 1.6117265,23.593994 1.5926833,24.112991 1.8537338,24.386002 2.0716933,24.612991 2.6497034,24.886002 4.1457549,24.886002 6.0127832,24.886002 7.0867711,24.876999 7.6967641,24.867004L7.6457993,17.259995 14.853899,9.5849915 16.681924,9.5650024 16.681924,9.5429993 19.454908,9.5289917 19.406934,2.6210022C19.323925,2.3549957,18.960945,1.6239929,17.387928,1.6239929z M9.1738335,0L17.387928,0C19.94692,0,20.874971,1.5299988,21.022983,2.4329987L21.077976,9.5209961 22.446951,9.5139923C22.43395,9.5130005 24.031017,9.4250031 25.148035,10.481995 25.753999,11.054001 26.071996,11.822998 26.092992,12.766998 26.142006,15.065994 26.281044,26.268997 26.307047,28.412003L26.311014,28.764999C26.279029,29.817993 25.750032,31.802002 23.979013,31.931 23.342958,31.977005 20.887972,32 16.683878,32 13.798893,32 11.107818,31.988998 10.808803,31.987991 10.789821,31.990997 9.5147806,32.112 8.6008288,31.309006 8.0858074,30.854996 7.8107797,30.229004 7.7838017,29.444992L7.7728153,29.126999C7.721789,27.759995 7.6978022,26.970993 7.6898061,26.490005 7.0547882,26.5 5.9867817,26.509003 4.1457549,26.509003 2.4377257,26.509003 1.3387128,26.192001 0.68367504,25.509003 -0.055286743,24.742004 -0.017322397,23.742004 0.012707477,22.938004 0.020702986,22.744003 0.028698692,22.559998 0.026684528,22.378998 -0.00029337304,20.240997 0.016674615,13.856995 0.026684528,11.212997L0.026684528,10.867004 0.14167619,10.610992 8.7147823,0.54100037 8.7088009,0.45899963 8.8018194,0.43800354z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.CurrencyExchangeGeometryKey}">
M0,24L15.324005,24C16.042007,24.785004,16.875,25.460999,17.800003,26L2,26 2,30 23.087997,30 23.087006,27.424988C23.771011,27.423004,24.439011,27.352997,25.085999,27.225983L25.085999,30C25.085999,31.10199,24.189011,32,23.085999,32L2,32C0.89700317,32,0,31.10199,0,30z M22.484015,13.026998L23.475018,13.026998 23.475018,13.856997C24.151018,13.885996,24.605021,14.016996,24.93902,14.167996L24.646021,15.233995C24.38302,15.129995 23.919018,14.912995 23.191017,14.912995 22.535015,14.912995 22.323015,15.176995 22.323015,15.440995 22.323015,15.751994 22.676016,15.950994 23.535017,16.251994 24.73702,16.647994 25.222021,17.166993 25.222021,18.015992 25.222021,18.854991 24.58502,19.571991 23.424017,19.759991L23.424017,20.72199 22.434015,20.72199 22.434015,19.825991C21.757013,19.797991,21.101011,19.627991,20.71701,19.420991L21.019012,18.317992C21.444014,18.533992 22.040014,18.731992 22.697016,18.731992 23.272017,18.731992 23.666018,18.524992 23.666018,18.147992 23.666018,17.788992 23.343018,17.562993 22.596016,17.326993 21.515013,16.987993 20.777012,16.516994 20.777012,15.601995 20.777012,14.771996 21.404013,14.119996 22.484015,13.922997z M0.065009117,12.384011L13.628021,12.384011C13.320021,13.018011,13.075021,13.687011,12.89902,14.384011L2.065011,14.384011 2.065011,18.384011 12.68002,18.384011C12.77602,19.075011,12.93702,19.743011,13.16102,20.384011L0.065009117,20.384011z M23.060013,10.460008C19.480015,10.460008 16.568016,13.368006 16.568016,16.943003 16.568016,20.519001 19.480015,23.426999 23.060013,23.427 26.640011,23.426999 29.55201,20.519001 29.55201,16.943003 29.55201,13.368006 26.640011,10.460008 23.060013,10.460008z M23.060013,8.4600086C27.74201,8.4600086 31.552008,12.266006 31.552008,16.943003 31.552008,21.621 27.74201,25.426998 23.060013,25.426998 18.378014,25.426998 14.568016,21.621 14.568016,16.943003 14.568016,12.266006 18.378014,8.4600086 23.060013,8.4600086z M2.0000181,2L2.0000181,6 23.08602,6 23.08602,2z M2.0000181,0L23.08602,0C24.18902,0,25.08602,0.89699936,25.08602,2L25.08602,6.6599998C24.430019,6.5310001 23.753019,6.4599991 23.060019,6.4599991 21.06402,6.4599991 19.20402,7.0300007 17.614019,8L1.8119812E-05,8 1.8119812E-05,2C1.8066406E-05,0.89699936,0.89701813,0,2.0000181,0z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.DocumentAddGeometryKey}">
M10.830011,12.05L13.334007,12.05 13.334007,16.535997 17.819998,16.535997 17.819998,19.03902 13.334007,19.03902 13.334007,23.525016 10.830988,23.525016 10.830988,19.03902 6.3460046,19.03902 6.3449975,16.53499 10.830988,16.535997z M2.2799975,2.4149805L2.2799975,29.580015 22.121998,29.580015 22.121998,8.500008 15.83599,8.500008 15.83599,2.4149805z M0,0L15.83599,0 17.125998,0 22.681996,5.439977 24.407,7.125007 24.407,32.000001 0,32.000001z
</sys:String>
@@ -276,6 +280,7 @@
m464.867188 0c-25.988282 0-47.132813 21.144531-47.132813 47.132812v313.75c0 49.324219 11.660156 98.710938 33.71875 142.824219 2.539063 5.082031 7.734375 8.292969 13.414063 8.292969 5.683593 0 10.875-3.210938 13.417968-8.292969 22.054688-44.113281 33.714844-93.503906 33.714844-142.824219v-313.75c0-25.988281-21.144531-47.132812-47.132812-47.132812zm0 30c9.445312 0 17.132812 7.6875 17.132812 17.132812v33.199219h-34.265625v-33.199219c0-9.445312 7.683594-17.132812 17.132813-17.132812zm17.132812 323.46875h-34.265625v-243.136719h34.265625zm-17.132812 105.4375c-8.71875-24.277344-14.1875-49.734375-16.222657-75.4375h32.445313c-2.035156 25.707031-7.507813 51.160156-16.222656 75.4375zm0 0
</sys:String>
</x:Array>
<sys:String x:Key="{x:Static mbts:Icons.CheckMarkGeometryKey}">
F1M9.97498,1.22334L4.6983,9.09834 4.52164,9.09834 0,5.19331 1.27664,3.52165 4.255,6.08833 8.33331,1.52588E-05 9.97498,1.22334z
</sys:String>
@@ -87,6 +87,15 @@ namespace mbts.spark {
public static bool operator !=(LadderColumnSettings x, LadderColumnSettings y) => !(x == y);
}
[ProtoContract]
class LadderOrderLimits : IEquatable<LadderOrderLimits> {
[ProtoMember(1)]
public ToggleInt32Proto max_settlement_cross_ticks { get; set; }
public bool Equals(LadderOrderLimits other) =>
other != null && max_settlement_cross_ticks == other.max_settlement_cross_ticks;
}
[ProtoContract]
class HistogramBarAnimation : IEquatable<HistogramBarAnimation> {
// this class is 100% mutable (there are literally 0 readonly members),
@@ -314,6 +323,8 @@ namespace mbts.spark {
// Settings are liable to change in the near future, so an internal IEqualityComparer simply won't do as it risks becoming out of date.
[ProtoContract]
class LadderSettings : IEquatable<LadderSettings> {
// RESERVED ProtoMember indices
// 900-999: dj settings
const double _default_order_entry_panel_width = 110.0;
const double _default_zoom_factor = 1.0;
const bool _default_show_warn_on_cross = true;
@@ -592,6 +603,9 @@ namespace mbts.spark {
[ProtoMember(61), DefaultValue(true)]
public bool status_message_visible { get; set; }
[ProtoMember(900)]
public LadderOrderLimits ladder_order_limits { get; set; }
public void sanitize() =>
sanitize(this);
@@ -697,7 +711,8 @@ namespace mbts.spark {
a.enforce_max_clip == b.enforce_max_clip &&
a.max_clip == b.max_clip &&
a.price_display_format == b.price_display_format &&
a.status_message_visible == b.status_message_visible;
a.status_message_visible == b.status_message_visible &&
a.ladder_order_limits.safe_equals(b.ladder_order_limits);
public bool Equals(LadderSettings other) =>
profile_equals(this, other) &&
@@ -100,6 +100,7 @@ namespace bts.shell {
ShellWindowVM shell_window_vm = null;
IShellWindow shell_window = null;
var title_source = new LazyObservable<string>(() => ShellWindowExtensions.literal_title_source(shell_window, shell_window_vm));
LadderVM vm = null;
var view = new Lazy<UIElement>(() => {
// resources
var model = new LadderModel(md, _orders_model, _mbo);
@@ -113,7 +114,6 @@ namespace bts.shell {
/// In response to that event, 'needs_resync' is set to true. This causes 'last_value' to be refreshed when the next caller requests the latest settings
/// (i.e., an IObserver subscribing to the settings_source, or the settings-dialog viewmodel).
bool initialized = false, needs_resync = false;
LadderVM vm = null;
var settings_subject = new Subject<LadderSettings>();
var settings_source = Observable.Create<LadderSettings>(o => {
ensure_synced();
@@ -272,10 +272,11 @@ namespace bts.shell {
(v, s) => save(_get_state(((LadderView)v).vm, settings_id), s),
icon: Icons.Ladder,
thread_id: _thread_id_provider.next_id(),
vm => {
shell_window_vm = vm;
swvm => {
shell_window_vm = swvm;
title_source.connect();
});
},
key_event_args => vm?.key_down(key_event_args));
}
async void _show_windows(IImmutableSet<uint> securities) {
@@ -3,6 +3,7 @@ using bts.api;
using bts.api.orderman;
using bts.collections;
using bts.persist.algo;
using bts.proto;
using bts.shell.orderbook;
using bts.utils;
using mbts.collections;
@@ -44,7 +45,8 @@ namespace mbts.spark {
LadderSettings.NetChangeTerms _price_format;
LadderSettings.PriceDisplayFormat _price_display_format;
double _order_entry_panel_width, _zoom_factor;
bool _auto_clear, _show_warn_on_cross, _enforce_max_clip;
bool _auto_clear, _show_warn_on_cross, _enforce_max_clip, _enforce_max_settlement_cross_ticks;
int _max_settlement_cross_ticks;
LadderSettings _current;
LadderColumnSettingsVM
_orders = new OrdersColumnSettingsVM(),
@@ -190,6 +192,8 @@ namespace mbts.spark {
public bool show_warn_on_cross { get => _show_warn_on_cross; set => Set(ref _show_warn_on_cross, value); }
public bool enforce_max_clip { get => _enforce_max_clip; set => Set(ref _enforce_max_clip, value); }
public uint max_clip { get => _max_clip.Value; set => _max_clip.Value = value; }
public bool enforce_max_settlement_cross_ticks { get => _enforce_max_settlement_cross_ticks; set => Set(ref _enforce_max_settlement_cross_ticks, value); }
public int max_settlement_cross_ticks { get => _max_settlement_cross_ticks; set => Set(ref _max_settlement_cross_ticks, value); }
// favorites
public FavoriteAlgosVM favorite_algos_vm { get; }
@@ -370,6 +374,10 @@ namespace mbts.spark {
show_warn_on_cross = settings.show_warn_on_cross;
enforce_max_clip = settings.enforce_max_clip;
max_clip = settings.max_clip;
if (settings.ladder_order_limits != null) {
enforce_max_settlement_cross_ticks = settings.ladder_order_limits.max_settlement_cross_ticks.is_enabled;
max_settlement_cross_ticks = settings.ladder_order_limits.max_settlement_cross_ticks.value;
}
}
}
@@ -448,6 +456,10 @@ namespace mbts.spark {
clone.show_warn_on_cross = show_warn_on_cross;
clone.enforce_max_clip = enforce_max_clip;
clone.max_clip = max_clip;
if (clone.ladder_order_limits == null)
clone.ladder_order_limits = new LadderOrderLimits();
clone.ladder_order_limits.max_settlement_cross_ticks =
new ToggleInt32Proto(max_settlement_cross_ticks, enforce_max_settlement_cross_ticks);
return clone;
}
@@ -1,5 +1,6 @@
using bts.api;
using bts.api.orderman;
using bts.proto;
using bts.shell;
using bts.spark;
using bts.utils;
@@ -259,7 +260,11 @@ namespace mbts.spark {
public IBus bus => _bus;
public event Action on_tick, request_settings_dialog, settings_invalidated;
public event Action
on_tick,
request_settings_dialog,
request_recenter,
settings_invalidated;
public MDConsumerHandle md => _model.md;
// we return only entries who have piqs and whose piqs are not uint.Max
@@ -447,15 +452,27 @@ namespace mbts.spark {
public void key_down(KeyEventArgs e) {
if (order_properties_vm == null)
return;
if (KeyboardExtensions.IsDown(Key.Space)) {
_bus?.post(SparkTags.RequestRecenterLadder, null);
}
// the ctrl modifier requirement helps avoid keyboard-input collisions w/ algo-templates popup
if (!KeyboardExtensions.IsCtrlDown()) return;
var new_algo = order_properties_vm.algo_definitions.FirstOrDefault(o => o.algo_root.key_match(e));
if (new_algo != null) {
order_properties_vm.selected_algo_definition = new_algo;
e.Handled = true;
switch (e.Key) {
case Key.Space:
if (KeyboardExtensions.IsShiftDown()) {
// only recenter this ladder
request_recenter?.Invoke();
} else {
// recenter all ladders
_bus?.post(SparkTags.RequestRecenterLadder, null);
}
e.Handled = true;
break;
default:
// the ctrl modifier requirement helps avoid keyboard-input collisions w/ algo-templates popup
if (KeyboardExtensions.IsCtrlDown()) {
var new_algo = order_properties_vm.algo_definitions.FirstOrDefault(o => o.algo_root.key_match(e));
if (new_algo != null) {
order_properties_vm.selected_algo_definition = new_algo;
e.Handled = true;
}
}
break;
}
}
@@ -489,6 +506,10 @@ namespace mbts.spark {
}
public async Task send_order_async(Side side, uint size, double price) {
if (!_validate_price(side, price, out var invalid_price_msg)) {
status_update(new Activity { security = security, message = invalid_price_msg, category = ActivityLogCategory.order });
return;
}
var order = order_properties_vm.create(side);
if (order.CustomDef != null) {
if (order.CustomDef.Stop != null) {
@@ -520,6 +541,23 @@ namespace mbts.spark {
}
}
bool _validate_price(Side side, double price, out string msg) {
msg = null;
if (!price.is_real()) {
msg = "not a real number";
} else if (settlement.is_real()) {
var ticks_from_settle = security.ContractSpec.tickdiff(price, settlement);
if (ticks_from_settle.HasValue) {
var max_cross = (current_settings?.ladder_order_limits?.max_settlement_cross_ticks)?.as_nullable();
if (max_cross.HasValue) {
if (side == Side.Sell ? ticks_from_settle < (-1 * max_cross.Value) : ticks_from_settle > max_cross.Value)
msg = $"exceeds settle cross ticks limit ({ticks_from_settle.Value})";
}
}
}
return msg == null;
}
void _update_header() {
bool last_updated = md.get_last_trade(ref _last_trade_time, out NativePriceSize last, out DateTime time, out ulong volume);
if (_misc_time != _model.md.misc_timestamp || last_updated) {
@@ -53,7 +53,7 @@ namespace mbts.spark {
readonly RefValueContainer<IEnumerable<VolumeAtPriceLevelImmutable>> _volume_container =
new RefValueContainer<IEnumerable<VolumeAtPriceLevelImmutable>>();
IDisposable _settings_sub, _volume_sub, _tick_sub;
IDisposable _settings_sub, _volume_sub, _tick_sub, _vm_sub;
ScrollViewer _scrollViewer;
LadderSettings _settings;
LadderVM _vm;
@@ -697,10 +697,22 @@ namespace mbts.spark {
_price_comparer = Comparer<double>.Create((x, y) => security.ContractSpec.tick_equals(x, y) ? 0 : y.CompareTo(x));
_price_dirty = true;
_piq_dirty = true;
_vm.on_tick += _tick;
// **use local vm to protect against re-assignment,
// so the events are unhooked from the same instance to which they were added
// when the subs are disposed.
var local_vm = _vm;
local_vm.on_tick += _tick;
local_vm.request_recenter += on_request_recenter;
_settings_sub = _vm.settings.OnDispatcher().Subscribe(_settings_updated);
_volume_sub = _vm.model.order_gateway.md_auxiliary_model.security_volume_at_price(security.Id).Subscribe(t => _volume_container.write_value(t.state.Values));
_tick_sub = Disposable.Create(() => _vm.on_tick -= _tick);
// **unhook from local_vm.request_recenter.
// todo: organize these subs into a single entity, prob _vm_subs.
// This hasn't already been done bc the ladder a bit fragile, so changes must be carefully implemented,
// with meticulous attention to detail.
_tick_sub = Disposable.Create(() => local_vm.on_tick -= _tick);
_vm_sub = Disposable.Create(() => local_vm.request_recenter -= on_request_recenter);
void on_request_recenter() =>
RecenterCommand?.ExecuteIfCan(null);
}
}
@@ -1069,7 +1081,7 @@ namespace mbts.spark {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return double.IsNaN(best_bid) ?
double.IsNaN(best_ask) ? _vm.low : security.ContractSpec.tickdown(best_ask) :
double.IsNaN(best_ask) ? _vm.settlement : security.ContractSpec.tickdown(best_ask) :
best_bid;
}
@@ -1077,7 +1089,7 @@ namespace mbts.spark {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return double.IsNaN(best_ask) ?
double.IsNaN(best_bid) ? security.ContractSpec.tickdown(_vm.high) : best_bid :
double.IsNaN(best_bid) ? _vm.settlement : best_bid :
security.ContractSpec.tickdown(best_ask);
}
@@ -1085,7 +1097,7 @@ namespace mbts.spark {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return double.IsNaN(best_bid) ?
double.IsNaN(best_ask) ? 0.5 * (_vm.low + _vm.high) : security.ContractSpec.tickdown(best_ask) :
double.IsNaN(best_ask) ? _vm.settlement : security.ContractSpec.tickdown(best_ask) :
double.IsNaN(best_ask) ? best_bid : TickUtils.mid_tick(security.ContractSpec, best_bid, best_ask);
}
@@ -1019,45 +1019,47 @@
<Grid HorizontalAlignment="Left" Margin="6">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="Auto" />
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush3}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<!-- market cross -->
<CheckBox Name="warn" Grid.Column="0" FlowDirection="RightToLeft" IsChecked="{Binding show_warn_on_cross}">
<CheckBox.Resources>
<Style TargetType="{x:Type Path}">
<Setter Property="FlowDirection" Value="LeftToRight"/>
</Style>
</CheckBox.Resources>
<CheckBox Grid.Column="0" VerticalContentAlignment="Center" IsChecked="{Binding show_warn_on_cross}">
<TextBlock
Style="{StaticResource EnableDisableFeatureText}"
IsEnabled="{Binding show_warn_on_cross}"
Text="Warn on Market Cross"
/>
</CheckBox>
<TextBlock Grid.Column="1"
Style="{StaticResource EnableDisableFeatureText}"
IsEnabled="{Binding ElementName=warn, Path=IsChecked}"
Text="Warn on Market Cross" />
<!-- max order qty -->
<CheckBox Name="enforce_max_clip" Grid.Row="1" Grid.Column="0" FlowDirection="RightToLeft" IsChecked="{Binding enforce_max_clip}">
<CheckBox.Resources>
<Style TargetType="{x:Type Path}">
<Setter Property="FlowDirection" Value="LeftToRight"/>
</Style>
</CheckBox.Resources>
<CheckBox Grid.Row="2" Grid.Column="0" VerticalContentAlignment="Center" IsChecked="{Binding enforce_max_clip}">
<TextBlock
Style="{StaticResource EnableDisableFeatureText}"
IsEnabled="{Binding enforce_max_clip}"
Text="Max Order Quantity"
/>
</CheckBox>
<TextBlock Grid.Row="1" Grid.Column="1"
Style="{StaticResource EnableDisableFeatureText}"
IsEnabled="{Binding ElementName=enforce_max_clip, Path=IsChecked}"
MinWidth="{Binding ElementName=warn, Path=ActualWidth}"
Text="Max Order Quantity"/>
<c:TickUpDownUInt Grid.Row="1" Grid.Column="2"
IsEnabled="{Binding ElementName=enforce_max_clip, Path=IsChecked}"
Value="{Binding max_clip}" />
<c:TickUpDownUInt
Grid.Row="2"
Grid.Column="2"
IsEnabled="{Binding enforce_max_clip}"
Value="{Binding max_clip}"
Width="60"
/>
<CheckBox Grid.Row="4" VerticalContentAlignment="Center" IsChecked="{Binding enforce_max_settlement_cross_ticks}">
<TextBlock
Style="{StaticResource EnableDisableFeatureText}"
IsEnabled="{Binding enforce_max_settlement_cross_ticks}"
Text="Max Ticks from Settlement"
/>
</CheckBox>
<c:TickUpDownInt Grid.Row="4" Grid.Column="2" IsEnabled="{Binding enforce_max_settlement_cross_ticks}" Value="{Binding max_settlement_cross_ticks}"/>
</Grid>
</TabItem>
<TabItem Header="Mini Order Book">
@@ -93,6 +93,7 @@ namespace mbts.spark {
_ui_scaler.MouseDoubleClick += _ui_scaler_MouseDoubleClick;
this.PreviewMouseWheel += LadderView_PreviewMouseWheel;
this.PreviewMouseDown += LadderView_PreviewMouseDown;
PreviewKeyDown += (s, e) => vm.key_down(e);
}
IDisposable _connect_left_panel_scroll() {
@@ -282,15 +282,18 @@ namespace bts.shell.pnl {
public readonly WorkingOrderData working;
public readonly double
cpp,
default_cpp,
bid_price,
ask_price,
last_price,
settlement_price;
public readonly double? override_cpp;
public PNLRowData(
PNLKey key,
double cpp = 0,
double default_cpp = 0,
double? override_cpp = null,
double bid_price = 0,
double ask_price = 0,
double last_price = 0,
@@ -305,7 +308,8 @@ namespace bts.shell.pnl {
QuantityConversionData? qty_conversion = null) {
//
this.key = key;
this.cpp = cpp;
this.default_cpp = default_cpp;
this.override_cpp = override_cpp;
this.bid_price = bid_price;
this.ask_price = ask_price;
this.last_price = last_price;
@@ -335,6 +339,9 @@ namespace bts.shell.pnl {
AskLTESettle = Ask | Settle | 1 << 7
}
public string symbol => security?.pnl_symbol() ?? string.Empty;
public double effective_cpp => override_cpp ?? default_cpp;
/// Market/Calc
public double mid_price => (bid_price + ask_price) / 2;
public double pnl_price {
@@ -374,26 +381,26 @@ namespace bts.shell.pnl {
}
}
/// Sod
public double sod_pnl => cpp *
public double sod_pnl => effective_cpp *
DoubleUtil.nan_to_zero_sum(
sod_long_avg_price_delta_raw * sod_long_pos,
sod_short_avg_price_delta_raw * sod_short_pos
);
// long
public double sod_long_pos => sod.long_pos;
public double sod_long_avg_price => cpp * sod.long_avg;
public double sod_long_avg_price => effective_cpp * sod.long_avg;
public double sod_long_avg_price_raw => sod.long_avg;
public double sod_long_avg_price_delta => cpp * sod_long_avg_price_delta_raw;
public double sod_long_avg_price_delta => effective_cpp * sod_long_avg_price_delta_raw;
public double sod_long_avg_price_delta_raw => sod.long_pos == 0 ? double.NaN : long_pnl_price - sod.long_avg;
// short
public double sod_short_pos => sod.short_pos;
public double sod_short_avg_price => cpp * sod.short_avg;
public double sod_short_avg_price => effective_cpp * sod.short_avg;
public double sod_short_avg_price_raw => sod.short_avg;
public double sod_short_avg_price_delta => cpp * sod_short_avg_price_delta_raw;
public double sod_short_avg_price_delta => effective_cpp * sod_short_avg_price_delta_raw;
public double sod_short_avg_price_delta_raw => sod.short_pos == 0 ? double.NaN : sod.short_avg - short_pnl_price;
// net
public double sod_net_pos => sod.net_pos;
public double sod_net_avg_price_delta => cpp * sod_net_avg_price_delta_raw;
public double sod_net_avg_price_delta => effective_cpp * sod_net_avg_price_delta_raw;
public double sod_net_avg_price_delta_raw =>
MathUtils.weighted_average(
sod_long_avg_price_delta_raw, sod.long_pos,
@@ -404,27 +411,27 @@ namespace bts.shell.pnl {
public double display_sod_short_pos => qty_conversion.to_display(sod_short_pos);
/// Day
public double day_pnl => cpp *
public double day_pnl => effective_cpp *
DoubleUtil.nan_to_zero_sum(
day_long_avg_price_delta_raw * day_long_pos,
day_short_avg_price_delta_raw * day_short_pos
);
// long
public double day_long_pos => day.long_pos;
public double day_long_avg_price => cpp * day.long_avg;
public double day_long_avg_price => effective_cpp * day.long_avg;
public double day_long_avg_price_raw => day.long_avg;
public double day_long_avg_price_delta => cpp * day_long_avg_price_delta_raw;
public double day_long_avg_price_delta => effective_cpp * day_long_avg_price_delta_raw;
public double day_long_avg_price_delta_raw => day.long_pos == 0 ? double.NaN : long_pnl_price - day.long_avg;
// short
public double day_short_pos => day.short_pos;
public double day_short_avg_price => cpp * day.short_avg;
public double day_short_avg_price => effective_cpp * day.short_avg;
public double day_short_avg_price_raw => day.short_avg;
public double day_short_avg_price_delta => cpp * day_short_avg_price_delta_raw;
public double day_short_avg_price_delta => effective_cpp * day_short_avg_price_delta_raw;
public double day_short_avg_price_delta_raw => day.short_pos == 0 ? double.NaN : day.short_avg - short_pnl_price;
public bool has_day_trades => day.long_pos > 0 || day.short_pos > 0;
// net
public double day_net_pos => day.net_pos;
public double day_net_avg_price_delta => cpp * day_net_avg_price_delta_raw;
public double day_net_avg_price_delta => effective_cpp * day_net_avg_price_delta_raw;
public double day_net_avg_price_delta_raw =>
MathUtils.weighted_average(
day_long_avg_price_delta_raw, day.long_pos,
@@ -447,25 +454,25 @@ namespace bts.shell.pnl {
public double total_pnl => DoubleUtil.nan_to_zero_sum(sod_pnl, day_pnl);
// long
public double total_long_pos => DoubleUtil.nan_to_zero_sum(sod.long_pos, day.long_pos);
public double total_long_avg_price => cpp * total_long_avg_price_raw;
public double total_long_avg_price => effective_cpp * total_long_avg_price_raw;
public double total_long_avg_price_raw => DoubleUtil.nan_to_zero_sum(sod.long_avg, day.long_avg);
public double total_long_avg_price_delta => cpp * total_long_avg_price_delta_raw;
public double total_long_avg_price_delta => effective_cpp * total_long_avg_price_delta_raw;
public double total_long_avg_price_delta_raw =>
MathUtils.weighted_average(
sod_long_avg_price_delta_raw, sod.long_pos,
day_long_avg_price_delta_raw, day.long_pos);
// short
public double total_short_pos => DoubleUtil.nan_to_zero_sum(sod.short_pos, day.short_pos);
public double total_short_avg_price => cpp * total_short_avg_price_raw;
public double total_short_avg_price => effective_cpp * total_short_avg_price_raw;
public double total_short_avg_price_raw => DoubleUtil.nan_to_zero_sum(sod.short_avg, day.short_avg);
public double total_short_avg_price_delta => cpp * total_short_avg_price_delta_raw;
public double total_short_avg_price_delta => effective_cpp * total_short_avg_price_delta_raw;
public double total_short_avg_price_delta_raw =>
MathUtils.weighted_average(
sod_short_avg_price_delta_raw, sod.short_pos,
day_short_avg_price_delta_raw, day.short_pos);
// net
public double total_net_pos => DoubleUtil.nan_to_zero_sum(sod.long_pos, -sod.short_pos, day.long_pos, -day.short_pos);
public double total_net_avg_price_delta => cpp * total_net_avg_price_delta_raw;
public double total_net_avg_price_delta => effective_cpp * total_net_avg_price_delta_raw;
public double total_net_avg_price_delta_raw =>
MathUtils.weighted_average(
total_long_avg_price_delta_raw, total_long_pos,
@@ -478,23 +485,23 @@ namespace bts.shell.pnl {
#region Working
// long
public double working_long_pos => working.long_data.working_total;
public double working_long_avg_price => cpp * working_long_avg_price_raw;
public double working_long_top_price => cpp * working_long_top_price_raw;
public double working_long_avg_price => effective_cpp * working_long_avg_price_raw;
public double working_long_top_price => effective_cpp * working_long_top_price_raw;
public double working_long_top_price_raw => working.top_bid;
public double working_long_avg_price_raw => working.long_data.avg_price;
public double working_long_avg_price_delta => cpp * working_long_avg_price_delta_raw;
public double working_long_avg_price_delta => effective_cpp * working_long_avg_price_delta_raw;
public double working_long_avg_price_delta_raw => working_long_pos == 0 ? double.NaN : long_pnl_price - working_long_avg_price_raw;
// short
public double working_short_pos => working.short_data.working_total;
public double working_short_avg_price => cpp * working_short_avg_price_raw;
public double working_short_top_price => cpp * working_short_top_price_raw;
public double working_short_avg_price => effective_cpp * working_short_avg_price_raw;
public double working_short_top_price => effective_cpp * working_short_top_price_raw;
public double working_short_top_price_raw => working.top_ask;
public double working_short_avg_price_raw => working.short_data.avg_price;
public double working_short_avg_price_delta => cpp * working_short_avg_price_delta_raw;
public double working_short_avg_price_delta => effective_cpp * working_short_avg_price_delta_raw;
public double working_short_avg_price_delta_raw => working_short_pos == 0 ? double.NaN : working_short_avg_price_raw - short_pnl_price;
// net
public double working_net_pos => working_long_pos - working_short_pos;
public double working_net_avg_price_delta => cpp * working_net_avg_price_delta_raw;
public double working_net_avg_price_delta => effective_cpp * working_net_avg_price_delta_raw;
public double working_net_avg_price_delta_raw =>
MathUtils.weighted_average(
working_long_avg_price_delta_raw, working_long_pos,
@@ -505,6 +512,24 @@ namespace bts.shell.pnl {
public double display_working_short_pos => qty_conversion.to_display(working_short_pos);
#endregion
public PNLRowData with(SecurityImmutable? security = null, string account_name = null, WorkingOrderData? working = null, PNLCalculationType? calc_type = null) =>
new PNLRowData(
key,
default_cpp,
override_cpp,
bid_price,
ask_price,
last_price,
settlement_price,
sod,
day,
raw_day,
working ?? this.working,
security ?? this.security,
account_name ?? this.account_name,
calc_type ?? this.calc_type,
qty_conversion: qty_conversion);
WaterfallPriceFlags _waterfall_flags() {
var flags = WaterfallPriceFlags.None;
if (!double.IsNaN(bid_price)) flags |= WaterfallPriceFlags.Bid;
@@ -546,7 +571,8 @@ namespace bts.shell.pnl {
public bool Equals(PNLRowData other) =>
key == other.key &&
cpp == other.cpp &&
default_cpp == other.default_cpp &&
override_cpp == other.override_cpp &&
security.HasValue == other.security.HasValue &&
account_name == other.account_name &&
sod == other.sod &&
@@ -574,9 +600,12 @@ namespace bts.shell.pnl {
}
static class PNLRowDataFactory {
public static PNLRowData create((SecurityImmutable? sec, PNLUnitImmutable value, QuantityConversionData qty_conversion) t) =>
new PNLRowData(new PNLKey(t.value.Pos.AccountId, t.value.Pos.SecurityId),
t.value.CashValue,
public static PNLRowData create((SecurityImmutable? sec, PNLUnitImmutable value, QuantityConversionData qty_conversion) t) {
var (default_cpp, override_cpp) = t.value.pnl_cpp_tuple(t.sec);
return new PNLRowData(
new PNLKey(t.value.Pos.AccountId, t.value.Pos.SecurityId),
default_cpp,
override_cpp,
t.value.BidPrice,
t.value.AskPrice,
t.value.LastPrice,
@@ -588,25 +617,27 @@ namespace bts.shell.pnl {
t.sec,
t.value.Pos.Account,
qty_conversion: t.qty_conversion);
}
}
static class PNLDataExtensions {
// Note: PNLRowData is passed by ref because it is fairly large struct, and since it is a readonly struct, we know it cannot be modified (so might as well avoid excessive copying).
public static PNLRowData with(this PNLRowData pnl_data, SecurityImmutable? security = null, string account_name = null, WorkingOrderData? working = null, PNLCalculationType? calc_type = null) =>
new PNLRowData(
pnl_data.key,
pnl_data.cpp,
pnl_data.bid_price,
pnl_data.ask_price,
pnl_data.last_price,
pnl_data.settlement_price,
pnl_data.sod,
pnl_data.day,
pnl_data.raw_day,
working ?? pnl_data.working,
security ?? pnl_data.security,
account_name ?? pnl_data.account_name,
calc_type ?? pnl_data.calc_type,
qty_conversion: pnl_data.qty_conversion);
public static string pnl_symbol(this SecurityImmutable security) {
if(security.HasIce)
return PNLICEHelper.get_symbol(security);
return security.Symbol;
}
// while override_cpp could use double.NaN to indicate the lack of an override,
// the nullable double makes it clear that it is an optional value.
public static (double default_cpp, double? override_cpp) pnl_cpp_tuple(this PNLUnitImmutable pnl_unit, SecurityImmutable? security) =>
security.HasValue ?
pnl_cpp_tuple(pnl_unit, security.Value) :
(pnl_unit.CashValue, pnl_unit.HasCppOverride ? pnl_unit.CppOverride.Value : (double?)null);
public static (double default_cpp, double? override_cpp) pnl_cpp_tuple(this PNLUnitImmutable pnl_unit, SecurityImmutable security) {
// TODO: actual impl
double calced_pnl = PNLICEHelper.get_cpp(pnl_unit,security);
return (calced_pnl, /*pnl_unit.HasCppOverride ? pnl_unit.CppOverride.Value : */(double?)null);
}
}
}
@@ -0,0 +1,77 @@
using bts.api;
using bts.api.orderman;
using bts.api.position;
using bts.utils;
using mbts;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
namespace bts.shell.pnl {
static class PNLICEHelper{
public static bool is_spread(SecurityImmutable sec){
return sec.HasSpread && sec.Ice.StripName.Contains("/");
}
public static bool is_strip(SecurityImmutable sec){
return sec.HasSpread && !is_spread(sec);
}
public static bool is_ice_lots(SecurityImmutable sec){
return sec.Ice.MarketDescription.Contains("ICE Lots");
}
public static double get_future_cpp (SecurityImmutable sec){
if(sec.Symbol == "HHD")
return 1;
if(is_ice_lots(sec))
return 2500;
else{
var days_in_month = DateTime.DaysInMonth(Convert.ToInt32(sec.Future.ExpirationYear),
Convert.ToInt32(sec.Future.ExpirationMonth));
return days_in_month; // because the size is multiplied by 2500 already
}
}
public static double get_spread_cpp(SecurityImmutable sec){
return 0;
}
public static double get_strip_cpp(PNLUnitImmutable pnl,
SecurityImmutable sec){
double rv = 0;
foreach (var l in sec.Spread.Legs)
if(l.Security.HasFuture)
rv += get_cpp(pnl,l.Security);
return rv;
}
public static string get_symbol (SecurityImmutable sec){
var rv = String.Format("{0}{1}{2}",
sec.Symbol,
is_ice_lots(sec)? " ICE LOTS" : String.Empty,
is_spread(sec)? " Spread" : String.Empty);
return rv;
}
public static double get_cpp (PNLUnitImmutable pnl,
SecurityImmutable sec){
if(sec.Symbol == "HHD")
Console.WriteLine("yes!");
if (sec.HasGlbx)
return pnl.CashValue;
else if (sec.HasIce){
if(sec.HasFuture)
return get_future_cpp(sec);
else if(is_spread(sec))
return get_spread_cpp(sec);
else if(is_strip(sec))
return get_strip_cpp(pnl,sec);
}
return Double.NaN;
}
}}
@@ -1,4 +1,5 @@
using bts.api;
using bts.api.position;
using bts.collections;
using bts.settings;
using bts.shell.pnl;
@@ -11,6 +12,7 @@ using mbts.persist;
using mbts.spark;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.controls.property_editor;
using mbts.ui.settings;
using mbts.ui.spark;
using mbts.ui.utility;
@@ -22,6 +24,7 @@ using System.ComponentModel;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
@@ -34,11 +37,13 @@ namespace bts.shell {
readonly UserSettingsHub _settings_hub;
readonly PNLConfig _pnl_conf;
readonly IShellWindowThreadIDProvider _thread_id_provider;
readonly IPositionModel _position_model;
public PNLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model) : base(owner, _window_type) {
public PNLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model, IPositionModel position_model) : base(owner, _window_type) {
_bus = bus;
_orders_model = orders_model;
_settings_hub = settings_hub;
_position_model = position_model;
_pnl_conf = new PNLConfig(Configuration.get<bts.config.PNLOptions>());
_thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, Configuration.get<bts.config.MultiThreadedWindows>().pnl);
_dispose = bus.subscribe(SparkTags.ShowPNLTag).OnDispatcher().Subscribe(_show);
@@ -105,6 +110,8 @@ namespace bts.shell {
menu_display: menu_display_vm.create());
return new PNLSaveState { use_defaults = false, settings = state };
};
IDisposable cpp_override_dialog = null;
IEnumerable<SparkCommand> commands = new[] {
new SparkCommandCommand("Collapse All", Icons.RightArrow, new DelegateCommand(() => vm.set_all_expanded(false))),
new SparkCommandCommand("Expand All", Icons.DownArrow, new DelegateCommand(() => vm.set_all_expanded(true))),
@@ -116,6 +123,26 @@ namespace bts.shell {
show_in_context_menu = _pnl_conf.show_pause_resume,
show_in_toolbar = _pnl_conf.show_pause_resume
},
new SparkCommandCommand("Override CPP...", Icons.CurrencyExchange, new DelegateCommand(() => {
Disposable.dispose(ref cpp_override_dialog);
var security_keys = vm.selected_rows.Select(r => r.security_key.value).Distinct().ToList();
double initial_cpp = vm.selected_rows.Select(r => r.cpp.value).Distinct().SafeSingleOrDefault();
override_cpp_async().ignore();
async Task override_cpp_async() {
try {
var cts = new CancellationTokenSource();
cpp_override_dialog = Disposable.Create(new Action(cts.Cancel));
var (cpp, committed) = await PropertyEditor.get_double_async("Override CPP", "value", cts.Token, initial_cpp);
if (committed && cpp.is_real_positive())
await _position_model.override_cpp_async(security_keys, cpp);
} catch (Exception ex) {
Log.Ui.warn($"Error overriding cpp: {ex}.");
}
}
})) {
show_in_context_menu = true,
show_in_toolbar = false
},
SparkCommands.window_settings_command(new DialogCommand(() => {
settings_manager.instance_settings = get_save_state().settings;
var dialog_vm = new ShellSettingsDialogVM<PNLSettings, PNLSettingsVM>(
@@ -190,6 +217,7 @@ namespace bts.shell {
cached_columns.RemoveRange(e.OldItems.OfType<DIYGrid.ColumnBase>());
}),
Disposable.wrap_collection(commands.OfType<IDisposable>()),
Disposable.Create(() => Disposable.dispose(ref cpp_override_dialog)),
menu_display_vm,
vm);
return (content, commands, get_save_state, dispose);
@@ -384,5 +412,17 @@ namespace bts.shell {
return false;
}
}
[Export(typeof(IPNLSettingsMigrationRule))]
class InitializeDataFormattingMigrationRule : IPNLSettingsMigrationRule {
public bool apply(PNLSettings settings, out PNLSettings new_settings) {
if (settings != null && settings.data_formatting == null) {
new_settings = settings.with(data_formatting: PNLSettings.Default.data_formatting);
return true;
}
new_settings = null;
return false;
}
}
}
}
@@ -204,11 +204,11 @@ namespace bts.shell.pnl {
// impl (add all)
bd.add_discrete_values(fs.account, d => d.key.account_id);
bd.add_discrete_values(fs.exchange, d => d.security.exchange_or_default());
bd.add_discrete_values(fs.symbol, d => d.security.symbol_or_default());
bd.add_discrete_values(fs.symbol, d => d.symbol);
bd.add_discrete_values(fs.security_type, d => d.security.HasValue ? d.security.Value.ContractCase : Security.ContractOneofCase.None);
bd.add_regex(fs.security, d => d.security.ToString());
bd.add_regex(fs.security_key, d => d.key.security_id.ToString());
bd.add_numeric(fs.cpp, d => d.cpp);
bd.add_numeric(fs.cpp, d => d.effective_cpp);
/// sod
bd.add_numeric(fs.sod_pnl, d => d.sod_pnl);
bd.add_numeric(fs.sod_long_pos, d => d.sod_long_pos);
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,52 @@
using bts.utils;
using mbts.spark;
using mbts.ui.shell;
using System;
using System.Collections.Generic;
namespace bts.shell.pnl {
class PNLDataFormattingVM : ViewModelBase, IValueFactory<PNLDataFormatting> {
const uint _min_decimal_places = 1, _max_decimal_places = 6;
uint _market_price_decimal_places, _fill_price_decimal_places;
public uint market_price_decimal_places {
get => _market_price_decimal_places;
set => Set(ref _market_price_decimal_places, value);
}
public uint fill_price_decimal_places {
get => _fill_price_decimal_places;
set => Set(ref _fill_price_decimal_places, value);
}
public IEnumerable<uint> decimal_place_options {
get {
for (uint n = _min_decimal_places; n <= _max_decimal_places; n++)
yield return n;
}
}
public PNLDataFormatting create() =>
new PNLDataFormatting {
fill_price_display = new DoubleFormatting {
tick_factors = new mbts.user.settings.TickFactors(
Math.Pow(10, MathUtils.within_range(_min_decimal_places, _max_decimal_places, fill_price_decimal_places)),
1)
},
market_price_display = new DoubleFormatting {
tick_factors = new mbts.user.settings.TickFactors(
Math.Pow(10, MathUtils.within_range(_min_decimal_places, _max_decimal_places, market_price_decimal_places)),
1)
}
};
public void load_from(PNLDataFormatting value) {
if (value != null) {
if (value.market_price_display?.tick_factors != null) {
market_price_decimal_places = (uint)Math.Log10(value.market_price_display.tick_factors.tick_base);
}
if (value.fill_price_display?.tick_factors != null) {
fill_price_decimal_places = (uint)Math.Log10(value.fill_price_display.tick_factors.tick_base);
}
}
}
}
}
@@ -14,7 +14,6 @@ using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Dynamic;
using System.Linq;
using ColumnKeys = bts.shell.pnl.PNLView.Columns;
@@ -52,6 +51,7 @@ namespace bts.shell.pnl {
public SimpleGridSettingsVM core_settings_vm { get; }
public PNLGroupRowAppearanceVM group_row_defaults { get; } = new PNLGroupRowAppearanceVM();
public PNLCellAppearanceVM header_row_defaults { get; } = new PNLCellAppearanceVM();
public PNLDataFormattingVM data_formatting_vm { get; } = new PNLDataFormattingVM();
public PNLCalculationType calculation_type { get => _calculation_type; set => Set(ref _calculation_type, value); }
public IEnumerable<PNLCalculationType> calculation_types => EnumHelper.get_values_except(PNLCalculationType.None, PNLCalculationType.Same, PNLCalculationType.Opposite);
public PNLHeaderRowDisplay header_row_display { get => _header_row_display; set => Set(ref _header_row_display, value); }
@@ -63,6 +63,7 @@ namespace bts.shell.pnl {
var s = _last_loaded == null ? new PNLSettings() : SparkUtils.clone_proto(_last_loaded);
s.calculation_type = _calculation_type;
s.grid = core_settings_vm.create();
s.data_formatting = data_formatting_vm.create();
// move anchor cols to the left, order wrt grouping hierarchy
List<GridColumnSettings> new_cols = null;
IEnumerable<GridColumnSettings> cols = s.grid.columns;
@@ -136,6 +137,7 @@ namespace bts.shell.pnl {
_last_loaded = value;
header_row_defaults.load(value.header_cell_appearance.to_appearance());
group_row_defaults.load_from((value.group_cell_appearance.to_appearance(), value.group_background_colors.WrapSelectorRO(c => c.argb_color())));
data_formatting_vm.load_from(value.data_formatting);
var column_map = _map_column_data(value.grid.columns, value.animations);
var group_column_map = _map_column_data(value.group_columns, value.group_header_animations);
var header_column_map = _map_column_data(value.header_columns, value.header_row_animations);
@@ -154,7 +156,7 @@ namespace bts.shell.pnl {
anchor_items.WrapSelector(a => a.key, k => _anchor_cache[k]).sync_with(value.anchors.Intersect(PNLSettings.anchorable_columns));
header_row_display = value.header_row_display;
calculation_type = value.calculation_type;
}
}
PNLSettings IValueFactory<PNLSettings>.create() => get_result();
void IValueFactory<PNLSettings>.load_from(PNLSettings value) => load(value);
@@ -55,11 +55,11 @@ namespace bts.shell.pnl {
}
class PNLCellVM<TRow, TValue> : ViewModelBase, IObserver<PNLAnimation>, IPNLCellVM<TRow>, IComparable<PNLCellVM<TRow, TValue>>, IComparable {
readonly Func<TValue, string> _fmt;
readonly Func<TRow, TValue> _get;
readonly IEqualityComparer<TValue> _eq_comparer;
readonly IComparer<TValue> _comparer;
readonly PNLView.Columns _column;
Func<TValue, string> _fmt;
IComparer _value_comparer;
Color
_foreground = Colors.Black,
@@ -123,6 +123,15 @@ namespace bts.shell.pnl {
set => Set(ref _font_weight, value);
}
public Func<TValue, string> format {
get => _fmt;
set {
_fmt = value;
_text = null;
RaisePropertyChanged(nameof(text));
}
}
public void on_row(TRow row) =>
value = _get(row);
@@ -22,7 +22,13 @@ namespace bts.shell.pnl {
bool _refresh_normalized_data = true, _is_selected;
PNLNormalizedData _normalized_data;
public PNLRowVM(PNLRowData data, ImmutableDictionary<ColumnKeys, PNLCellAppearance> default_appearances, IReadOnlyList<IPNLAnimationTrigger<PNLRowData>> triggers) {
public PNLRowVM(
PNLRowData data,
ImmutableDictionary<ColumnKeys, PNLCellAppearance> default_appearances,
IReadOnlyList<IPNLAnimationTrigger<PNLRowData>> triggers,
Func<double, string> fmt_fill_price,
Func<double, string> fmt_market_price) {
//
this.data = data;
_animator = new PNLCellEmbeddedAnimationModel<PNLRowData>(default_appearances, triggers);
_animator.on_row(data);
@@ -30,10 +36,10 @@ namespace bts.shell.pnl {
account_name_cell = _cell_map.add(ColumnKeys.Account, d => d.account_name);
security_type_cell = _cell_map.add(ColumnKeys.SecurityType, d => d.security?.ContractCase ?? Security.ContractOneofCase.None);
exchange_cell = _cell_map.add(ColumnKeys.Exchange, d => d.security?.Exchange ?? Venue.Unset);
symbol_cell = _cell_map.add(ColumnKeys.Symbol, d => d.security?.Symbol ?? string.Empty);
symbol_cell = _cell_map.add(ColumnKeys.Symbol, d => d.symbol);
security_cell = _cell_map.add(ColumnKeys.Security, d => (d.security), null, EqualityComparer<SecurityImmutable?>.Default, Comparer<SecurityImmutable>.Default.to_nullable());
security_key = _cell_map.add(ColumnKeys.SecurityKey, d => d.key.security_id);
cpp = _cell_map.add(ColumnKeys.CPP, d => d.cpp);
cpp = _cell_map.add(ColumnKeys.CPP, d => d.effective_cpp);
// sod
sod_pnl = _cell_map.add_pnl_double(ColumnKeys.SODPNL, d => d.sod_pnl);
sod_net_pos = _cell_map.add_net_pos(ColumnKeys.SODNetPos, d => d.display_sod_net_pos);
@@ -73,6 +79,7 @@ namespace bts.shell.pnl {
last_price = _cell_map.add_price_double(ColumnKeys.LastPrice, d => d.last_price);
settlement_price = _cell_map.add_price_double(ColumnKeys.SettlementPrice, d => d.settlement_price);
_set_price_formatting_delegates(fmt_fill_price, fmt_market_price);
_cell_map.on_row(data);
_cell_map.set_appearances(_animator.cell_appearances);
_dispose = _cell_map.animation_model.OnDispatcher().Subscribe(new_animations => {
@@ -185,6 +192,7 @@ namespace bts.shell.pnl {
public PNLCellVM<PNLRowData, double> pnl_price { get; }
public IList<mbts.ui.spark.CellAnimation> animations { get; private set; }
public bool is_selected {
get => _is_selected;
set {
@@ -193,6 +201,35 @@ namespace bts.shell.pnl {
}
}
IEnumerable<PNLCellVM<PNLRowData, double>> _market_price_cells {
get {
yield return pnl_price;
yield return last_price;
yield return bid_price;
yield return mid_price;
yield return ask_price;
yield return settlement_price;
}
}
// includes sod, day, total, and working avg price columns
IEnumerable<PNLCellVM<PNLRowData, double>> _fill_price_cells {
get {
// sod
yield return sod_long_avg_price;
yield return sod_short_avg_price;
// day
yield return day_long_avg_price;
yield return day_short_avg_price;
// total
yield return total_long_avg_price;
yield return total_short_avg_price;
// working
yield return working_long_avg_price;
yield return working_short_avg_price;
}
}
public void update(PNLRowData data) {
_refresh_normalized_data = true;
this.data = data;
@@ -201,9 +238,10 @@ namespace bts.shell.pnl {
_cell_map.set_appearances(_animator.cell_appearances);
}
public void on_settings(ImmutableDictionary<ColumnKeys, PNLCellAppearance> defaults, IReadOnlyList<IPNLAnimationTrigger<PNLRowData>> triggers) {
public void on_settings(ImmutableDictionary<ColumnKeys, PNLCellAppearance> defaults, IReadOnlyList<IPNLAnimationTrigger<PNLRowData>> triggers, Func<double, string> fmt_fill_price, Func<double, string> fmt_market_price) {
_animator.on_settings(defaults, triggers);
_cell_map.set_appearances(_animator.cell_appearances);
_set_price_formatting_delegates(fmt_fill_price, fmt_market_price);
}
public bool Equals(PNLRowVM other) =>
@@ -214,5 +252,14 @@ namespace bts.shell.pnl {
public override string ToString() =>
$"account: {account_name} exchange: {exchange} symbol: {symbol} security: {security} buy_quantity: {day_long_pos} sell_quantity: {day_short_pos} pnl: {total_pnl}";
void _set_price_formatting_delegates(Func<double, string> fmt_fill_price, Func<double, string> fmt_market_price) {
foreach (var cell in _fill_price_cells) {
cell.format = fmt_fill_price;
}
foreach (var cell in _market_price_cells) {
cell.format = fmt_market_price;
}
}
}
}
@@ -41,6 +41,9 @@ namespace bts.shell.pnl {
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly IObservableCollectionAddRemoveOnly<PNLRowVM> _selected_rows = new ObservableSortedCollection<PNLRowVM>(PNLRowVM.key_comparer);
/// treat <see cref="_rows_data_wrapper"/> and <see cref="_rows_key_wrapper"/>
/// as IReadOnlyLists - don't call any mutation methods.
/// The only reason they are ILists is for the binary_search methods.
readonly IList<PNLRowData> _rows_data_wrapper;
readonly IList<PNLKey> _rows_key_wrapper;
readonly DeferrableActionWrapper _refresh_filter;
@@ -51,6 +54,7 @@ namespace bts.shell.pnl {
IReadOnlyList<(ColumnKeys key, ListSortDirection direction)> _sorting_hierarchy;
Brush _selection_highlight;
Color _grid_background_color = Colors.Transparent;
Func<double, string> _fmt_fill_price_backing, _fmt_market_price_backing;
bool _is_paused;
// default appearances
ImmutableDictionary<ColumnKeys, PNLCellAppearance>
@@ -74,7 +78,7 @@ namespace bts.shell.pnl {
PNLVM(IBus bus, OrdersModel orders_model, PNLSettings settings, IObservable<TableUpdate<PNLRowData, PNLKey>> pnl_source) {
_bus = bus;
_orders_model = orders_model;
_rows_data_wrapper = rows.WrapSelector(r => r.data, d => new PNLRowVM(d, _default_appearances, _triggers));
_rows_data_wrapper = rows.WrapSelector(r => r.data, null);
_rows_key_wrapper = rows.WrapSelector(r => r.key, null);
_rows_view = new PNLRowCollectionView(rows, _default_group_appearances, _group_triggers);
_calculation_type = backing(nameof(calculation_type), PNLCalculationType.Waterfall);
@@ -88,6 +92,12 @@ namespace bts.shell.pnl {
});
// filters
account_filter = DiscreteValuesFilterVM.Common.account<PNLRowData>(orders_model, r => new AccountTuple(r.key.account_id, r.account_name), nameof(PNLRowVM.account_name));
symbol_filter = DiscreteValuesFilterVM.CreateTableUpdate<PNLRowData, string, string>(
r => r.symbol,
sym => sym,
out var symbol_filter_items_observer,
out var symbol_filter_items_view);
symbol_filter_items_view.CustomSort = Comparer<string>.Default.to_safe().to_non_generic();
_refresh_filter = new DeferrableActionWrapper(() => _filter_changed?.Invoke(get_filters_states().build_predicate()));
var filter_src = Observable.Create<Func<PNLRowData, bool>>(o => {
o.OnNext(get_filters_states().build_predicate());
@@ -108,9 +118,11 @@ namespace bts.shell.pnl {
).FilterWithRaw(filter_src, PNLRowData.key_fn, null)
.OnDispatcher()
.Subscribe(_update),
_symbols_source(pnl_source).OnDispatcher().Subscribe(symbol_filter_items_observer),
Disposable.Create(() => {
foreach (var f in _all_filters)
f.filter_changed -= _refresh_filter.execute;
_all_filters.OfType<IDisposable>().DisposeAll();
rows.DisposeAll();
_rows_view.Groups.OfTypeSafe<IDisposable>().DisposeAll();
}));
@@ -187,14 +199,14 @@ namespace bts.shell.pnl {
/// security
public IDataGridColumnPersistentFilter<PNLRowData, uint[]> account_filter { get; }
public IDataGridColumnPersistentFilter<PNLRowData, Venue[]> exchange_filter { get; } = DiscreteValuesFilterVM.Common.exchange<PNLRowData>(r => r.security.exchange_or_default(), nameof(PNLRowVM.exchange));
public IDataGridColumnPersistentFilter<PNLRowData, string[]> symbol_filter { get; } = DiscreteValuesFilterVM.Common.symbol<PNLRowData>(r => r.security.symbol_or_default(), nameof(PNLRowVM.symbol));
public IDataGridColumnPersistentFilter<PNLRowData, string[]> symbol_filter { get; }
public IDataGridColumnPersistentFilter<PNLRowData, string> security_filter { get; } = new RegexFilterVM<PNLRowData>(r => r.security?.ToString(), nameof(PNLRowData.security));
public IDataGridColumnPersistentFilter<PNLRowData, string> security_key_filter { get; } = new RegexFilterVM<PNLRowData>(r => r.key.security_id.ToString());
public IDataGridColumnPersistentFilter<PNLRowData, SecurityType[]> security_type_filter { get; } = DiscreteValuesFilterVM.Create<PNLRowData, SecurityType>(
EnumHelper.get_values_except(SecurityType.Option, SecurityType.Synthetic).ToArray(),
r => r.security?.ContractCase ?? SecurityType.None,
nameof(PNLRowData.security));
public IDataGridColumnPersistentFilter<PNLRowData, DoubleMinMaxState> cpp_filter { get; } = new DoubleMinMax<PNLRowData>(r => r.cpp);
public IDataGridColumnPersistentFilter<PNLRowData, DoubleMinMaxState> cpp_filter { get; } = new DoubleMinMax<PNLRowData>(r => r.effective_cpp);
/// sod
public IDataGridColumnPersistentFilter<PNLRowData, DoubleMinMaxState> sod_pnl_filter { get; } = new DoubleMinMax<PNLRowData>(r => r.sod_pnl);
public IDataGridColumnPersistentFilter<PNLRowData, DoubleMinMaxState> sod_long_pos_filter { get; } = new DoubleMinMax<PNLRowData>(r => r.sod.long_pos);
@@ -238,6 +250,15 @@ namespace bts.shell.pnl {
IEnumerable<IDataGridColumnFilter<PNLRowData>> _all_filters =>
_filter_getters.Select(get => get(this));
Func<double, string> _fmt_fill_price {
get => _fmt_fill_price_backing ?? FormattingDelegates.Price.Value;
set => _fmt_fill_price_backing = value;
}
Func<double, string> _fmt_market_price {
get => _fmt_market_price_backing ?? FormattingDelegates.Price.Value;
set => _fmt_market_price_backing = value;
}
public static IComparer<PNLRowVM> get_column_comparer(ColumnKeys column) =>
_get_column_comparer(column).row_comparer;
@@ -360,8 +381,10 @@ namespace bts.shell.pnl {
_triggers = settings.triggers();
_group_triggers = settings.group_triggers();
_header_triggers = settings.header_triggers();
_fmt_fill_price = settings.data_formatting?.fill_price_display?.get_formatting_delegate();
_fmt_market_price = settings.data_formatting?.market_price_display?.get_formatting_delegate();
foreach (var r in rows)
r.on_settings(_default_appearances, _triggers);
r.on_settings(_default_appearances, _triggers, _fmt_fill_price, _fmt_market_price);
total_aggregate.on_settings(settings.header_background_color, _default_header_appearances, _header_triggers);
selected_aggregate.on_settings(settings.header_background_color,_default_header_appearances, _header_triggers);
void map_appearances(ref ImmutableDictionary<ColumnKeys, PNLCellAppearance> from, IEnumerable<GridColumnSettings> col_settings, PNLCellAppearance fallback_appearance) {
@@ -542,6 +565,16 @@ namespace bts.shell.pnl {
yield return col_hash.Contains(c.id) ? c.with(is_visible: false) : c;
}
// combines the known system symbols
static IObservable<TableUpdate<string, string>> _symbols_source(IObservable<TableUpdate<PNLRowData, PNLKey>> pnl_source) =>
pnl_source
// ensure this fires once immediatey, because the known symbols are appended to the first update
// (observers shouldn't have to wait for the pnl source to tick to see them).
.StartWith(TableUpdate<PNLRowData, PNLKey>.mk_empty(PNLRowData.key_fn))
.distinct_on(PNLRowData.key_fn, r => r.symbol, s => s)
.Filter(sym => !string.IsNullOrEmpty(sym))
.AppendTable(mbts.co2.UserSymbol.get_all().Select(u => u.symbol).Distinct().ToList());
#region Fills Popup Utils
static void _append_key_filters(fills.FillsFilterStates f, ColumnKeys key) {
switch (key) {
@@ -734,7 +767,7 @@ namespace bts.shell.pnl {
}
}
foreach (var v in filtered.added) {
var r = new PNLRowVM(v.with(calc_type: calculation_type), _default_appearances, _triggers);
var r = new PNLRowVM(v.with(calc_type: calculation_type), _default_appearances, _triggers, _fmt_fill_price, _fmt_market_price);
rows.InsertSorted(r, PNLRowVM.key_comparer);
total_pnl += r.normalized_data;
}
@@ -619,7 +619,7 @@
<!--Symbol-->
<pnl:PNLColumn
c:DataGridFilterProperties.Filter="{Binding DataContext.symbol_filter, Source={u:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource {x:Static ft:DataGridFilterKnownTemplates.DiscreteValues}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource {x:Static ft:DataGridFilterKnownTemplates.DiscreteValuesCollectionView}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.symbol_filter.active, Source={u:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.symbol_filter.open, Source={u:DirectReference _grid}}"
key="Symbol"
@@ -1,4 +1,5 @@
using bts.api;
using bts.api.position;
using bts.shell.fills;
using bts.shell.manual_fills;
using bts.spark;
@@ -38,6 +39,7 @@ namespace bts.shell {
UserSettingsHub settings_hub,
OrdersModel orders_model,
md.MBOService mbo,
IPositionModel position_model,
ErrorReporter error_reporter) {
/// Unlike our <see cref="SparkCommand"/> members, <see cref="IShellWindowFactory"/> members must be instantiated immediately,
/// as they are responsible for launching windows in response to a SparkTag being published to the bus.
@@ -47,7 +49,7 @@ namespace bts.shell {
_fwf = new FillsWindowFactory(this, bus, settings_hub, orders_model);
_pnl_conf = new PNLConfig(mbts.config.Configuration.get<bts.config.PNLOptions>());
if (_pnl_conf.show_new_pnl)
_plwf = new PNLWindowFactory(this, bus, settings_hub, orders_model);
_plwf = new PNLWindowFactory(this, bus, settings_hub, orders_model, position_model);
if (_pnl_conf.show_old_pnl)
_old_plwf = new PAndLWindowFactory(this, bus, settings_hub, orders_model);
_aswf = new AlgoStudioWindowFactory(this, bus, orders_model, error_reporter);
@@ -0,0 +1,44 @@
using bts.spark;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Threading.Tasks;
namespace bts.api.position {
interface IPositionModel {
Task<bool> override_cpp_async(IEnumerable<(uint security_key, double cpp)> cpp_overrides);
}
[Export(typeof(IPositionModel))]
class PositionModel : IPositionModel {
readonly PositionService _position_service;
readonly ErrorReporter _error_reporter;
[ImportingConstructor]
public PositionModel(PositionService position_service, ErrorReporter error_reporter) {
_position_service = position_service ?? throw new ArgumentNullException(nameof(position_service));
_error_reporter = error_reporter ?? throw new ArgumentNullException(nameof(error_reporter));
}
public Task<bool> override_cpp_async(IEnumerable<(uint security_key, double cpp)> cpp_overrides) {
var sec_params_batch_op = new SecurityParametersBatchOp();
sec_params_batch_op.OpParams.AddRange(cpp_overrides.Select(tup => new SecurityParameters {
SecurityKey = tup.security_key,
CppOverride = new CppOverride { Value = tup.cpp }
}));
return _error_reporter.safe_execute(
() => _position_service.update_security_parameters_async(sec_params_batch_op),
r => r.Ok,
r => r.Msg,
(v, success) => success,
"override cpp");
}
}
static class PositionModelExtensions {
public static Task<bool> override_cpp_async(this IPositionModel position_model, IEnumerable<uint> security_keys, double cpp) =>
(position_model ?? throw new ArgumentNullException(nameof(position_model)))
.override_cpp_async(security_keys.Select(k => (k, cpp)));
}
}
@@ -30,7 +30,9 @@ namespace mbts.spark {
}
public SecurityAuxiliaryData? get_auxiliary_data(SecurityImmutable security) =>
_auxiliary_data.TryGetValue(security.Symbol, out var d) ? d : (SecurityAuxiliaryData?)null;
security.ToString().SafeContains("ICE Lots") ?
new SecurityAuxiliaryData(1) :
_auxiliary_data.TryGetValue(security.Symbol, out var d) ? d : (SecurityAuxiliaryData?)null;
}
static class SecurityAuxiliaryDataModelExtensions {
@@ -187,7 +187,7 @@ namespace mbts.collections {
}
}
class KeyedMultiSelector<T, TKey> : ViewModelBase where TKey : struct, IEquatable<TKey> {
class KeyedMultiSelector<T, TKey> : ViewModelBase where TKey : IEquatable<TKey> {
readonly Func<T, TKey> _key_selector;
HashSet<TKey> _desired_keys = new HashSet<TKey>();
@@ -204,7 +204,7 @@ namespace mbts.collections {
try_select(key, true);
public bool try_select(TKey key, bool reattempt_on_collection_change) {
if (items.TryGetFirst(i => _key_selector(i).Equals(key), out T result)) {
if (items.TryGetFirst(i => _key_selector(i).safe_equals(key), out T result)) {
selected_items.Add(result);
return true;
} else if (reattempt_on_collection_change) {
@@ -0,0 +1,34 @@
using ProtoBuf;
using System;
namespace bts.proto {
[ProtoContract]
readonly struct ToggleInt32Proto : IEquatable<ToggleInt32Proto> {
public ToggleInt32Proto(int value, bool is_enabled) {
this.value = value;
this.is_enabled = is_enabled;
}
[ProtoMember(1)]
public int value { get; }
[ProtoMember(2)]
public bool is_enabled { get; }
public bool Equals(ToggleInt32Proto other) =>
value == other.value && is_enabled == other.is_enabled;
public override bool Equals(object obj) =>
obj is ToggleInt32Proto other && Equals(other);
public override int GetHashCode() =>
(value % (1 << 31)) | (is_enabled ? 1 << 31 : 0);
public static bool operator ==(ToggleInt32Proto a, ToggleInt32Proto b) => a.Equals(b);
public static bool operator !=(ToggleInt32Proto a, ToggleInt32Proto b) => !a.Equals(b);
}
static class ToggleInt32ProtoExtensions {
public static int? as_nullable(this ToggleInt32Proto toggle) =>
toggle.is_enabled ? toggle.value : (int?)null;
}
}
@@ -59,6 +59,7 @@ namespace mbts.spark.filters {
ULongMinMax = "ULongMinMaxTemplate",
TimeFilter = "TimeFilterTemplate",
DiscreteValues = "DiscreteValuesTemplate",
DiscreteValuesCollectionView = "DiscreteValuesCollectionViewTemplate",
EnumValues = "EnumValuesTemplate",
Regex = "RegexTemplate",
YesNo = "YesNoTemplate";
@@ -70,7 +70,7 @@ namespace mbts.spark.filters {
out IObserver<TableUpdate<TValue, TKey>> items_observer,
out ListCollectionView<TValue> items_view,
string prop_name = null)
where TKey : struct, IEquatable<TKey> =>
where TKey : IEquatable<TKey> =>
//
CreateTableUpdate(factory, key, keys => keys, keys => keys.ToArray(), out items_observer, out items_view, prop_name);
@@ -82,7 +82,7 @@ namespace mbts.spark.filters {
out IObserver<TableUpdate<TValue, TKey>> items_observer,
out ListCollectionView<TValue> items_view,
string prop_name = null)
where TKey : struct, IEquatable<TKey> {
where TKey : IEquatable<TKey> {
//
var filter = new TableUpdateItemsFilter<TRow, TValue, TKey, TState>(factory, key, load_state, get_state, prop_name);
items_observer = filter;
@@ -282,7 +282,7 @@ namespace mbts.spark.filters {
}
}
class TableUpdateItemsFilter<TRow, TValue, TKey, TState> : FilterVMBase<TRow, TValue, TState>, IObserver<TableUpdate<TValue, TKey>> where TKey : struct, IEquatable<TKey> {
class TableUpdateItemsFilter<TRow, TValue, TKey, TState> : FilterVMBase<TRow, TValue, TState>, IObserver<TableUpdate<TValue, TKey>> where TKey : IEquatable<TKey> {
readonly ObservableKeyedCollection<TValue, TKey> _items;
readonly KeyedMultiSelector<TValue, TKey> _selection_model;
readonly Func<TValue, TKey> _key;
@@ -1,10 +1,13 @@
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:msp="clr-namespace:mbts.spark"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:filters="clr-namespace:mbts.spark.filters"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:usp="clr-namespace:mbts.ui.spark"
xmlns:msp="clr-namespace:mbts.spark"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Resources/ComboBoxes.xaml"/>
<ResourceDictionary Source="/view/Controls/DataGridEx/Filters/Views/DoubleMinMaxFilterControl.xaml"/>
@@ -147,6 +150,21 @@
/>
</usp:FilterContentControl>
</DataTemplate>
<DataTemplate x:Key="{x:Static filters:DataGridFilterKnownTemplates.DiscreteValuesCollectionView}">
<usp:FilterContentControl
ApplyCommandParameter="{Binding}"
ApplyCommand="{x:Static c:DataGridFilterProperties.CommitCommand}"
ClearCommandParameter="{Binding}"
ClearCommand="{x:Static c:DataGridFilterProperties.ClearCommand}"
>
<c:ListBoxEx
ItemsSource="{Binding items_view}"
Selection="{Binding selected_items}"
SelectionMode="Multiple"
ItemContainerStyle="{StaticResource ListBoxItemCheckBoxStyle}"
/>
</usp:FilterContentControl>
</DataTemplate>
<DataTemplate x:Key="AlgoTypeTemplate">
<usp:FilterContentControl
ApplyCommandParameter="{Binding}"
@@ -0,0 +1,38 @@
<ResourceDictionary
x:Class="mbts.ui.controls.property_editor.PropertyEditorResources"
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:mbts.ui.controls"
xmlns:pe="clr-namespace:mbts.ui.controls.property_editor"
>
<Thickness x:Key="PropertyLabelMargin" Left="0" Top="4" Right="4"/>
<Thickness x:Key="PropertyValueMargin" Top="4"/>
<DataTemplate DataType="{x:Static pe:PropertyEditorItemTypes.DoubleItem}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center" Margin="{StaticResource PropertyLabelMargin}" Text="{Binding name}"/>
<c:TickUpDownDouble Grid.Column="1" VerticalAlignment="Center" Margin="{StaticResource PropertyValueMargin}" Value="{Binding value}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type pe:PropertyEditorVM}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ItemsControl ItemsSource="{Binding properties}" Margin="8,4"/>
<c:DialogSkirt Grid.Row="1">
<c:DialogSkirt.RightItems>
<x:Array Type="{x:Type Button}">
<Button IsDefault="True" Command="{Binding commit_cmd}">OK</Button>
<Button IsCancel="True" Command="{Binding cancel_cmd}">Cancel</Button>
</x:Array>
</c:DialogSkirt.RightItems>
</c:DialogSkirt>
</Grid>
</DataTemplate>
</ResourceDictionary>
@@ -0,0 +1,122 @@
using mbts.spark;
using mbts.ui.utilities;
using mbts.ui.utility;
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace mbts.ui.controls.property_editor {
partial class PropertyEditorResources : ResourceDictionary {
public PropertyEditorResources() {
InitializeComponent();
}
}
static class PropertyEditor {
static int _window_id;
public static Task<(double value, bool committed)> get_double_async(
string title,
string prompt,
CancellationToken cancellation_token,
double initial_value = 0,
Func<double, string> validate = null,
WindowStartupLocation startup_location = WindowStartupLocation.Manual,
int? offset_x = -72,
int? offset_y = -40) {
//
PropertyEditorItem<double> double_item = null;
return get_result_async(create_vm, _ => (double_item?.value ?? double.NaN, true), cancellation_token, init, tcs => tcs.TrySetResult((double.NaN, false)));
PropertyEditorVM create_vm() {
var vm = new PropertyEditorVM(title, prompt);
vm.properties.Add(double_item = new PropertyEditorItem<double>(prompt, validate) {
value = initial_value
});
return vm;
}
IDisposable init(PropertyEditorVM vm, Window dialog) {
_position_window(dialog, startup_location, offset_x, offset_y);
return null;
}
}
public static Task<TResult> get_result_async<TResult>(
Func<PropertyEditorVM> create_vm,
Func<PropertyEditorVM, TResult> get_result,
CancellationToken cancellation_token,
Func<PropertyEditorVM, Window, IDisposable> init = null,
Action<TaskCompletionSource<TResult>> premature_close_callback = null) {
//
var tcs = new TaskCompletionSource<TResult>();
var window_name = $"{nameof(PropertyEditor)} - {Interlocked.Increment(ref _window_id)}";
var launcher = new ThreadedWindowLauncher(window_name, 1);
launcher.show(create_win_impl);
return tcs.Task;
Window create_win_impl() {
var vm = create_vm();
var win = new Window {
DataContext = vm,
Resources = new PropertyEditorResources(),
SizeToContent = SizeToContent.WidthAndHeight
};
win.SetResourceReference(FrameworkElement.StyleProperty, "BTSDialog");
win.SetBinding(ContentControl.ContentProperty, new Binding());
win.SetBinding(Window.TitleProperty, nameof(PropertyEditorVM.title));
var dispose = init?.Invoke(vm, win);
IDisposable check_canceled_loop = null;
vm.RequestCommit += on_request_commit;
vm.RequestClose += on_request_close;
win.Closed += on_premature_closed;
check_canceled_loop = WorkLoop.Start($"{window_name} cancellation loop", () => {
if (cancellation_token.IsCancellationRequested && win != null) {
Disposable.dispose(ref check_canceled_loop);
WindowUtilities.force_close(win);
}
});
return win;
void on_request_commit(object sender, EventArgs e) {
detach_and_dispose();
WindowUtilities.force_close(win);
win = null;
end_task()?.TrySetResult(get_result(vm));
}
void on_request_close(object sender, EventArgs e) {
detach_and_dispose();
WindowUtilities.force_close(win);
win = null;
premature_close_callback?.Invoke(end_task());
}
void on_premature_closed(object sender, EventArgs e) {
detach_and_dispose();
win = null;
premature_close_callback?.Invoke(end_task());
}
void detach_and_dispose() {
Disposable.dispose(ref check_canceled_loop);
Disposable.dispose(ref dispose);
win.Closed -= on_premature_closed;
vm.RequestCommit -= on_request_commit;
vm.RequestClose -= on_request_close;
}
TaskCompletionSource<TResult> end_task() {
var temp_tcs = tcs;
tcs = null;
return temp_tcs;
}
}
}
static void _position_window(Window window, WindowStartupLocation startup_location, int? offset_x = null, int? offset_y = null) {
window.WindowStartupLocation = startup_location;
if (startup_location == WindowStartupLocation.Manual && (offset_x.HasValue || offset_y.HasValue))
window.move_to_mouse(offset_x ?? 0, offset_y ?? 0);
}
}
static class PropertyEditorItemTypes {
public static Type DoubleItem => typeof(PropertyEditorItem<double>);
}
}
@@ -0,0 +1,62 @@
using mbts.ui.shell;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows.Input;
namespace mbts.ui.controls.property_editor {
interface IPropertyEditorItem : INotifyPropertyChanged {
string name { get; }
object value { get; set; }
}
interface IPropertyEditorItem<T> : IPropertyEditorItem {
new T value { get; set; }
}
class PropertyEditorItem<T> : ViewModelBaseWithValidation, IPropertyEditorItem<T> {
readonly Func<T, string> _validate;
T _value;
public PropertyEditorItem(string name, Func<T, string> validate) {
this.name = name ?? throw new ArgumentNullException(nameof(name));
_validate = validate;
}
public string name { get; }
public T value {
get => _value;
set {
if (_validate == null) {
Set(ref _value, value);
} else {
using (validation(nameof(value))) {
Set(ref _value, value);
string error = _validate(value);
validation_assert(error != null, error, nameof(value));
}
}
}
}
object IPropertyEditorItem.value { get => value; set => value = (T)value; }
}
class PropertyEditorVM : ViewModelBase, IRequestViewClose {
public PropertyEditorVM(string title, string prompt) {
this.title = title ?? throw new ArgumentNullException(nameof(title));
this.prompt = prompt ?? throw new ArgumentNullException(nameof(prompt));
commit_cmd = new DelegateCommand(() => RequestCommit?.Invoke(this, EventArgs.Empty));
cancel_cmd = new DelegateCommand(() => RequestClose?.Invoke(this, EventArgs.Empty));
}
public event EventHandler RequestCommit, RequestClose;
public string title { get; }
public string prompt { get; }
public ObservableCollection<object> properties { get; } = new ObservableCollection<object>();
public ICommand commit_cmd { get; }
public ICommand cancel_cmd { get; }
}
}
@@ -2,6 +2,7 @@
using System;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
namespace mbts.ui {
@@ -51,15 +52,19 @@ namespace mbts.ui {
public void thread_init() { }
}
public static IShellWindow create(IShellModule owner, string title, string window_type, Lazy<UIElement> content, Action<UIElement, Stream> get_state = null, ImageSource icon = null, string thread_id=null, Action<ShellWindowVM> on_shell_window_vm = null) {
public static IShellWindow create(IShellModule owner, string title, string window_type, Lazy<UIElement> content, Action<UIElement, Stream> get_state = null, ImageSource icon = null, string thread_id=null, Action<ShellWindowVM> on_shell_window_vm = null, Action<KeyEventArgs> on_key_down = null) {
IShellWindow rv = null;
if (string.IsNullOrEmpty(thread_id)) {
return create<AnonShellWindow>(owner, title, window_type, content, get_state, icon, on_shell_window_vm);
rv = create<AnonShellWindow>(owner, title, window_type, content, get_state, icon, on_shell_window_vm);
if (on_key_down != null)
rv = new KeyListenerWrapper(rv, on_key_down);
}
else {
var res = create<LazyAnonShellWindow>(owner, title, window_type, content, get_state, icon, on_shell_window_vm);
res.thread_id = thread_id;
return res;
rv = on_key_down == null ? (ISharedWindow)res : new SharedKeyListenerWrapper(res, on_key_down);
}
return rv;
}
static T create<T>(IShellModule owner, string title, string window_type, Lazy<UIElement> content, Action<UIElement,Stream> get_state=null, ImageSource icon=null, Action<ShellWindowVM> on_shell_window_vm = null) where T : AnonShellWindow, new() {
var result = new T() {
@@ -121,5 +126,56 @@ namespace mbts.ui {
if (cleanup != null) { window.Closed += (o, e) => cleanup.Dispose(); }
return window;
}
class KeyListenerWrapper<T> : IShellWindow, IKeyListener where T : class, IShellWindow {
readonly T _model;
readonly Action<KeyEventArgs> _key_down;
public KeyListenerWrapper(T model, Action<KeyEventArgs> key_down) {
_model = model ?? throw new ArgumentNullException(nameof(model));
_key_down = key_down ?? throw new ArgumentNullException(nameof(key_down));
}
public event Action TitleChanged {
add => _model.TitleChanged += value;
remove => _model.TitleChanged -= value;
}
public event Action IconChanged {
add => _model.IconChanged += value;
remove => _model.IconChanged -= value;
}
public string Title { get => _model.Title; set => _model.Title = value; }
public string window_type => _model.window_type;
public ImageSource Icon => _model.Icon;
public IShellModule Owner => _model.Owner;
public void Dispose() => _model.Dispose();
public ShellWindowUI GetContent() => _model.GetContent();
public void GetState(Stream save_here) => _model.GetState(save_here);
public void on_shell_window_vm(ShellWindowVM shell_window_vm) => _model.on_shell_window_vm(shell_window_vm);
public void key_down(KeyEventArgs e) =>
_key_down(e);
}
class KeyListenerWrapper : KeyListenerWrapper<IShellWindow> {
public KeyListenerWrapper(IShellWindow model, Action<KeyEventArgs> key_down)
: base(model, key_down) { }
}
class SharedKeyListenerWrapper : KeyListenerWrapper<ISharedWindow>, ISharedWindow {
readonly ISharedWindow _model;
readonly Action<KeyEventArgs> _key_down;
public SharedKeyListenerWrapper(ISharedWindow model, Action<KeyEventArgs> key_down)
: base(model, key_down) {
_model = model ?? throw new ArgumentNullException(nameof(model));
_key_down = key_down ?? throw new ArgumentNullException(nameof(key_down));
}
public string thread_id => _model.thread_id;
public void thread_init() => _model.thread_init();
}
}
}
@@ -87,6 +87,25 @@
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type pnl:PNLDataFormattingVM}">
<Grid VerticalAlignment="Top">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush1}}"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush2}}"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock>Market Price Decimal Places</TextBlock>
<ComboBox Grid.Column="2" ItemsSource="{Binding decimal_place_options}" SelectedItem="{Binding market_price_decimal_places}"/>
<TextBlock Grid.Row="2">Fill Price Decimal Places</TextBlock>
<ComboBox Grid.Row="2" Grid.Column="2" ItemsSource="{Binding decimal_place_options}" SelectedItem="{Binding fill_price_decimal_places}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="{x:Type pnl:PNLCellAppearanceVM}">
<Grid VerticalAlignment="Top">
<Grid.RowDefinitions>
@@ -744,6 +763,7 @@
</DataTemplate>
</TabItem.ContentTemplate>
</TabItem>
<TabItem Header="Data Formatting" Content="{Binding data_formatting_vm}"/>
</TabControl>
</Grid>
</DataTemplate>
@@ -10,6 +10,7 @@ using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace mbts.ui.shell {
// This Class owns the hierarchy of shell Windows
@@ -59,6 +60,14 @@ namespace mbts.ui.shell {
viewmodel.host_id = state.host_id ?? "";
viewmodel.TitleOverride = state.custom_title;
}
if (model is IKeyListener key_listener) {
content.KeyDown += on_key_down;
void on_key_down(object sender, KeyEventArgs e) {
viewmodel.Dispatcher.InvokeAsync(() => {
key_listener.key_down(e);
});
}
}
var window = await CreateWindow(content, state);
window.Show();
@@ -111,7 +111,9 @@ namespace mbts.spark {
raw_mid = (bid + ask) / 2.0;
}
double tick_size = spec.ticksize(raw_mid);
return raw_mid - (raw_mid % tick_size);
return raw_mid < 0 ?
raw_mid + (raw_mid % tick_size) :
raw_mid - (raw_mid % tick_size);
}
public static TickFactors deduce_ticks(IEnumerable<ContractSpecification> contract_specs) {
@@ -13,5 +13,8 @@ namespace bts.utils {
[Pure]
public static bool IsNullOrEmpty(this string str) =>
string.IsNullOrEmpty(str);
public static bool SafeContains(this string str, string value) =>
str != null && str.Contains(value);
}
}
@@ -11,6 +11,35 @@ using System.Reactive.Linq;
namespace bts.utils {
public static class UpdateExtensions {
public static IObservable<TableUpdate<T, TKey>> AppendTable<T, TKey>(this IObservable<TableUpdate<T, TKey>> source, IEnumerable<T> append_items) where TKey : IEquatable<TKey> {
HashSet<TKey> append_keys = null;
Func<T, bool> append_key_filter = null;
return Observable.Create<TableUpdate<T, TKey>>(o => {
TableUpdate<T, TKey> output = null;
return source.Subscribe(table => {
if (output == null) {
// first update - initialize output, and (maybe) append_keys/append_key_filter
// Note: append_keys/filter can be shared among all subscriptions because, and only needs to be initialized once;
// once initialized, the append_keys/filter will not change.
output = table;
if (append_keys == null) {
append_keys = new HashSet<TKey>(append_items.Select(table.key_extractor));
append_key_filter = v => !append_keys.Contains(table.key_extractor(v));
}
// filter append_items out of the normal source (ensures that they will be immune to removes/changes).
output = TableUpdate<T, TKey>.FilterHelper.on_predicate_changed(output, table.state, null, append_key_filter);
// add the append_items to the output table (only need to do this once)
output = TableUpdate<T, TKey>.update(output, append_items, Enumerable.Empty<Change<T>>(), Enumerable.Empty<T>(), table.key_extractor);
output = output.as_snapshot();
} else {
output = TableUpdate<T, TKey>.FilterHelper.on_source_changed(
output, table.added, table.changes, table.removed, append_key_filter);
}
o.OnNext(output);
});
});
}
public static TableUpdate<T, TKey> with_added<T, TKey>(this TableUpdate<T, TKey> table, IEnumerable<T> added) where TKey : IEquatable<TKey> =>
TableUpdate<T, TKey>.update(table, added, Enumerable.Empty<Change<T>>(), Enumerable.Empty<T>(), table.key_extractor);
@@ -80,6 +80,10 @@ void PositionUtilities::apply_fill (PositionEntry& pos,
void PositionUtilities::apply_fill (PositionEntry& pos,
const Fill& f,
bool is_add){
// strip legs are not applied to positions
if(f.fill_kind() == Fill::FILL_KIND_STRIP_LEG ||
f.fill_kind() == Fill::FILL_KIND_SOD_STRIP_LEG)
return;
PositionUtilities::apply_fill(pos,
f.side(),
f.last_price(),
+3
View File
@@ -331,6 +331,9 @@ message Fill {
FILL_KIND_STANDARD = 0;
FILL_KIND_LEG = 1;
FILL_KIND_SOD = 2;
FILL_KIND_STRIP_LEG = 3;
FILL_KIND_SOD_SPREAD_LEG = 4;
FILL_KIND_SOD_STRIP_LEG = 5;
}
FillKind fill_kind = 10;
+2 -1
View File
@@ -43,7 +43,8 @@ message PositionUnit{
message PNLUnit{
int32 record_id = 1 [(bts.api.key)=true];
PositionUnit pos = 10;
double cash_value = 20;
double cash_value = 20;
CppOverride cpp_override = 21;
double bid_price = 30;
double ask_price = 40;
double last_price = 50;
+38
View File
@@ -18,6 +18,7 @@ namespace bts {
namespace api {
class Security;
class ICEExchangeData;
}
namespace securities {
@@ -212,5 +213,42 @@ inline bool gr_than(double p1, double p2, double tick_size) {
!test_price_equality(p1, p2, tick_size);
}
// Works only if ICEExchangeData is part of the a spread security
// inline bool is_ice_strip(const bts::api::ICEExchangeData& ice_data){
// return ice_data.is_strip();
// }
inline bool is_ice_strip(const bts::api::ICEExchangeData& ice_data){
// TODO, put this in the security
const auto& strip = ice_data.strip_name();
auto find = [&](const std::string& sub) -> bool {
return strip.find(sub) != std::string::npos;
};
if(!find("/"))
return find("-") ||
find("Q1") || find("Q2") || find("Q3") || find("Q4") ||
find("Cal");
else
return false;
}
inline bool is_strip(const bts::api::Security& sec){
if(sec.has_spread())
if (sec.has_ice())
return is_ice_strip(sec.ice());
return false;
}
inline bool is_spread_of_strips(const bts::api::Security& sec){
if(sec.has_spread())
if (sec.has_ice()){
const auto& spr = sec.spread();
for (const auto& l : spr.legs())
// assumption : either all legs are strips or none
return is_strip(l.security());
}
return false;
}
} // namespace securities
} // namespace bts
+1
View File
@@ -115,6 +115,7 @@ message ICEExchangeData {
string hub_alias = 130;
string strip_name = 140;
string mic_code = 150;
bool is_strip = 160;
}
message FutureContract {
+2 -2
View File
@@ -786,9 +786,9 @@ OutFIXPtr make_logon(uint32_t seq_num, uint32_t last_seq_num_processed,
if(session_cfg.platform() == bts::config::JetFIX_Connection_JetFIXPlatform_ICE ||
session_cfg.platform() == bts::config::JetFIX_Connection_JetFIXPlatform_SIMICE)
{
buffer.add<ICEApplicationSystemName>(application);
buffer.add<ICEApplicationSystemName>("Katallage");
buffer.add<ICEApplicationSystemVersion>("1.0");
buffer.add<ICEApplicationSystemVendor>("BTS");
buffer.add<ICEApplicationSystemVendor>("Katallage");
buffer.add<UserName>(session_cfg.user_name());
buffer.add<RawDataLength>(session_cfg.raw_data().size());
+3
View File
@@ -34,6 +34,7 @@ FixedSecurity::FixedSecurity() :
ice_price_denominator(0),
ice_deal_denominator(0),
ice_settle_denominator(0),
is_ice_strip(false),
_symbol(),
_cfi_code(),
_security_desc(),
@@ -195,6 +196,7 @@ void convert_security(const FixedSecurity& source, Security* presult) {
dest.mutable_ice()->set_hub_alias(source.ice_hub_alias());
dest.mutable_ice()->set_strip_name(source.ice_strip_name());
dest.mutable_ice()->set_mic_code(source.mic_code());
dest.mutable_ice()->set_is_strip(source.is_ice_strip);
break;
case Venue::VENUE_BTS:
break;
@@ -320,6 +322,7 @@ void convert_security(const Security& src, FixedSecurity& dest, bool set_securit
dest.ice_price_denominator = src.ice().price_denominator();
dest.ice_deal_denominator = src.ice().deal_denominator();
dest.ice_settle_denominator = src.ice().settle_denominator();
dest.is_ice_strip = src.ice().is_strip();
dest.ice_market_description(src.ice().market_description());
dest.ice_cleared_alias(src.ice().cleared_alias());
+1
View File
@@ -62,6 +62,7 @@ public:
int8_t ice_price_denominator;
int8_t ice_deal_denominator;
int8_t ice_settle_denominator;
bool is_ice_strip;
STRING_PROPERTY(ice_market_description);
STRING_PROPERTY(ice_cleared_alias);
+51 -3
View File
@@ -39,6 +39,51 @@ struct FillStore::PImpl {
FillStore::FillStore(md::SecurityOracle o) : me(new PImpl(o)) {}
auto sod_fill_kind (const api::orderman::Fill& fill){
auto rv = Fill::FILL_KIND_SOD;
switch (fill.fill_kind()){
case Fill::FILL_KIND_STANDARD:
rv = Fill::FILL_KIND_SOD;
break;
case Fill::FILL_KIND_LEG:
rv = Fill::FILL_KIND_SOD_SPREAD_LEG;
break;
case Fill::FILL_KIND_STRIP_LEG:
rv = Fill::FILL_KIND_SOD_STRIP_LEG;
break;
default:
rv = Fill::FILL_KIND_SOD;
break;
}
return rv;
}
auto leg_fill_kind (const api::Security& parent,
const api::Security& child){
if (parent.has_ice()){
if(securities::is_strip(parent))
return Fill::FILL_KIND_STRIP_LEG;
else{
// parent is a spread
if(securities::is_spread_of_strips(parent)){
// this has 3 levels strip spread -> strip -> outright
// first level is an ordinary leg and second is a strip leg.
// since we dont get the level passed we have to
// use the following heurestics
if(securities::is_strip(child))
return Fill::FILL_KIND_LEG;
else
return Fill::FILL_KIND_STRIP_LEG;
}
else
// regular spread
return Fill::FILL_KIND_LEG;
}
}
return Fill::FILL_KIND_LEG;
}
void FillStore::init() {
// Subscribe to NewExecutionReportEvent for new fills
@@ -54,8 +99,10 @@ void FillStore::init() {
SODPosition sod_helper;
for (auto const &kvp : all)
if (utils::pb::from_string<api::orderman::Fill>(kvp.second, &fill)) {
if (sod_helper.is_sod(fill.timestamp()))
fill.set_fill_kind(Fill::FILL_KIND_SOD);
if (sod_helper.is_sod(fill.timestamp())){
auto fill_kind = sod_fill_kind(fill);
fill.set_fill_kind(fill_kind);
}
auto sec = me->oracle.get_security(SecurityKey(fill.security_key()));
if (sec) {
auto fk = kvp.first;
@@ -103,7 +150,8 @@ void FillStore::on_execution_report(
if (!is_known) {
fill.set_order_key(er.order_key.value());
if (er.leg_security) {
fill.set_fill_kind(api::orderman::Fill::FILL_KIND_LEG);
auto leg_type = leg_fill_kind(*er.security,*er.leg_security);
fill.set_fill_kind(leg_type);
fill.set_security_key(er.leg_security->id());
} else {
fill.set_fill_kind(api::orderman::Fill::FILL_KIND_STANDARD);
+8 -8
View File
@@ -620,7 +620,7 @@ OrderOpResult ICENativeOrder::on_update(api::orderman::Update const &update)
if (me->state.last_msg().size())
me->state.set_last_msg("");
LOG(OrderMan, Warn,
LOG(OrderMan, Info,
"ICE may not honor this update if we recently issued an unacknowledged cancelreplace {}. Update: {}@{}. Buffering",
key().value(), q.value(), p.value());
me->buffered_update.emplace(p, q);
@@ -807,7 +807,7 @@ void ICENativeOrder::on_exe_report(const NewExecutionReportEvent &er)
if(er.data->exec_type == api::orderman::ExecType::EXEC_TYPE_TRADE_CANCEL ||
er.data->exec_type == api::orderman::ExecType::EXEC_TYPE_TRADE_CORRECT)
{
LOG(OrderMan, Info, "ICENativeOrder ignoring Cancel or Correct execution report {} in order {}", er.data->msg_seq_num, key().value());
LOG(OrderMan, Error, "ICENativeOrder ignoring Cancel or Correct execution report {} in order {}", er.data->msg_seq_num, key().value());
return;
}
@@ -934,7 +934,7 @@ void ICENativeOrder::handle_buffered_state(const std::string& condition)
{
if (me->buffered_cancel)
{
LOG(OrderMan, Warn,
LOG(OrderMan, Info,
"Applying buffered cancel to order {}, on ",
condition,
key().value());
@@ -943,7 +943,7 @@ void ICENativeOrder::handle_buffered_state(const std::string& condition)
else if (me->buffered_update.has_value())
{
auto [p, q] = me->buffered_update.value();
LOG(OrderMan, Warn,
LOG(OrderMan, Info,
"Applying buffered update ({}@{}) to order {}, on ",
condition,
q.value(),p.value(), key().value());
@@ -1106,14 +1106,14 @@ void ICENativeOrder::init_fix()
create_encoding.add<fix::Memo>(memo);
me->create_clordid_bm = create_encoding.add<fix::Int_ClOrdID>(get_clordid(0), ice_orderid_sz());
create_encoding.add<fix::CompanyID>(std::atoi(rr.company_id().c_str()));
//create_encoding.add<fix::OnBehalfOfCompID>(""); //optional, unclear if we need
create_encoding.add<fix::OnBehalfOfCompID>("Katallage|Katallage");
std::string cust = rr.cust_order_handing_inst();
if(cust == "")
cust = "Y";
create_encoding.add<fix::CustOrderHandlingInst>(cust);
create_encoding.add<fix::SenderSubID>(rr.operator_id());
create_encoding.add<fix::OnBehalfOfSubID>(rr.operator_id() + "|" + rr.authorized_trader());
create_encoding.add<fix::OnBehalfOfLocationID>("ISV-BTS|" + rr.authorized_group());
create_encoding.add<fix::OnBehalfOfLocationID>("DAU|" + rr.authorized_group());
create_encoding.add<fix::OriginatorUserID>(rr.authorized_trader());
create_encoding.add<fix::HandlInst>('1');
create_encoding.add<fix::Int_Symbol>(sec.ice().exchange_id());
@@ -1137,10 +1137,10 @@ void ICENativeOrder::init_fix()
update_encoding.add<fix::Memo>(memo);
me->update_orig_clordid_bm = update_encoding.add<fix::Int_OrigClOrdID>(get_clordid(0), ice_orderid_sz());
update_encoding.add<fix::CompanyID>(std::atoi(rr.company_id().c_str()));
//update_encoding.add<fix::OnBehalfOfCompID>(""); //optional, unclear if we need
update_encoding.add<fix::OnBehalfOfCompID>("Katallage|Katallage");
update_encoding.add<fix::SenderSubID>(rr.operator_id());
update_encoding.add<fix::OnBehalfOfSubID>(rr.operator_id() + "|" + rr.authorized_trader());
update_encoding.add<fix::OnBehalfOfLocationID>("ISV-BTS|" + rr.authorized_group());
update_encoding.add<fix::OnBehalfOfLocationID>("DAU|" + rr.authorized_group());
update_encoding.add<fix::OriginatorUserID>(rr.authorized_trader());
update_encoding.add<fix::HandlInst>('1');
update_encoding.add<fix::Int_Symbol>(sec.ice().exchange_id());
@@ -84,7 +84,7 @@ void ICEListener::onFuturesProductDefinition(const onixs_ice::FuturesProductDefi
on_future_strip(msg, is_interested);
else
on_future(msg, is_interested);
LOG(md,Info,"ICE_Future,{},{},{},{},{},{},{},{},{},{},{},{},{}",
LOG(md,Diag,"ICE_Future,{},{},{},{},{},{},{},{},{},{},{},{},{}",
is_interested,
msg.productName, // NG Swing GDD Futures,
msg.hubAlias, // Henry
@@ -108,7 +108,7 @@ void ICEListener::onNewExpiry(const onixs_ice::NewExpiry& msg, bool& is_interest
void ICEListener::onFuturesStrategyDefinition(const onixs_ice::FuturesStrategyDefinition& msg, bool& is_interested)
{
on_uds_future_spread(msg, is_interested);
LOG(md,Info,"ICE_Strategy,{},{},{},{},{},{},{},{},{},{},{},{},{},{}",
LOG(md,Diag,"ICE_Strategy,{},{},{},{},{},{},{},{},{},{},{},{},{},{}",
is_interested,
msg.productName,
msg.hubAlias,
@@ -187,7 +187,11 @@ void ICEListener::onMarketStatistics(const onixs_ice::MarketStatistics& msg, con
if (data != nullptr)
{
bts_assert(data->id == msg.marketId);
auto ts = utils::TimeStamp::now();
auto deal_denominator = data->handle.security().ice_deal_denominator;
data->handle.set_total_volume(msg.volume);
data->handle.update_session_high( ts, double_of_price(msg.high, deal_denominator) );
data->handle.update_session_low( ts, double_of_price(msg.low, deal_denominator) );
}
}
@@ -334,7 +338,7 @@ void ICEListener::onSettlementPrice(const onixs_ice::SettlementPrice& msg, const
auto price = msg.settlementPrice;
auto time = msg.dateTime;
auto denominator = data->handle.security().ice_settle_denominator;
LOG(md,Diag,"OnixSICE Got Settlement: {} - {}", std::to_string(data->id), std::to_string(price));
LOG(md,Info,"OnixSICE Got Settlement: {} - {}", std::to_string(data->id), std::to_string(price));
data->handle.update_settlement(ts, convert_price(price, denominator), date_of_timestamp(time));
}
}
@@ -382,7 +386,7 @@ void ICEListener::onEndOfDayMarketSummary(const onixs_ice::EndOfDayMarketSummary
auto settle_denominator = data->handle.security().ice_settle_denominator;
data->handle.update_settlement( ts, convert_price(msg.settlementPrice, settle_denominator), date_of_timestamp(time) );
LOG(md,Warn,"OnixSICE Got EOD Market : {} - {}", std::to_string(data->id), std::to_string(msg.settlementPrice));
LOG(md,Info,"OnixSICE Got EOD Market : {} - {}", std::to_string(data->id), std::to_string(msg.settlementPrice));
auto deal_denominator = data->handle.security().ice_deal_denominator;
data->handle.update_opening( ts, double_of_price(msg.openingPrice, deal_denominator), date_of_timestamp(time) );
@@ -124,8 +124,13 @@ private:
const auto& sym = def.contractSymbol;
// TODO : this is only exception right now but for HHD sstrips
// def.contractSymbol is empty !
if (sym.size() == 0 && def.marketDesc.rfind("NG Swing GDD Futures - Henry", 0) == 0)
if (sym.size() == 0 &&
(
def.marketDesc.rfind("NG Swing GDD Futures - Henry", 0) == 0 ||
def.marketDesc.rfind("NG GDD for LD1 Futures Spr - Henry", 0) == 0
))
return "HHD";
auto end = sym.find(' ');
if(end == std::string::npos)
return sym;
@@ -265,7 +270,8 @@ void ICEListener::on_future_strip(const FutureDefinition& def, bool& is_interest
FixedSpreadSecurityXL fsec;
set_security_common(def, fsec);
fsec.alt_symbol(def.stripName);
fsec.is_ice_strip = true;
fsec.alt_symbol(def.stripName);
fsec.set_leg_count(2);
for(size_t x = 0; x < fsec.leg_count(); ++x)
@@ -145,15 +145,16 @@ void PositionServicePNLHelper::compute_pnl(
for (const auto& p : in_pos) {
const PositionUnit& pu = *(p.second);
uint32_t sec_key = pu.security_id();
double cpp = me->handle_index.get_cpp(SecurityKey(sec_key));
auto it = cpp_override_map.find(sec_key);
cpp = (it != cpp_override_map.end()) ? it->second : cpp;
double cpp = me->handle_index.get_cpp(SecurityKey(sec_key));
double bid, ask, last, settle;
me->handle_index.get_md(SecurityKey(sec_key),bid,ask,last,settle);
PNLUnit pnlu;
pnlu.set_record_id(pu.record_id());
pnlu.mutable_pos()->CopyFrom(pu);
pnlu.set_cash_value(cpp);
auto it = cpp_override_map.find(sec_key);
if(it != cpp_override_map.end())
pnlu.mutable_cpp_override()->set_value(it->second);
pnlu.set_bid_price(bid);
pnlu.set_ask_price(ask);
pnlu.set_last_price(last);
@@ -323,27 +323,28 @@ void PositionServiceServer::set_base_position(
}
void PositionServiceServer::update_security_parameters(
const SecurityParametersBatchOp& req,
const SecurityParametersBatchOp&,
const api::Response<SecurityParametersBatchOpResponse>&){
LOG(persist, Info, "PositionServiceServer::update_security_parameters bp count:{}",
req.op_params_size());
for (const auto& p : req.op_params()){
std::string key_str = std::to_string(p.security_key());
auto db_p = me->security_params_store->retrieve_one(security_params_ns, key_str);
auto found = db_p.first;
if (!found) {
me->security_params_store->insert(security_params_ns,
key_str,
utils::pb::to_string(p));
}
else {
me->security_params_store->insert(security_params_ns,
key_str,
utils::pb::to_string(p));
}
}
_load_security_params();
_compute_pnl_and_publish();
// TODO
// LOG(persist, Info, "PositionServiceServer::update_security_parameters bp count:{}",
// req.op_params_size());
// for (const auto& p : req.op_params()){
// std::string key_str = std::to_string(p.security_key());
// auto db_p = me->security_params_store->retrieve_one(security_params_ns, key_str);
// auto found = db_p.first;
// if (!found) {
// me->security_params_store->insert(security_params_ns,
// key_str,
// utils::pb::to_string(p));
// }
// else {
// me->security_params_store->insert(security_params_ns,
// key_str,
// utils::pb::to_string(p));
// }
// }
// _load_security_params();
// _compute_pnl_and_publish();
}
///////////////////////////////////////////////////////////////////////////////
+10
View File
@@ -0,0 +1,10 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SRC_ROOT=$DIR/../..
BUILD_ROOT=`readlink -f $SRC_ROOT/build`
BUILD_TYPE="${1:-clang_debug}"
BUILD_CMD="ninja -C $BUILD_ROOT/$BUILD_TYPE"
touch $SRC_ROOT/CMakeLists.txt
$DIR/execute_in_docker $BUILD_CMD
+6
View File
@@ -0,0 +1,6 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SRC_ROOT=$DIR/../..
BUILD_ROOT=`readlink -f $SRC_ROOT/build`
cgdb -- -ex start --cd=$BUILD_ROOT/ninja_debug/server --args ./sparkd run
+39
View File
@@ -0,0 +1,39 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SRC_ROOT=$DIR/../..
CMD=$@
read -d '' docker_cmd << EOF
docker run \
--rm \
--net host \
-h $(hostname)_spark \
-e "TZ=America/New_York" \
--security-opt seccomp=unconfined \
-v /var/log/syslog:/var/log/syslog \
-v /usr/local/share/fonts:/usr/local/share/fonts \
-v /usr/share/fonts:/usr/share/fonts \
-v /run/user/:/run/user/ \
-v /tmp:/tmp \
-v /etc/group:/etc/group \
-v /etc/passwd:/etc/passwd \
-v /tmp:/tmp \
-v /etc/sudoers:/etc/sudoers \
-v /home:/home \
--shm-size=4024m \
-w $SRC_ROOT \
-u $UID \
-t \
-i \
-e DISPLAY=$DISPLAY \
bluetradingsystems/linux_docker
EOF
if [ -f /.dockerenv ]; then
$CMD
else
echo "Running $CMD"
$docker_cmd $CMD
fi
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
$DIR/execute_in_docker /usr/local/bin/rdm $@
+5
View File
@@ -0,0 +1,5 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
CMD="$DIR/../setup_builds.sh"
$DIR/execute_in_docker "/bin/bash -c $CMD"
+7
View File
@@ -0,0 +1,7 @@
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SRC_ROOT=$DIR/../
$DIR/execute_in_docker /bin/bash
+3
View File
@@ -14,6 +14,7 @@ mkdir $BUILD_ROOT/clang_debug
cd $BUILD_ROOT/clang_debug
cmake -G Ninja -DCMAKE_BUILD_TYPE=Debug -DCMAKE_EXPORT_COMPILE_COMMANDS=1 -DCMAKE_CXX_COMPILER=/usr/lib/ccache/clang++ $SRC_ROOT
rm -rf $BUILD_ROOT/ninja_debug
mkdir $BUILD_ROOT/ninja_debug
cd $BUILD_ROOT/ninja_debug
@@ -24,3 +25,5 @@ mkdir $BUILD_ROOT/ninja_release
cd $BUILD_ROOT/ninja_release
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -DCMAKE_EXPORT_COMPILE_COMMANDS=1 -DCMAKE_CXX_COMPILER=g++ $SRC_ROOT
rm -f $SRC_ROOT/compile_commands.json
ln -s $BUILD_ROOT/clang_debug/compile_commands.json $SRC_ROOT/compile_commands.json