This commit is contained in:
Pedro Pinto committed 2018-08-24 13:56:35 -04:00
commit 03e3549895
169 files changed
+4317 -1494

No files matched your search

+68 -13
View File
@@ -1,30 +1,85 @@
using bts.api;
using bts;
using bts.api.admin;
using bts.api.core;
using bts.spark;
using mbts.spark.utilities;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Linq;
using System.Threading.Tasks;
using System.Reactive.Subjects;
namespace mbts.spark {
[Export]
class AdminModel {
readonly AdminService _service;
class AdminModel : IDisposable {
readonly string _user_name;
readonly BehaviorSubject<IReadOnlyDictionary<uint, string>>
_accounts_subject = new BehaviorSubject<IReadOnlyDictionary<uint, string>>(new Dictionary<uint, string>()),
_users_subject = new BehaviorSubject<IReadOnlyDictionary<uint, string>>(new Dictionary<uint, string>());
IReadOnlyDictionary<uint, string>
_account_map = new Dictionary<uint, string>(),
_user_map = new Dictionary<uint, string>();
IDisposable _dispose;
[ImportingConstructor]
private AdminModel(AdminService service) {
_service = service;
AdminModel(AdminService service, [Import("username")]string user_name) {
_user_name = user_name;
_dispose = service.subscribei_admin_data().Select(update => {
IEnumerable<BTSUserImmutable> active_users =
from admin_data in update.all
from bts_user in admin_data.Users
where bts_user.Name == user_name && bts_user.HasUserData && bts_user.UserData.HasAccountPermissions
select bts_user;
on_admin_data = _service.subscribei_admin_data().Table().Replay(1).RefCount();
IEnumerable<BTSAccountImmutable> active_accounts =
from admin_data in update.all
from bts_account in admin_data.Accounts
where bts_account.IsPresent
join account_id in (
from bts_user in active_users
from account_id in bts_user.UserData.AccountPermissions.AccountPermissions.Keys
select account_id
) on bts_account.Id equals account_id
select bts_account;
var users = active_users.ToDictionary(u => u.Id, u => u.Name);
var accounts = active_accounts.ToDictionary(a => a.Id, a => a.Name);
return (users, accounts);
}).Subscribe(t => {
_account_map = t.accounts;
_user_map = t.users;
_users_subject.OnNext(_user_map = t.users);
_accounts_subject.OnNext(_account_map = t.accounts);
});
}
public IObservable<TableUpdate<AdminDataImmutable, int>> on_admin_data { get; }
public IObservable<IReadOnlyDictionary<uint, string>> on_users => _users_subject.AsObservable();
public IObservable<IReadOnlyDictionary<uint, string>> on_accounts => _accounts_subject.AsObservable();
public IObservable<IReadOnlyList<UserTuple>> on_user_tuples => on_users.Select(d => d.Select(kv => new UserTuple(kv.Key, kv.Value)).ToList());
public IObservable<IReadOnlyList<AccountTuple>> on_account_tuples => on_accounts.Select(d => d.Select(kv => new AccountTuple(kv.Key, kv.Value)).ToList());
public UserTuple? get_current_user() {
foreach (var kv in _user_map) {
// just for good measure, there should never be > 1 element in _user_map, and it should always match _user_name
if (kv.Value == _user_name)
return new UserTuple(kv.Key, kv.Value);
}
return null;
}
public AccountTuple? get_default_account() {
foreach (var kv in _account_map) {
return new AccountTuple(kv.Key, kv.Value);
}
return null;
}
public uint? get_user_id(string user) => _id_for_name(user, _user_map);
public uint? get_account_id(string account) => _id_for_name(account, _account_map);
public void Dispose() => Disposable.dispose(ref _dispose);
static uint? _id_for_name(string name, IReadOnlyDictionary<uint, string> map) {
foreach (var kv in map) {
if (kv.Value == name)
return kv.Key;
}
return null;
}
}
}
@@ -29,7 +29,7 @@ namespace bts.perf {
}
void on_tick(Update<TickImmutable, int> update) {
if (update.added.Count > 0) {
if (update.added.Any()) {
var tick = update.added.Last();
_service.report_async(new Report() {
HostName = _hostname,
+12 -18
View File
@@ -1,23 +1,16 @@
using bts.api.core;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using bts.api.user;
using bts.api.persistence;
using bts.support;
using bts.api.admin;
using bts.api.core;
using bts.api.orderman;
using bts.api.persistence;
using bts.api.position;
using bts.api.synthetic;
using bts.api.diagnostic;
using bts.api.admin;
using bts.api.user;
using bts.metrics;
using bts.support;
using System.ComponentModel.Composition;
namespace Spark
{
public class ShellServices
{
namespace Spark {
public class ShellServices {
[Export]
public static ServiceContext context { get; } = new ServiceContext();
@@ -45,6 +38,7 @@ namespace Spark
[Export]
public ShellLatencyService shell_latency_service => context.locate<ShellLatencyService>();
[Export]
public PositionService position_service => context.locate<PositionService>();
}
}
}
+19 -7
View File
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
@@ -6,8 +7,9 @@ using System.Windows.Media.Imaging;
namespace mbts.ui {
public class Icons {
public const string
PaymentGeometryKey = "PaymentGeometry",
OrdersGeometryKey = "OrdersGeometry";
PaymentGeometryKey = nameof(PaymentGeometryKey),
OrdersGeometryKey = nameof(OrdersGeometryKey),
ToolsGeometryKey = nameof(ToolsGeometryKey);
static readonly string base_uri = "pack://application:,,,/Images/Icons/";
private static ResourceDictionary _resources = (ResourceDictionary)Application.LoadComponent(new Uri("/Images/Vector/Icons.xaml", UriKind.RelativeOrAbsolute));
@@ -106,6 +108,7 @@ namespace mbts.ui {
public static ImageSource Spawn { get { return (DrawingImage)_resources["Spawn"]; } }
public static ImageSource Target { get { return (DrawingImage)_resources["Target"]; } }
public static ImageSource Tetris { get { return (DrawingImage)_resources["Tetris"]; } }
public static ImageSource Tools => create_icon(ToolsGeometryKey);
public static ImageSource ViewSettings => (DrawingImage)_resources["ViewSettings"];
public static ImageSource Wrench { get { return (DrawingImage)_resources["Wrench"]; } }
public static ImageSource UpArrow { get { return (DrawingImage)_resources["UpArrow"]; } }
@@ -114,12 +117,21 @@ namespace mbts.ui {
public static ImageSource create_icon(string geometric_path_key) => create_icon(geometric_path_key, Brushes.Black);
public static ImageSource create_icon(string geometric_path_key, Brush brush, Pen pen = null) {
string path = _resources[geometric_path_key] as string;
if (string.IsNullOrEmpty(path))
throw new ArgumentException($"Resource lookup of '{geometric_path_key}' did not return a valid string.", nameof(geometric_path_key));
var geometry = Geometry.Parse(path);
object obj = _resources[geometric_path_key];
if (obj is string path) {
if (string.IsNullOrEmpty(path))
throw new ArgumentException($"Resource lookup of '{geometric_path_key}' did not return a valid string.", nameof(geometric_path_key));
return _create_icon(new[] { path }, brush, pen);
} else if (obj is string[] paths) {
return _create_icon(paths, brush, pen);
} else return null;
}
static ImageSource _create_icon(IEnumerable<string> paths, Brush brush, Pen pen = null) {
var drawing_group = new DrawingGroup();
drawing_group.Children.Add(new GeometryDrawing(brush, pen, geometry));
foreach (string p in paths) {
drawing_group.Children.Add(new GeometryDrawing(brush, pen, Geometry.Parse(p)));
}
return new DrawingImage(drawing_group);
}
}
+5 -2
View File
@@ -5,13 +5,16 @@
xmlns:mbts="clr-namespace:mbts.ui"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
>
<sys:String x:Key="{x:Static mbts:Icons.OrdersGeometryKey}">
M50.14375,33.389126C50.416863,33.394688,50.653496,33.587773,50.705998,33.864617L50.015995,45.114388C49.810295,46.291462,49.130394,45.097489,49.130394,45.097489L47.65659,42.640538C42.747776,49.635197 34.633152,54.221001 25.433924,54.221001 14.884193,54.221001 5.7437552,48.204125 1.2449617,39.419205 0.80087067,38.552021 0.21358696,37.705738 0.052086769,36.736958 -0.49735315,33.490925 3.4507786,32.901036 4.8049124,34.432404 5.3674143,35.067692 6.034036,36.16407 6.5079177,37.026051 10.106778,43.799416 17.2321,48.413819 25.433924,48.413819 32.656544,48.413819 39.026364,44.826695 42.903977,39.351506L40.229367,38.854115C40.229367,38.854115,38.677464,38.647118,39.742466,37.996033L50.024895,33.398526C50.064972,33.391365,50.104733,33.388333,50.14375,33.389126z M23.030291,9.0310004L27.889918,9.0310004 27.889918,13.028299C30.539786,13.205498,32.324932,13.958096,33.464161,14.528294L33.964176,14.775793 32.417435,20.038878 31.706417,19.68068C30.579987,19.11958 28.839241,18.244583 26.149073,18.244583 24.006916,18.244583 22.723183,19.122181 22.723183,20.590876 22.723183,21.894272 23.943314,22.804369 27.551308,24.187165 32.706444,26.124659 34.911,28.702853 34.911,32.817341 34.911,36.892929 32.090527,40.05172 27.673611,40.989117L27.673611,45.540001 22.767485,45.540001 22.767485,41.330414C20.252919,41.155815,17.695551,40.424118,16.101811,39.404721L15.683999,39.137619 17.221739,33.731438 17.969059,34.180634C19.088988,34.851235 21.402748,35.97873 24.340325,35.97873 26.734886,35.97873 28.276728,34.921635 28.276728,33.291336 28.276728,31.986641 27.547409,30.853846 23.986016,29.57255 20.083815,28.144253 16.095511,26.04406 16.095511,21.239174 16.095511,17.280985 18.737379,14.291395 23.030291,13.329098z M25.268765,0C35.819447,2.7347414E-07 44.961449,6.0155495 49.458798,14.804573 49.902695,15.669173 50.490094,16.516972 50.651287,17.48427 51.198281,20.734265 47.255726,21.318962 45.901341,19.789065 45.336346,19.153567 44.669552,18.051968 44.19566,17.19517 40.5957,10.421881 33.473275,5.8072398 25.268765,5.8072393 18.047545,5.8072398 11.678013,9.3918336 7.8003562,14.867073L10.474627,15.367072C10.474627,15.367072,12.026909,15.574172,10.962921,16.223872L0.67933281,20.826762C0.36037083,20.880062,0.057029126,20.669165,0.00099972012,20.354063L0.69093342,9.1118043C0.89552094,7.9296158,1.5738537,9.124924,1.5738539,9.124924L3.0452772,11.583379C7.9566038,4.584462,16.073666,2.7347414E-07,25.268765,0z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.PaymentGeometryKey}">
M28.000001,6.0000026L28.000001,15 6.0010006,15 6.0010006,17.000003 30.001,17.000003 30.001,6.0000026z M14.231,2.9540056L14.979999,2.9540056 14.979999,3.987005C15.704998,4.009005,16.200997,4.178005,16.550998,4.3600049L16.248998,5.0620046C15.994998,4.9340047 15.499998,4.7010047 14.725999,4.7010047 13.796,4.7010047 13.445001,5.1900046 13.445001,5.6160046 13.445001,6.1710043 13.893,6.4470041 14.943999,6.8310037 16.187998,7.2780037 16.816998,7.8320036 16.816998,8.7800031 16.816998,9.6210027 16.151998,10.409003 14.907999,10.591002L14.907999,11.698002 14.146,11.698002 14.146,10.622003C13.445001,10.611002,12.720001,10.420002,12.297002,10.154003L12.587001,9.4400029C13.022001,9.696003 13.651,9.8980026 14.328,9.8980026 15.185999,9.8980026 15.765998,9.4620028 15.765998,8.8540034 15.765998,8.2680035 15.293999,7.9060035 14.4,7.5870035 13.167001,7.1610038 12.406001,6.6710041 12.406001,5.7440041 12.406001,4.8600047 13.119,4.189005 14.231,4.0290052z M2,2.0000002L2,13 26.000001,13 26.000001,2.0000002z M0,0L28.000001,0 28.000001,4.0000031 32.001,4.0000031 32.001,19.000003 4.0010006,19.000003 4.0010006,15 0,15z
</sys:String>
<sys:String x:Key="{x:Static mbts:Icons.OrdersGeometryKey}">
M50.14375,33.389126C50.416863,33.394688,50.653496,33.587773,50.705998,33.864617L50.015995,45.114388C49.810295,46.291462,49.130394,45.097489,49.130394,45.097489L47.65659,42.640538C42.747776,49.635197 34.633152,54.221001 25.433924,54.221001 14.884193,54.221001 5.7437552,48.204125 1.2449617,39.419205 0.80087067,38.552021 0.21358696,37.705738 0.052086769,36.736958 -0.49735315,33.490925 3.4507786,32.901036 4.8049124,34.432404 5.3674143,35.067692 6.034036,36.16407 6.5079177,37.026051 10.106778,43.799416 17.2321,48.413819 25.433924,48.413819 32.656544,48.413819 39.026364,44.826695 42.903977,39.351506L40.229367,38.854115C40.229367,38.854115,38.677464,38.647118,39.742466,37.996033L50.024895,33.398526C50.064972,33.391365,50.104733,33.388333,50.14375,33.389126z M23.030291,9.0310004L27.889918,9.0310004 27.889918,13.028299C30.539786,13.205498,32.324932,13.958096,33.464161,14.528294L33.964176,14.775793 32.417435,20.038878 31.706417,19.68068C30.579987,19.11958 28.839241,18.244583 26.149073,18.244583 24.006916,18.244583 22.723183,19.122181 22.723183,20.590876 22.723183,21.894272 23.943314,22.804369 27.551308,24.187165 32.706444,26.124659 34.911,28.702853 34.911,32.817341 34.911,36.892929 32.090527,40.05172 27.673611,40.989117L27.673611,45.540001 22.767485,45.540001 22.767485,41.330414C20.252919,41.155815,17.695551,40.424118,16.101811,39.404721L15.683999,39.137619 17.221739,33.731438 17.969059,34.180634C19.088988,34.851235 21.402748,35.97873 24.340325,35.97873 26.734886,35.97873 28.276728,34.921635 28.276728,33.291336 28.276728,31.986641 27.547409,30.853846 23.986016,29.57255 20.083815,28.144253 16.095511,26.04406 16.095511,21.239174 16.095511,17.280985 18.737379,14.291395 23.030291,13.329098z M25.268765,0C35.819447,2.7347414E-07 44.961449,6.0155495 49.458798,14.804573 49.902695,15.669173 50.490094,16.516972 50.651287,17.48427 51.198281,20.734265 47.255726,21.318962 45.901341,19.789065 45.336346,19.153567 44.669552,18.051968 44.19566,17.19517 40.5957,10.421881 33.473275,5.8072398 25.268765,5.8072393 18.047545,5.8072398 11.678013,9.3918336 7.8003562,14.867073L10.474627,15.367072C10.474627,15.367072,12.026909,15.574172,10.962921,16.223872L0.67933281,20.826762C0.36037083,20.880062,0.057029126,20.669165,0.00099972012,20.354063L0.69093342,9.1118043C0.89552094,7.9296158,1.5738537,9.124924,1.5738539,9.124924L3.0452772,11.583379C7.9566038,4.584462,16.073666,2.7347414E-07,25.268765,0z
<sys:String x:Key="{x:Static mbts:Icons.ToolsGeometryKey}">
M4.9629898,25.440168C4.564003,25.440168 4.0650101,25.640182 3.7659989,25.939165 3.0680008,26.638176 3.0680008,27.635191 3.7659989,28.3342 4.4639969,29.032204 5.4620133,29.032204 6.1600113,28.3342 6.8589859,27.635191 6.8589859,26.638176 6.1600113,25.939165 5.760994,25.640182 5.3620072,25.440168 4.9629898,25.440168z M18.432014,18.457121L22.422005,22.447138 24.816994,22.946165 29.107002,29.431192 27.509987,31.027212 21.025002,26.737175 20.526985,24.343178 16.535988,20.352123z M8.1560135,18.357115L13.643013,23.84415C11.048988,26.638176 8.9539872,28.932196 7.9560013,29.930189 6.359993,31.526207 3.6659928,31.626215 2.070015,29.930189 0.47400668,28.3342 0.47400668,25.640182 2.070015,24.044165z M2.967995,6.7840408C2.768013,6.7840408 2.5690079,6.8840479 2.4690018,6.9840545 2.1699906,7.2830371 2.1699906,7.7820638 2.4690018,8.0810469L11.746986,17.359123C12.047005,17.659113 12.544991,17.659113 12.845009,17.359123 13.14399,17.06011 13.14399,16.561113 12.845009,16.2621L3.5659867,6.9840545C3.3670121,6.8840479,3.1669998,6.7840408,2.967995,6.7840408z M5.2620011,4.4890431C5.0629959,4.4890431 4.8630143,4.5890192 4.7640152,4.6890262 4.3649979,4.9880394 4.3649979,5.4870356 4.7640152,5.8860554L14.042,15.164101C14.341011,15.46409 14.840004,15.46409 15.139015,15.164101 15.439003,14.865087 15.439003,14.366092 15.139015,14.067109L5.8610001,4.6890262C5.661995,4.5890192,5.4620133,4.4890431,5.2620011,4.4890431z M4.3649979,2.3940283C5.4620133,2.3940281,6.5589981,2.7930175,7.3580094,3.5920337L19.328987,15.46409 13.342995,21.450153 1.2720107,9.6770657C-0.42400357,7.9810704 -0.42400357,5.2880291 1.2720107,3.6910337 2.1699906,2.7930175 3.267006,2.3940281 4.3649979,2.3940283z M24.217995,0C25.31501,-8.5992724E-08,26.312996,0.20001344,27.211006,0.59900296L23.021004,4.7890328C22.223,5.5870422,22.223,6.7840408,23.021004,7.4820436L24.617012,9.079069C25.414986,9.8770789,26.612007,9.8770789,27.311012,9.079069L31.501015,4.9880394C31.799995,5.8860554 32.000008,6.7840408 32.000008,7.7820638 32.000008,12.07207 28.508003,15.564097 24.217995,15.564097 19.927986,15.564097 16.436012,12.07207 16.436012,7.7820638 16.436012,3.4920272 19.927986,-8.5992724E-08 24.217995,0z
</sys:String>
<DrawingImage x:Key="Bookmarks">
@@ -256,14 +256,27 @@
<DataGridRowHeader
Background="Transparent"
Padding="{Binding section_count, Converter={StaticResource RowHeaderGroupIndentConverter}}"
Content="{Binding display_name}"
FontWeight="{Binding font_weight, FallbackValue={u:FontWeight Normal}}"
SelectiveScrollingGrid.SelectiveScrollingOrientation="Vertical"
Visibility="{Binding
HeadersVisibility,
ConverterParameter={x:Static DataGridHeadersVisibility.Row},
Converter={x:Static DataGrid.HeadersVisibilityConverter},
RelativeSource={RelativeSource AncestorType=DataGrid}}"
/>
>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding display_name}" />
<c:HelpButton
x:Name="row_helpbutton"
ToolTip="{Binding help_text}"
Opacity="0"
Visibility="{Binding help_text, Converter={StaticResource NullToVisibilityConverter}}"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Margin="3,0,0,0"
/>
</StackPanel>
</DataGridRowHeader>
<DataGridCellsPresenter Grid.Column="1" ItemsPanel="{TemplateBinding ItemsPanel}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</SelectiveScrollingGrid>
</Border>
@@ -272,6 +285,9 @@
<Setter Property="BorderBrush" Value="Red"/>
<Setter Property="BorderThickness" Value="1"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Opacity" TargetName="row_helpbutton" Value="1"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
<Style x:Key="DataGridRowStyle" TargetType="DataGridRow">
@@ -35,9 +35,10 @@ namespace mbts.ui.spark {
static ExecutionStrategyEditor() =>
DefaultStyleKeyProperty.OverrideMetadata(typeof(ExecutionStrategyEditor), new FrameworkPropertyMetadata(typeof(ExecutionStrategyEditor)));
public ExecutionStrategyEditor() =>
public ExecutionStrategyEditor() {
AdornerHelper.attach_continuously_on_loaded(() => new ExecutionStrategyErrorAdorner(this), this);
ToolTipService.ShowDurationProperty.OverrideMetadata(typeof(DependencyObject), new FrameworkPropertyMetadata(Int32.MaxValue));
}
#region SyntheticName
public static readonly DependencyProperty SyntheticNameProperty = DependencyProperty.Register("SyntheticName", typeof(string), typeof(ExecutionStrategyEditor),
new FrameworkPropertyMetadata(string.Empty, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
@@ -180,7 +181,7 @@ namespace mbts.ui.spark {
#region ContractPickerModel
public static readonly DependencyProperty ContractPickerModelProperty = DependencyProperty.Register(nameof(ContractPickerModel), typeof(mbts.spark.ContractPickerModel), typeof(ExecutionStrategyEditor));
public mbts.spark.ContractPickerModel ContractPickerModel { get => GetValue(ContractPickerModelProperty) as mbts.spark.ContractPickerModel; set => SetValue(ContractPickerModelProperty, value); }
#endregion
#endregion
public override void OnApplyTemplate() =>
_connect_leg_tuples();
@@ -54,10 +54,10 @@
x:Name="PART_Description_HelpButton"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Command="{Binding ToggleShowDescription, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}"
Margin="3,0,0,0"
Opacity="0"
Visibility="{Binding Description, Converter={StaticResource EmptyStringVisibilityConverter}, RelativeSource={RelativeSource TemplatedParent}}"
ToolTip="{Binding Description, RelativeSource={RelativeSource TemplatedParent}}"
/>
</StackPanel>
</BlockUIContainer>
@@ -6,6 +6,8 @@ namespace mbts.spark {
partial class SyntheticEditorVM {
class IsQuoteModel : RowModelBase<bool> {
public override string display_name { get; } = "Enable Quoting";
public override string help_text { get; } = "This parameter is in the form of a check box, where if the box is checked the leg will be quoted versus not checked, it will not be shown in the market. If it is not actively quoted in the market, the leg will still be used for calculation of the entire synthetic.";
public override string man_page { get; } = string.Empty;
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
leg_tup.leg_params.IsActiveQuoting;
@@ -1,15 +1,18 @@
using mbts.ui.spark;
using System;
namespace mbts.spark {
partial class SyntheticEditorVM {
class HedgeRatioModel : RowModelBase<double> {
public override string display_name { get; } = "Hedge Ratio";
public override string display_name { get; } = "Lean Qty Factor";
public override string help_text { get; } = "This is the ratio multiplier that defines how much volume you require in that leg before leaning off it. For example, if you are looking to buy 4 ES and sell 2 NQ, if your hedge ratio is 1, you will work the ES leg at where you could get filled on 2 NQ. If your Hedge Ratio is 3 on the NQ leg, then you’ll work the ES order based on where you could fill 6 (2 (Qty of NQ) * 3 (Hedge Ratio)).";
public override string man_page { get; } = string.Empty;
public override double get_value(LegSpreaderParamsTuple leg_tup) =>
leg_tup.leg_params.QuoteParams.LeanQuantityRatio;
public override void set_value(LegSpreaderParamsTuple leg_tup, double value) =>
leg_tup.leg_params.QuoteParams.LeanQuantityRatio = value;
leg_tup.leg_params.QuoteParams.LeanQuantityRatio = Math.Abs(value);
public override ICell create_cell(LegSpreaderParamsTuple leg_tup) => new HedgeRatioCell(this, leg_tup);
@@ -11,6 +11,8 @@ namespace mbts.spark {
public override bool read_only { get; }
public override string display_name { get; } = "Price Multiplier";
public override string help_text { get; } = "This is multiplier at which the synthetic will be priced, by default, it’ll be based on the same as the quantity of the synthetic produced, but you can change it to modify the balance of the price, giving more weighting to one leg over another.";
public override string man_page { get; } = string.Empty;
public override double get_value(LegSpreaderParamsTuple leg_tup) =>
leg_tup.leg.PriceMultiplier;
@@ -11,6 +11,8 @@ namespace mbts.spark {
public event Action quantity_changed;
public override bool read_only { get; }
public override string display_name { get; } = "Quantity";
public override string help_text { get; } = "This is the number of contracts of the security you would like to be included in the calculation of the synthetic as well as a buy or sell. By default, the first leg will come up as a buy and the second leg a sell. Sells are represented “-1”";
public override string man_page { get; } = string.Empty;
public override double get_value(LegSpreaderParamsTuple leg_tup) =>
leg_tup.leg.Side == Side.Buy ? leg_tup.leg.Quantity : -leg_tup.leg.Quantity;
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Cross Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.OppositeMarketVolumeBasedCross };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -13,6 +13,8 @@ namespace mbts.spark {
}
public override string display_name { get; } = string.Empty;
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.OppositeMarketVolumeBasedCross };
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, QuantityMeasure> _value_store = new Dictionary<uint, QuantityMeasure>();
public override string display_name { get; } = "Threshold";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.OppositeMarketVolumeBasedCross };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -13,6 +13,8 @@ namespace mbts.spark {
}
public override string display_name { get; } = string.Empty;
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.TicksAwayCross };
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Cross Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.TicksAwayCross };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.TicksAwayCross };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -13,6 +13,8 @@ namespace mbts.spark {
}
public override string display_name { get; } = string.Empty;
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.TimeBasedCross };
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Cross Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.TimeBasedCross };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Time(ms)";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PostHedge, Subsections.TimeBasedCross };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -4,6 +4,8 @@ namespace mbts.spark {
partial class SyntheticEditorVM {
class MaxTicksInsideMarketModel : RowModelBase<uint> {
public override string display_name { get; } = "Max Inside Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PreHedge };
public override uint get_value(LegSpreaderParamsTuple leg_tup) =>
@@ -13,6 +13,8 @@ namespace mbts.spark {
}
public override string display_name { get; } = string.Empty;
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PreHedge, Subsections.Payless };
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, QuantityMeasure> _value_store = new Dictionary<uint, QuantityMeasure>();
public override string display_name { get; } = "Threshold";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PreHedge, Subsections.Payless };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,9 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Payless Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PreHedge, Subsections.Payless };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -13,6 +13,8 @@ namespace mbts.spark {
}
public override string display_name { get; } = string.Empty;
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PreHedge, Subsections.Payup };
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, QuantityMeasure> _value_store = new Dictionary<uint, QuantityMeasure>();
public override string display_name { get; } = "Threshold";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PreHedge, Subsections.Payup };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Payup Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.PreHedge, Subsections.Payup };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -0,0 +1,39 @@
using bts.spark;
using mbts.collections.extensions;
using mbts.ui.spark;
using System.Collections.Generic;
using System.Windows;
namespace mbts.spark {
partial class SyntheticEditorVM {
class QuoteHiddenModel : RowModelBase<bool>, IHaveFontParams {
IDictionary<uint, bool> _value_store = new Dictionary<uint, bool>();
public override string display_name { get; } = "Hidden";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote };
public FontWeight font_weight => FontWeights.SemiBold;
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
leg_tup.leg_params.QuoteParams.QuoteHidden = _value_from_store(leg_tup) ? new QuoteHidden() : null;
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
_get_throttle(leg_tup) != null;
public override void set_value(LegSpreaderParamsTuple leg_tup, bool value) {
_value_store[leg_tup.SecurityKey] = value;
leg_tup.leg_params.QuoteParams.QuoteHidden = value ? new QuoteHidden() : null;
}
protected override bool _get_enabled(LegSpreaderParamsTuple leg_tup) =>
_get_throttle(leg_tup) != null;
QuoteHidden _get_throttle(LegSpreaderParamsTuple leg_tup) =>
leg_tup.leg_params.QuoteParams.QuoteHidden;
bool _value_from_store(LegSpreaderParamsTuple leg_tup) =>
_value_store.GetValueOrDefault(leg_tup.SecurityKey, _ => false);
}
}
}
@@ -13,6 +13,8 @@ namespace mbts.spark {
}
public override string display_name { get; } = string.Empty;
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.InsideMarketThrottleThresholds };
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Min Move";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.InsideMarketThrottleThresholds };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.InsideMarketThrottleThresholds };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -13,6 +13,8 @@ namespace mbts.spark {
}
public override string display_name { get; } = string.Empty;
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.Throttle };
public override bool get_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Inside Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.Throttle };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -10,6 +10,8 @@ namespace mbts.spark {
IDictionary<uint, uint> _value_store = new Dictionary<uint, uint>();
public override string display_name { get; } = "Outside Ticks";
public override string help_text { get; } = string.Empty;
public override string man_page { get; } = string.Empty;
public override ParameterSection[] section_path { get; } = new[] { Sections.Quote, Subsections.Throttle };
public void apply_value(LegSpreaderParamsTuple leg_tup) =>
@@ -4,11 +4,13 @@ using mbts.utils;
using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using System.Windows;
namespace mbts.spark {
partial class SyntheticEditorVM {
internal interface IRowModel {
string display_name { get; }
string help_text { get; }
bool read_only { get; }
ParameterSection[] section_path { get; }
bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups);
@@ -33,7 +35,11 @@ namespace mbts.spark {
Type data_type { get; }
bool enabled { get; }
}
internal interface IHaveFontParams {
FontWeight font_weight { get; }
}
abstract class RowModelBase<T> : ViewModelBase, IRowModel {
readonly Dictionary<uint, ReplaySubject<bool>> _enabled_store = new Dictionary<uint, ReplaySubject<bool>>();
readonly Dictionary<uint, Subject<T>> _override_value_store = new Dictionary<uint, Subject<T>>();
@@ -41,6 +47,8 @@ namespace mbts.spark {
protected RowModelBase() { }
public abstract string display_name { get; }
public abstract string help_text { get; }
public abstract string man_page { get; }
public virtual bool read_only { get; } = false;
public virtual ParameterSection[] section_path { get; } = new ParameterSection[0];
public virtual bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups) => false;
@@ -92,41 +100,41 @@ namespace mbts.spark {
private static class Subsections {
public static ParameterSection Throttle =>
new ParameterSection("Throttle", true,
"reduces re-quoting updates by defining a region on either side " +
"Reduces re-quoting updates by defining a region on either side " +
"of the working quoting order, inside which quote updates will not be sent.");
public static ParameterSection InsideMarketThrottleThresholds =>
new ParameterSection("Inside Market Throttle Thresholds", true,
"reduces re-quoting for quotes that are moving toward the inside market. " +
"Reduces re-quoting for quotes that are moving toward the inside market. " +
"Orders moving toward the inside market are not re-quoted if:\n\n" +
"i. New order is more than 'Ticks' away from the inside market or\n" +
"ii. New order has not moved 'Min Move' away from the current price");
public static ParameterSection Payless =>
new ParameterSection("Pay Less", true,
"when the quantity at the level of the calculated hedge price is more than " +
"When the quantity at the level of the calculated hedge price is more than " +
"'Threshold,' the hedge order is paid less by 'Payless Ticks.'");
public static ParameterSection Payup =>
new ParameterSection("Pay Up", true,
"when the quantity at the level of the calculated hedge price is less than " +
"When the quantity at the level of the calculated hedge price is less than " +
"'Threshold,' then the hedge order is paid up by 'Payup Ticks.'");
public static ParameterSection TicksAwayCross =>
new ParameterSection("Ticks Away Cross", true,
"forces legged hedging orders to automatically cross the market if they get too " +
"Forces legged hedging orders to automatically cross the market if they get too " +
"far away from the opposite inside market.If a legged hedge order's price gets 'Ticks' away " +
"from the opposite inside market, it is re-priced to cross the opposite inside market by 'Cross Ticks.'");
public static ParameterSection TimeBasedCross =>
new ParameterSection("Time Based Cross", true,
"forces legged hedge orders to automatically cross the market, if they are still " +
"Forces legged hedge orders to automatically cross the market, if they are still " +
"working beyond a certain time period.If a hedge order is legged for 'Time(ms)', " +
"it is re-priced to cross the opposite inside market by 'Cross Ticks.'");
public static ParameterSection OppositeMarketVolumeBasedCross =>
new ParameterSection("Size Based Cross", true,
"forces legged hedging orders to automatically cross the market if the volume " +
"Forces legged hedging orders to automatically cross the market if the volume " +
"of the opposite inside market drops below the threhold. If opposite inside market volume drops below 'Threshold,' " +
"it is re-priced to cross the opposite inside market by 'Cross Ticks.'");
}
@@ -7,11 +7,13 @@ using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
namespace mbts.spark {
partial class SyntheticEditorVM {
public interface IParameterRowVM {
string display_name { get; }
string help_text { get; }
bool read_only { get; }
ParameterSection[] section_path { get; }
}
@@ -22,10 +24,12 @@ namespace mbts.spark {
public RowVM(IRowModel model, ObservableCollection<LegSpreaderParamsTuple> legs) {
display_name = model.display_name;
help_text = model.help_text;
section_path = model.section_path;
for (int i = 0; i < section_count; i++)
section_path[i].level = i;
read_only = model.read_only;
font_weight = model is IHaveFontParams fps ? fps.font_weight : FontWeights.Normal;
_has_errors = backing(nameof(has_errors), false);
_cells = ObservantDictionary.Create(legs, l => l.leg.Security, model.create_cell, EqualityComparer.Create<Security, uint>(s => s.Id));
_cells.ValueDestroyed += c => (c as IDisposable)?.Dispose();
@@ -33,6 +37,8 @@ namespace mbts.spark {
}
public string display_name { get; }
public string help_text { get; }
public FontWeight font_weight { get; }
public ParameterSection[] section_path { get; }
public int section_count => section_path.Length;
public bool read_only { get; }
@@ -201,6 +201,7 @@ namespace mbts.spark {
_price_mult_model,
new IsQuoteModel(),
new HedgeRatioModel(),
new QuoteHiddenModel(),
new QuoteThrottleEnabledModel(quote_throttle_inside_ticks, quote_throttle_outside_ticks),
quote_throttle_inside_ticks,
quote_throttle_outside_ticks,
@@ -41,6 +41,7 @@ namespace bts.shell {
SparkCommands.ShowAboutSpark,
// SparkCommands.ShowReleaaseNotes,
SparkCommands.ShowActivityLog,
SparkCommands.ShowManual,
};
public Task<IShellWindow> create(Stream load_stream) {
@@ -30,8 +30,8 @@ namespace mbts.spark {
FillsVM(IBus bus, OrdersModel model, IObservable<IIncrementalUpdate<FillTuple, FillTupleKey>> fills_source, IReadOnlyCollection<SortingCriteria> sorting_criteria, FilterStates filters)
: base(RXCollection.CreateIncrementalUpdate(fills_source), sorting_criteria) {
_model = model;
account_filter = DiscreteValuesFilterVM.Create<Row, string>(_model.factory.subscribe_accounts(), r => r.account, nameof(Row.account));
user_filter = DiscreteValuesFilterVM.Create<Row, string>(_model.factory.subscribe_users(), r => r.user, nameof(Row.user));
account_filter = DiscreteValuesFilterVM.Create<Row, string>(_model.factory.subscribe_accounts().Select(d => d.Values), r => r.account, nameof(Row.account));
user_filter = DiscreteValuesFilterVM.Create<Row, string>(_model.factory.subscribe_users().Select(d => d.Values), r => r.user, nameof(Row.user));
security_filter = DiscreteValuesFilterVM.Create<Row, SecurityImmutable, SecurityCriteria>(
fills_source.with_respect_to(
ft => ft.security_md.HasValue ? ft.security_md.Value.security : SecurityDataHelper.Defaults.SecurityImmutable,
@@ -66,6 +66,7 @@ namespace mbts.spark {
TimeTextTuple.FromDateTime(DateTime.Today.AddDays(1))
)
);
fill_kind_filter.load_state(EnumHelper.get_values_except(FillKind.Sod).ToArray());
}
// columns
add_col(Columns.Security, DefaultColumnHeaders.Security, r => r.security.ToString(), nameof(Row.security), security_filter, DataGridFilterKnownTemplates.DiscreteValues, DefaultColumnWidths.Security);
@@ -152,14 +153,15 @@ namespace mbts.spark {
_fill = fill_tuple.fill;
_order = fill_tuple.order ?? OrderDataHelper.Defaults.OrderRecordImmutable;
_model = model;
account = fill_tuple.account;
}
public DateTime fill_time => _fill.Timestamp.ToDateTimeOffset().LocalDateTime;
public TimeInForce time_in_force => _order.Def.TimeInForce;
public OrderType order_type => _order.Def.CustomDef.CustomCase;
public TimeInForce time_in_force => _order.time_in_force();
public OrderType order_type => _order.order_type();
public OrderMetadata order_metadata => _model.factory.get_metadata(_order.Def.CustomDef.CustomCase);
public string account => _order.Def.Account;
public string user => _order.Def.User;
public string account { get; private set; }
public string user => _order.user();
public Venue exchange => security.Exchange;
public Side side => _fill.Side;
public double price => _fill.LastPrice;
@@ -80,6 +80,8 @@ namespace bts.shell {
s.session_low_line = LadderSettings.Default.session_low_line;
if (s.session_high_line == null)
s.session_high_line = LadderSettings.Default.session_high_line;
if (s.session_range_fill == null)
s.session_range_fill = LadderSettings.Default.session_range_fill;
s.row_height = LadderRender.measure_row_height(s);
return s;
}
@@ -84,7 +84,7 @@ namespace mbts.spark {
r => r.user.store,
DefaultColumnWidths.User,
DiscreteValuesFilterVM.Create<OrderBookRowVM, string>(
model.factory.subscribe_users(),
model.factory.subscribe_users().Select(d => d.Values),
r => r.user.value,
value_path(nameof(OrderBookRowVM.user))),
DataGridFilterKnownTemplates.DiscreteValues));
@@ -96,7 +96,7 @@ namespace mbts.spark {
r => r.account.store,
DefaultColumnWidths.Account,
DiscreteValuesFilterVM.Create<OrderBookRowVM, string, string[]>(
model.factory.subscribe_accounts(),
model.factory.subscribe_accounts().Select(d => d.Values),
r => r.account.value,
vals => vals.ToArray(),
vals => Observable.Return(vals),
@@ -69,13 +69,13 @@ namespace mbts.spark {
_dispose = Disposable.Create(
bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(on_securities),
model.on_orders.OnDispatcher().Subscribe(on_orders),
model.on_orders.OnDispatcher().AddRemoveOnly().Subscribe(on_orders),
grid_settings_manager,
columns);
void on_orders(TableUpdate<OrderRecordImmutable, uint> table) {
void on_orders(LegacyTableUpdate<OrderRecordImmutable, uint> table) {
// clear everything (most likely the server restarted)
if (table.removed.Count == _order_rows.Count && table.added.Count == 0) {
if (table.removed.Count() == _order_rows.Count && !table.added.Any()) {
_selected_rows.Clear();
_order_rows.DisposeAll();
_order_rows.Clear();
@@ -216,6 +216,7 @@ namespace mbts.spark {
public OrderBookRowVM current_row { get => _current_row.Value; set => _current_row.Value = value ?? _selected_rows.FirstOrDefault(); }
public OrderRecordImmutable? current_order => current_row?.order;
public IEnumerable<OrderRecordImmutable> selected_orders => _selected_rows.Select(r => r.order);
public GridSettingsManager<OrderBookRowVM, OrderRecordTuple, INotificationServiceDataCache, OrderRecordTuplePredicate> grid_settings_manager { get; }
public ICommand expand_collapse_all_rows_command { get; }
@@ -40,11 +40,10 @@ namespace bts.shell {
/// </summary>
public PAndLStartupData() { }
public PAndLStartupData(List<SortingCriteria> sorting_criteria, FilterStates filters, pnl_calc_type calc_type, TimeSpan start_of_day_time) {
public PAndLStartupData(List<SortingCriteria> sorting_criteria, FilterStates filters, pnl_calc_type calc_type) {
this.sort_criteria = sorting_criteria;
this.filters = filters;
this.calc_type = calc_type;
this.start_of_day_time = start_of_day_time;
}
[ProtoMember(5)]
@@ -53,9 +52,9 @@ namespace bts.shell {
public FilterStates filters;
[ProtoMember(15)]
public pnl_calc_type calc_type;
[ProtoMember(20)]
public TimeSpan? start_of_day_time;
//[ProtoMember(20)]
// ProtoMember 20 cannot be used further
}
[ProtoContract]
@@ -8,8 +8,11 @@ namespace bts.shell {
// The INotificationService updates these caches in its IObservable.OnNext callbacks, just before calling all of the predicate-trigger methods.
// Therfore, data referenced through this interface is guarenteed to be up-to-date, and thread safe. It also reduces performance overhead by avoiding redundant bookeeping.
// Note: last_order_reset_time can be used by sound/toast-notification sources to avoid sending false-positive notifications for old orders (i.e. all the orders that arrive in the first update on startup/server restart)
// --------------------------------------------------------------------------------------------------------------------------------------------
// IMPOARTANT!!! The current implementation of this interface is NOT INTENDED FOR GENERAL USE - order_history is NOT THREAD-SAFE
interface INotificationServiceDataCache {
DateTime last_order_reset_time { get; }
bool is_first_order_update { get; }
IReadOnlyDictionary<uint, List<TimeStampedData<OrderRecordTuple>>> order_history { get; }
}
@@ -31,31 +34,37 @@ namespace bts.shell {
partial class NotificationService : INotificationService, IDisposable {
class DataCache : INotificationServiceDataCache {
const int _buffer_size = 10;
Dictionary<uint, List<TimeStampedData<OrderRecordTuple>>> _order_cache = new Dictionary<uint, List<TimeStampedData<OrderRecordTuple>>>();
public IReadOnlyDictionary<uint, List<TimeStampedData<OrderRecordTuple>>> order_history => _order_cache;
readonly Dictionary<uint, OrderRecordTuple> _order_cache = new Dictionary<uint, OrderRecordTuple>();
readonly Dictionary<uint, List<TimeStampedData<OrderRecordTuple>>> _order_history = new Dictionary<uint, List<TimeStampedData<OrderRecordTuple>>>();
public IReadOnlyDictionary<uint, List<TimeStampedData<OrderRecordTuple>>> order_history => _order_history;
public DateTime last_order_reset_time { get; private set; }
public bool is_first_order_update { get; private set; }
public void update(IIncrementalUpdate<OrderRecordTuple, uint> data) {
DateTime now = DateTime.Now;
if (data.removed.Count == _order_cache.Count) {
last_order_reset_time = now;
_order_cache.Clear();
}
is_first_order_update = _order_cache.Count == 0 && data.added.Count > 0;
foreach (var kv in data.removed) {
if (data.added.ContainsKey(kv.Key)) {
_order_cache[kv.Key].Add(new TimeStampedData<OrderRecordTuple>(kv.Value, now));
_order_cache[kv.Key] = kv.Value;
_order_history[kv.Key].Add(new TimeStampedData<OrderRecordTuple>(kv.Value, now));
} else {
_order_cache.Remove(kv.Key);
// TODO: maybe these shouldn't be removed?
// if we add delta/time predicates that need to refer to order history, we might need to keep them around
// although, if the server is telling us to remove them, perhaps we shouldn't consider such data.
_order_cache.Remove(kv.Key);
_order_history.Remove(kv.Key);
}
}
foreach (var kv in data.added) {
if (data.removed.ContainsKey(kv.Key))
continue;
_order_cache.AddOrUpdate(kv.Key,
_order_cache.Add(kv.Key, kv.Value);
_order_history.AddOrUpdate(kv.Key,
k => new List<TimeStampedData<OrderRecordTuple>> { new TimeStampedData<OrderRecordTuple>(kv.Value, now) },
(k, l) => {
l.Add(new TimeStampedData<OrderRecordTuple>(kv.Value, now));
@@ -68,7 +68,7 @@ namespace bts.shell {
public static IToastNotification order_completed(OrderRecordTuple order) =>
new OrderCompletedToastNotification(order.order, order.security_md?.security);
public static IToastNotification order_status_changed(uint key, OrderStatus old_status, OrderStatus new_status, SecurityImmutable? security) =>
public static IToastNotification order_status_changed(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) =>
new OrderStatusChangeToastNotification(key, old_status, new_status, security);
abstract class ToastNotificationBase : IToastNotification {
@@ -109,10 +109,11 @@ namespace bts.shell {
class OrderStatusChangeToastNotification : ToastNotificationBase, IEquatable<OrderStatusChangeToastNotification> {
uint _key;
readonly OrderStatus _new_status, _old_status;
readonly OrderStatus _new_status;
readonly OrderStatus? _old_status;
readonly SecurityImmutable? _security;
public OrderStatusChangeToastNotification(uint key, OrderStatus old_status, OrderStatus new_status, SecurityImmutable? security) {
public OrderStatusChangeToastNotification(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) {
_key = key;
_old_status = old_status;
_new_status = new_status;
@@ -126,14 +127,14 @@ namespace bts.shell {
public bool Equals(OrderStatusChangeToastNotification other) =>
other != null &&
_key == other._key &&
_old_status == other._old_status &&
EqualityComparer.nullable_equals(_old_status, other._old_status) &&
_new_status == other._new_status &&
_security.HasValue == other._security.HasValue;
public override bool Equals(object obj) => Equals(obj as OrderStatusChangeToastNotification);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash((int)_key, (int)_old_status, (int)_new_status, _security.HasValue.GetHashCode());
EqualityComparer.aggregate_hash((int)_key, _old_status.HasValue ? (int)_old_status.Value : -1, (int)_new_status, _security.HasValue.GetHashCode());
}
// Note: this class does not check whether or not order.status is actually "completed,"
@@ -1,4 +1,5 @@
using bts.api;
using bts;
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.shell;
@@ -13,7 +14,7 @@ namespace mbts.spark {
readonly Property<SecurityImmutable> _security;
readonly Property<double> _price, _current_price;
readonly Property<uint> _current_size;
readonly Property<string> _current_account;
readonly Property<AccountTuple> _current_account;
readonly Property<TimeInForce> _current_time_in_force;
readonly Property<CustomOrderDefinition.CustomOneofCase> _current_order_type;
readonly Property<bool> _price_dirty, _size_dirty, _account_dirty, _time_in_force_dirty, _order_type_dirty;
@@ -28,7 +29,7 @@ namespace mbts.spark {
size_calculator = new CalculatorLogic(null, calculator_buttons);
_current_price = backing(nameof(current_price), order_source.Select(ort => ort.order.State.Price));
_current_size = backing(nameof(current_size), order_source.Select(ort => ort.order.State.Quantity));
_current_account = backing(nameof(current_account), order_source.Select(ort => ort.order.Def.Account));
_current_account = backing(nameof(current_account), order_source.Select(ort => new AccountTuple(ort.order.Def.AccountId, ort.order.Def.Account)));
_current_time_in_force = backing(nameof(current_time_in_force), order_source.Select(ort => ort.order.Def.TimeInForce));
_current_order_type = backing(nameof(current_order_type), order_source.Select(ort => ort.order.Def.CustomDef.CustomCase));
//
@@ -103,7 +104,7 @@ namespace mbts.spark {
public CalculatorLogic size_calculator { get; }
public double current_price => _current_price.Value;
public uint current_size => _current_size.Value;
public string current_account => _current_account.Value;
public AccountTuple current_account => _current_account.Value;
public TimeInForce current_time_in_force => _current_time_in_force.Value;
public CustomOrderDefinition.CustomOneofCase current_order_type => _current_order_type.Value;
public bool price_dirty => _price_dirty.Value;
+13
View File
@@ -3,6 +3,8 @@ using bts.api.orderman;
using mbts.utils;
using System;
using static bts.api.orderman.Fill.Types;
namespace mbts.spark {
class FillTuple : IEquatable<FillTuple> {
public readonly FillImmutable fill;
@@ -17,6 +19,17 @@ namespace mbts.spark {
key = new FillTupleKey(fill.FillKey, order.HasValue ? order.Value.Key : 0u, security_md.HasValue ? security_md.Value.security.Id : 0u);
}
// the TrimEnd is very important b/c the server currently does not trim,
// but the account is part of the group, so this is necessary
public string account {
get {
var trimmed_account_string = string.Empty;
if (fill.FillKind != FillKind.Sod && order.HasValue && order.Value.HasDef) trimmed_account_string = order.Value.Def.Account;
else trimmed_account_string = fill.Account;
return trimmed_account_string == null ? string.Empty : trimmed_account_string.Trim();
}
}
public bool Equals(FillTuple other) => other != null
&& other.order.HasValue == order.HasValue
&& other.security_md.HasValue == security_md.HasValue
+12 -25
View File
@@ -41,9 +41,8 @@ namespace mbts.spark {
IReadOnlyDictionary<string, FillImmutable> _fills_cache = new Dictionary<string, FillImmutable>(0);
IReadOnlyDictionary<uint, OrderRecordImmutable> _orders_cache = new Dictionary<uint, OrderRecordImmutable>(0);
IReadOnlyDictionary<uint, SecurityMD> _security_md_cache = new Dictionary<uint, SecurityMD>(0);
// _n_write_ops should never be greater than 1, bc all 3 input observables fire 'OnDispatcher'
int _n_read_ops, _n_write_ops;
IDisposable _dispose;
object _lock = new object();
FillTupleSource(
IObservable<IReadOnlyDictionary<uint, SecurityMD>> securities,
@@ -51,12 +50,12 @@ namespace mbts.spark {
IObservable<TableUpdate<FillImmutable, string>> fills) =>
//
_dispose = Disposable.Create(
securities.OnDispatcher().Subscribe(_update_securities),
orders.OnDispatcher().Subscribe(_update_orders),
fills.OnDispatcher().Subscribe(_update_fills));
securities.Subscribe(_update_securities),
orders.Subscribe(_update_orders),
fills.AddRemoveOnly().Subscribe(_update_fills));
public IDisposable Subscribe(IObserver<IIncrementalUpdate<FillTuple, FillTupleKey>> observer) {
using (_read()) {
lock (_lock) {
observer.OnNext(new IncrementalUpdate<FillTuple, FillTupleKey>(new Dictionary<FillTupleKey, FillTuple>(_state), new Dictionary<FillTupleKey, FillTuple>(0)));
return _subject.Subscribe(observer);
}
@@ -64,9 +63,11 @@ namespace mbts.spark {
public void Dispose() => Disposable.dispose(ref _dispose);
void _update_fills(TableUpdate<FillImmutable, string> fills) {
using (_write()) {
Dictionary<FillTupleKey, FillTuple> removed = new Dictionary<FillTupleKey, FillTuple>(), added = new Dictionary<FillTupleKey, FillTuple>();
void _update_fills(LegacyTableUpdate<FillImmutable, string> fills) {
lock (_lock) {
var removed = new Dictionary<FillTupleKey, FillTuple>();
var added = new Dictionary<FillTupleKey, FillTuple>();
foreach (FillImmutable fill in fills.removed) {
FillTuple old_ft = new FillTuple(fill, _get_order(fill.OrderKey), _get_security_md(fill.SecurityKey));
removed.Add(old_ft.key, old_ft);
@@ -85,7 +86,7 @@ namespace mbts.spark {
}
void _update_orders(TableUpdate<OrderRecordImmutable, uint> orders) {
using (_write()) {
lock (_lock) {
Dictionary<FillTupleKey, FillTuple> added = new Dictionary<FillTupleKey, FillTuple>(), removed = new Dictionary<FillTupleKey, FillTuple>();
HashSet<uint> changed_keys = new HashSet<uint>();
foreach (var o in orders.removed) {
@@ -123,7 +124,7 @@ namespace mbts.spark {
}
void _update_securities(IReadOnlyDictionary<uint, SecurityMD> securities) {
using (_write()) {
lock (_lock) {
Dictionary<FillTupleKey, FillTuple> added = new Dictionary<FillTupleKey, FillTuple>(), removed = new Dictionary<FillTupleKey, FillTuple>();
_security_md_cache.Keys.difference(securities.Keys, out IEnumerable<uint> added_keys, out IEnumerable<uint> removed_keys);
foreach (var k in removed_keys) {
@@ -170,19 +171,5 @@ namespace mbts.spark {
_state.Add(kv.Key, kv.Value);
_subject.OnNext(new IncrementalUpdate<FillTuple, FillTupleKey>(added, removed));
}
IDisposable _read() {
while (_n_write_ops > 0)
Thread.Yield();
Interlocked.Increment(ref _n_read_ops);
return Disposable.Create(() => Interlocked.Decrement(ref _n_read_ops));
}
IDisposable _write() {
while (_n_read_ops > 0)
Thread.Yield();
Interlocked.Increment(ref _n_write_ops);
return Disposable.Create(() => Interlocked.Decrement(ref _n_write_ops));
}
}
}
@@ -68,6 +68,14 @@ namespace bts.spark {
public static string format_status_change(uint key, OrderStatus old_status, OrderStatus new_status, SecurityImmutable? security) =>
_format_status_change(_header(key, security), key, old_status, new_status);
// since changes are naggled, transition changes aren't always detected (e.g. a new order changes before observers are notified of its existence), so old_status might be null.
public static string format_status_change(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) {
string header = _header(key, security);
return old_status.HasValue?
_format_status_change(header, key, old_status.Value, new_status) :
_format_status_change(header, key, new_status);
}
public static string order_completion_debrief(OrderRecordImmutable order, SecurityImmutable? security) =>
_format_order_completion(_header(order.Key, security), order, security?.ContractSpec);
@@ -104,6 +112,9 @@ namespace bts.spark {
return $"{header} {after.Def.Side.past_tense()} {(fa - fb)} ({fa} total), still working {after.working_quantity()}";
}
static string _format_status_change(string header, uint key, OrderStatus new_status) =>
$"{header} Status changed to {new_status}";
static string _format_status_change(string header, uint key, OrderStatus old_status, OrderStatus new_status) =>
$"{header} Status changed from {old_status} to {new_status}";
@@ -114,14 +125,7 @@ namespace bts.spark {
void orders_updated(TableUpdate<OrderRecordImmutable, uint> update) {
// Go though added and changed orders
var added = new HashSet<OrderRecordImmutable>(update.added, _id_comparer);
var changed = new HashSet<OrderRecordImmutable>(update.added, _id_comparer);
var removed = update.removed.ToDictionary(o => o.Key);
added.ExceptWith(update.removed);
changed.ExceptWith(added);
foreach (var order in added) {
foreach (var order in update.added) {
if (!string.IsNullOrEmpty(order.State.LastMsg) && order.State.Created.ToDateTime().Date == DateTime.Today) {
(var security, var spec) = get_security(order.Def.SecurityKey);
if (security.HasValue) {
@@ -130,8 +134,7 @@ namespace bts.spark {
}
}
foreach (var neworder in changed) {
var oldorder = removed[neworder.Key];
foreach (var (neworder, oldorder) in update.changes) {
(var security, var spec) = get_security(neworder.Def.SecurityKey);
//
// description
@@ -24,12 +24,11 @@ namespace mbts.ui.spark {
public DataTemplate LeanOrderTemplate { get; set; }
public DataTemplate JoinOrderTemplate { get; set; }
public DataTemplate TopOrderTemplate { get; set; }
public DataTemplate CoverOrderTemplate { get; set; }
public DataTemplate TriggerOrderTemplate { get; set; }
public DataTemplate IcebergOrderTemplate { get; set; }
public DataTemplate SpreaderTemplate { get; set; }
public DataTemplate BTSStopOrderTemplate { get; set; }
public DataTemplate BTSIcebergOrderTemplate { get; set; }
public DataTemplate ReflectionTemplate { get; set; }
public DataTemplate DynamicOrderTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container) {
var vm = item as IOrderTypeVM;
@@ -42,9 +41,11 @@ namespace mbts.ui.spark {
case CustomOrderDefinition.CustomOneofCase.Lean: return LeanOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Join: return JoinOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Top: return TopOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Cover: return CoverOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Trigger: return TriggerOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Iceberg: return IcebergOrderTemplate;
case CustomOrderDefinition.CustomOneofCase.Spreader: return SpreaderTemplate;
case CustomOrderDefinition.CustomOneofCase.Dynamic: return DynamicOrderTemplate;
}
}
return null;
@@ -1,4 +1,5 @@
using bts.api;
using bts;
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.shell;
@@ -11,25 +12,25 @@ using System.Reactive.Linq;
namespace mbts.spark {
class InlineOrderProperties {
public readonly InlineUserProperty<string> account;
public readonly InlineUserProperty<AccountTuple> account;
public readonly InlineUserProperty<TimeInForce> time_in_force;
public readonly InlineUserProperty<CustomOrderDefinition> order_type_def;
public InlineOrderProperties(OrdersModel model, LadderSettings settings) : this(
new InlineUserProperty<string>(model.factory.default_account, false),
new InlineUserProperty<AccountTuple>(),
new InlineUserProperty<TimeInForce>(settings.default_time_in_force, true),
new InlineUserProperty<CustomOrderDefinition>(model.factory.custom_order(settings.default_order_type), true)) { }
public InlineOrderProperties(OrdersModel model, OrderDefinitionImmutable def) : this(
new InlineUserProperty<string>(def.Account, true),
new InlineUserProperty<AccountTuple>(),
new InlineUserProperty<TimeInForce>(def.TimeInForce, true),
new InlineUserProperty<CustomOrderDefinition>(def.CustomDef.CloneToMutable(), true)) { }
public InlineOrderProperties(
InlineUserProperty<string> account=null,
InlineUserProperty<AccountTuple> account=null,
InlineUserProperty<TimeInForce> time_in_force=null,
InlineUserProperty<CustomOrderDefinition> order_type_def=null) {
this.account = account ?? new InlineUserProperty<string>();
this.account = account ?? new InlineUserProperty<AccountTuple>();
this.time_in_force = time_in_force ?? new InlineUserProperty<TimeInForce>();
this.order_type_def = order_type_def ?? new InlineUserProperty<CustomOrderDefinition>();
}
@@ -38,7 +39,7 @@ namespace mbts.spark {
class OrderPropertiesEditorVM : DisposableViewModelBase {
readonly OrdersModel _model;
readonly Property<SecurityImmutable> _security;
readonly SelectorProperty<string> _accounts;
readonly SelectorProperty<AccountTuple> _accounts;
readonly SelectorProperty<TimeInForce> _time_in_force;
readonly SelectorProperty<IOrderTypeVM> _order_type;
IDisposable _order_type_param_errors_sub;
@@ -55,16 +56,10 @@ namespace mbts.spark {
security_source = _security.observe_current(true).Replay(1).RefCount();
_accounts = backing(
nameof(selected_account),
model.factory.subscribe_accounts(),
model.factory.subscribe_account_tuples(),
order_properties.Select(ops => ops.account),
() => string.Empty,
val => (!String.IsNullOrWhiteSpace(val) && accounts.Contains(val), "Please select an account"));
_time_in_force = backing(
nameof(selected_time_in_force),
security_source.Select(s => model.factory.default_time_in_forces(s)),
order_properties.Select(ops => ops.time_in_force),
() => model.factory.default_time_in_force(security),
tif => time_in_forces.Contains(tif));
() => accounts?.FirstOrDefault() ?? default,
val => (!string.IsNullOrWhiteSpace(val.name) && accounts.Contains(val), "Please select an account"));
_order_type = backing(
nameof(selected_order_type),
security_source.Select(s => model.factory.default_order_type_defs(s).Select(create_order_type_vm)),
@@ -72,10 +67,22 @@ namespace mbts.spark {
get_default_order_type_vm,
(a, b) => a.order_type == b.order_type);
_order_type.Changed += on_selected_order_type_changed;
_time_in_force = backing(
nameof(selected_time_in_force),
// remember, both observables must fire once to start the CombineLatest sequence
security_source.CombineLatest(_order_type.observe_current(true)).Select(
t => model.factory.default_time_in_forces(t.Item1, t.Item2?.order_type ?? CustomOrderDefinition.CustomOneofCase.None)),
order_properties.Select(ops => ops.time_in_force),
() => model.factory.default_time_in_force(security),
tif => time_in_forces.Contains(tif));
_dispose = Disposable.Create(() => _order_type.Changed -= on_selected_order_type_changed);
// local methods
IOrderTypeVM create_order_type_vm(CustomOrderDefinitionImmutable cd) {
var vm = OrderTypeVMFactory.create(cd.CustomCase, model, security_md_source);
IOrderTypeVM vm = null;
if(cd.CustomCase == CustomOrderDefinition.CustomOneofCase.Dynamic)
vm = OrderTypeVMFactory.create(cd.CustomCase, model, security_md_source, cd.Dynamic.DynamicOrderType);
else
vm = OrderTypeVMFactory.create(cd.CustomCase, model, security_md_source);
vm.load_from(cd);
return vm;
}
@@ -106,14 +113,14 @@ namespace mbts.spark {
}
public SecurityImmutable security => _security.Value;
public ReadOnlyObservableCollection<string> accounts => _accounts.items;
public string selected_account { get => _accounts.selected_item; set => _accounts.selected_item = value; }
public ReadOnlyObservableCollection<AccountTuple> accounts => _accounts.items;
public AccountTuple selected_account { get => _accounts.selected_item; set => _accounts.selected_item = value; }
public ReadOnlyObservableCollection<TimeInForce> time_in_forces => _time_in_force.items;
public TimeInForce selected_time_in_force { get => _time_in_force.selected_item; set => _time_in_force.selected_item = value; }
public ReadOnlyObservableCollection<IOrderTypeVM> order_types => _order_type.items;
public IOrderTypeVM selected_order_type { get => _order_type.selected_item; set => _order_type.selected_item = value; }
public IObservable<string> observe_account(bool start_immediately = false) =>
public IObservable<AccountTuple> observe_account(bool start_immediately = false) =>
_accounts.observe_current(start_immediately);
public IObservable<TimeInForce> observe_time_in_force(bool start_immediately = false) =>
@@ -123,10 +130,9 @@ namespace mbts.spark {
_order_type.observe_current(start_immediately);
public OrderDefinition create(Side side) {
if (HasErrors) throw new InvalidOperationException("Cannot create order when errors are present.");
var order = _model.factory.order(security);
order.Account = selected_account;
order.AccountId = _model.factory.get_account_id(selected_account);
if (HasErrors)
throw new InvalidOperationException("Cannot create order when errors are present.");
var order = _model.factory.order(security, selected_account);
order.TimeInForce = selected_time_in_force;
order.Side = side;
selected_order_type.assign_to(order.CustomDef);
@@ -33,22 +33,21 @@ namespace mbts.spark {
string fmt_assert_msg(string msg) => $"{nameof(OrderRecordTupleSource)}.{nameof(create_observable)}: {msg}";
}
// _n_write_ops should never be greater than 1, bc all 3 input observables fire 'OnDispatcher'
readonly ThreadYieldRWGate _rw_gate = new ThreadYieldRWGate();
readonly Subject<IIncrementalUpdate<OrderRecordTuple, uint>> _subject = new Subject<IIncrementalUpdate<OrderRecordTuple, uint>>();
readonly Dictionary<uint, OrderRecordTuple> _state = new Dictionary<uint, OrderRecordTuple>();
readonly SetMap<uint, uint> _security_orders = new SetMap<uint, uint>();
IReadOnlyDictionary<uint, OrderRecordImmutable> _orders_cache = new Dictionary<uint, OrderRecordImmutable>(0);
IReadOnlyDictionary<uint, SecurityMD> _security_md_cache = new Dictionary<uint, SecurityMD>(0);
IDisposable _dispose;
object _lock = new object();
OrderRecordTupleSource(IObservable<IReadOnlyDictionary<uint, SecurityMD>> securities, IObservable<TableUpdate<OrderRecordImmutable, uint>> orders) =>
_dispose = Disposable.Create(
securities.OnDispatcher().Subscribe(_update_securities),
orders.OnDispatcher().Subscribe(_update_orders));
securities.Subscribe(_update_securities),
orders.AddRemoveOnly().Subscribe(_update_orders));
public IDisposable Subscribe(IObserver<IIncrementalUpdate<OrderRecordTuple, uint>> observer) {
using (_rw_gate.read()) {
lock (_lock) {
observer.OnNext(new IncrementalUpdate<OrderRecordTuple, uint>(new Dictionary<uint, OrderRecordTuple>(_state), new Dictionary<uint, OrderRecordTuple>(0)));
return _subject.Subscribe(observer);
}
@@ -56,8 +55,8 @@ namespace mbts.spark {
public void Dispose() => Disposable.dispose(ref _dispose);
void _update_orders(TableUpdate<OrderRecordImmutable, uint> orders) {
using (_rw_gate.write()) {
void _update_orders(LegacyTableUpdate<OrderRecordImmutable, uint> orders) {
lock (_lock) {
Dictionary<uint, OrderRecordTuple> removed = new Dictionary<uint, OrderRecordTuple>(), added = new Dictionary<uint, OrderRecordTuple>();
foreach (OrderRecordImmutable order in orders.removed) {
uint sec_key = order.security_key();
@@ -77,7 +76,7 @@ namespace mbts.spark {
}
void _update_securities(IReadOnlyDictionary<uint, SecurityMD> securities) {
using (_rw_gate.write()) {
lock (_lock) {
Dictionary<uint, OrderRecordTuple> added = new Dictionary<uint, OrderRecordTuple>(), removed = new Dictionary<uint, OrderRecordTuple>();
_security_md_cache.Keys.difference(securities.Keys, out IEnumerable<uint> added_keys, out IEnumerable<uint> removed_keys);
foreach (var k in removed_keys) {
@@ -123,49 +122,4 @@ namespace mbts.spark {
_subject.OnNext(new IncrementalUpdate<OrderRecordTuple, uint>(added, removed));
}
}
/// <summary>
/// Provides mechanisms to ensure that only one write op may execute at a time, and calls to read or write while a write op is underway will Thread.yield until the write-op is completed.
/// If no write-op is underway, read-ops may run concurrently.
/// </summary>
class ThreadYieldRWGate {
int _n_write_ops, _n_read_ops;
public IDisposable read() {
while (_n_write_ops > 0)
Thread.Yield();
Interlocked.Increment(ref _n_read_ops);
if (_n_write_ops > 0) {
// A write-op was yielding at the same time and beat us to the punch! Try again
Interlocked.Decrement(ref _n_read_ops);
return read();
}
return Disposable.Create(() => Interlocked.Decrement(ref _n_read_ops));
}
public IDisposable write() {
while (_n_read_ops > 0 || _n_write_ops > 0)
Thread.Yield();
if (Interlocked.Increment(ref _n_write_ops) > 1 || _n_read_ops > 0) {
// Another write/read-op was yielding at the same time and beat us to the punch! Try again
Interlocked.Decrement(ref _n_write_ops);
return write();
}
return Disposable.Create(() => Interlocked.Decrement(ref _n_write_ops));
}
}
class ThreadYieldGate {
int _n_ops;
public IDisposable enter() {
while (_n_ops > 0)
Thread.Yield();
if (Interlocked.Increment(ref _n_ops) > 1) {
Interlocked.Decrement(ref _n_ops);
return enter();
}
return Disposable.Create(() => Interlocked.Decrement(ref _n_ops));
}
}
}
@@ -0,0 +1,246 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlineCoverOrderProperties
{
public InlineCoverOrderProperties(CustomOneofCase selected_child_order_type, IReadOnlyCollection<CustomOneofCase> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<CustomOneofCase>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<CustomOneofCase>>(child_order_types, true);
var hedgetype = CustomOneofCase.Limit;
this.selected_hedge_order_type = new InlineUserProperty<CustomOneofCase>(hedgetype, true);
this.hedge_order_types = new InlineUserProperty<IReadOnlyCollection<CustomOneofCase>>(child_order_types, true);
hedge_ticks = new InlineUserProperty<int>(1, false);
}
public readonly InlineUserProperty<CustomOneofCase> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<CustomOneofCase>> child_order_types;
public readonly InlineUserProperty<CustomOneofCase> selected_hedge_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<CustomOneofCase>> hedge_order_types;
public readonly InlineUserProperty<int> hedge_ticks;
}
class CoverOrderVM : OrderTypeVMBase<CoverOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
InlineCoverOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _hedge_order_choices;
IOrderTypeVM _hedge_order;
IDisposable _hedge_order_errors_sub;
public int hedge_ticks { get; set; } = 1;
public CoverOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineCoverOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList())))
{ }
public CoverOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineCoverOrderProperties> inline_properties) : base(model)
{
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p =>
{
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value);
}
if (_hedge_order_choices != null && (_hedge_order == null || p.selected_hedge_order_type.force_override))
{
_select_hedge_order(p.selected_hedge_order_type.value);
}
if (p.hedge_ticks.force_override)
{
hedge_ticks = p.hedge_ticks.value;
RaisePropertyChanged(nameof(hedge_ticks));
}
_inline_props = p;
_validate();
})
);
_validate();
}
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
if (_hedge_order == null )
_select_hedge_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.cover_order();
i.HedgeTicks = hedge_ticks;
child_order.assign_to(i.Child);
if (hedge_order != null)
hedge_order.assign_to(i.Hedge);
value.Cover = i;
}
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _child_order_choices;
}
}
public ICollection<IOrderTypeVM> hedge_order_types
{
get
{
if (_hedge_order_choices == null)
_hedge_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _hedge_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public IOrderTypeVM hedge_order
{
get
{
init();
return _hedge_order;
}
set
{
Disposable.dispose(ref _hedge_order_errors_sub);
_hedge_order = value;
_hedge_order?.init();
if (_hedge_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_hedge_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(hedge_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
if (_hedge_order_choices != null)
_hedge_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
if (_hedge_order == null && _security.HasValue)
_select_hedge_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _select_hedge_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_hedge_order_type.has_value ?
_inline_props.selected_hedge_order_type.value :
model.factory.default_order_type(_security.Value, true);
_select_hedge_order(ot);
}
void _select_hedge_order(CustomOneofCase ot)
{
_hedge_order = hedge_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_hedge_order == null)
_hedge_order = hedge_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(hedge_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
if ((_hedge_order == null ) || (_hedge_order is INotifyDataErrorInfo hdei && hdei.HasErrors))
set_error(nameof(hedge_order), string.Empty, true);
else clear_error(nameof(hedge_order));
}
}
}
}
@@ -0,0 +1,211 @@
using bts.api;
using bts.api.orderman;
using mbts.ui;
using mbts.ui.utility;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
namespace mbts.spark
{
public static class DynamicOrderHelper
{
static Lazy<bts.config.dynamic_orders.DynamicOrderList> _list = new Lazy<bts.config.dynamic_orders.DynamicOrderList>(
() => mbts.config.Configuration.get<bts.config.dynamic_orders.DynamicOrderList>(), true);
public static void add_dynamic_order_defs(List<CustomOrderDefinitionImmutable> defs,
Func<CustomOrderDefinition.CustomOneofCase, CustomOrderDefinition> factory)
{
var dyntypes = _list.Value;
foreach (var d in dyntypes.dynamic_orders)
{
var dorder = factory(CustomOrderDefinition.CustomOneofCase.Dynamic);
dorder.Dynamic.DynamicOrderType = d.type_name;
foreach (var p in d.parameter_keys)
dorder.Dynamic.Parameters.Add(p, string.Empty);
defs.Add(new CustomOrderDefinitionImmutable(dorder));
}
}
internal static List<NameValueVM> get_parameters(string dyntype)
{
List<NameValueVM> par = new List<NameValueVM>();
var order = _list.Value.dynamic_orders.FirstOrDefault(x => x.type_name == dyntype);
if (order != null)
par.AddRange(order.parameter_keys.Select(x => new NameValueVM() { name = x, value = string.Empty }));
return par;
}
}
class NameValueVM : mbts.ui.shell.ViewModelBase
{
public NameValueVM() { }
public string name { get; set; }
public string value { get; set; }
}
static partial class OrderTypeVMFactory
{
class InlineDynamicOrderProperties
{
public InlineDynamicOrderProperties(CustomOneofCase selected_child_order_type, IReadOnlyCollection<CustomOneofCase> child_order_types)
{
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<CustomOneofCase>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<CustomOneofCase>>(child_order_types, true);
}
public readonly InlineUserProperty<CustomOneofCase> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<CustomOneofCase>> child_order_types;
}
class DynamicOrderVM : OrderTypeVMBase<DynamicOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
InlineDynamicOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
string _dyn_type;
List<NameValueVM> _parameters;
public DynamicOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string dyn_type)
: this(model, security_md_source, dyn_type, security_md_source.Select(smd =>
new InlineDynamicOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList())))
{ }
public DynamicOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, string dyn_type,
IObservable<InlineDynamicOrderProperties> inline_properties) : base(model)
{
_security_md_source = security_md_source;
_dyn_type = dyn_type;
_parameters = DynamicOrderHelper.get_parameters(dyn_type);
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
inline_properties.OnDispatcher()
.Subscribe(p =>
{
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
_select_child_order(p.selected_child_order_type.value);
}
_inline_props = p;
_validate();
})
);
_validate();
}
public override string type_name => _dyn_type;
public IEnumerable<NameValueVM> parameters => _parameters;
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.dynamic_order();
i.DynamicOrderType = _dyn_type;
set_parameter_dictionary(i.Parameters);
child_order.assign_to(i.Child);
value.Dynamic = i;
}
}
void set_parameter_dictionary(Google.Protobuf.Collections.MapField<string, string> par)
{
foreach(var vm in _parameters)
par[vm.name] = vm.value ?? string.Empty;
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _child_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
init();
return _child_order;
}
set
{
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
_child_order_errors_sub = Disposable.Create(() => ndei.ErrorsChanged -= on_errors_changed);
}
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
public void Dispose()
{
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init()
{
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order()
{
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate()
{
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
}
}
}
}
@@ -19,11 +19,14 @@ namespace mbts.spark {
public static IOrderTypeVM lean(OrdersModel model, IObservable<SecurityMD> security_md_source) => new LeanOrderVM(model, security_md_source);
public static IOrderTypeVM join(OrdersModel model, IObservable<SecurityMD> security_md_source) => new JoinOrderVM(model, security_md_source);
public static IOrderTypeVM top(OrdersModel model, IObservable<SecurityMD> security_md_source) => new TopOrderVM(model, security_md_source);
public static IOrderTypeVM cover(OrdersModel model, IObservable<SecurityMD> security_md_source) => new CoverOrderVM(model, security_md_source);
public static IOrderTypeVM trigger(OrdersModel model, IObservable<SecurityMD> security_md_source) => new TriggerOrderVM(model, security_md_source);
public static IOrderTypeVM iceberg(OrdersModel model, IObservable<SecurityMD> security_md_source) => new IcebergOrderVM(model, security_md_source);
public static IOrderTypeVM spreader(OrdersModel model, IObservable<SecurityImmutable> security_source) => new SpreaderOrderVM(model, security_source);
public static IOrderTypeVM dynamic(OrdersModel model, IObservable<SecurityMD> security_md_source, string type) => new DynamicOrderVM(model, security_md_source, type);
public static IOrderTypeVM create(CustomOneofCase order_type, OrdersModel model, IObservable<SecurityMD> security_md_source) {
public static IOrderTypeVM create(CustomOneofCase order_type, OrdersModel model,
IObservable<SecurityMD> security_md_source, string dynamic_type = null ) {
switch (order_type) {
case CustomOneofCase.Market: return market(model);
case CustomOneofCase.Limit: return limit(model);
@@ -34,9 +37,11 @@ namespace mbts.spark {
case CustomOneofCase.Lean: return lean(model, security_md_source);
case CustomOneofCase.Join: return join(model, security_md_source);
case CustomOneofCase.Top: return top(model, security_md_source);
case CustomOneofCase.Cover: return cover(model, security_md_source);
case CustomOneofCase.Trigger: return trigger(model, security_md_source);
case CustomOneofCase.Iceberg: return iceberg(model, security_md_source);
case CustomOneofCase.Spreader: return spreader(model, security_md_source.Select(smd => smd.security));
case CustomOneofCase.Dynamic: return dynamic(model, security_md_source, dynamic_type);
default: throw new NotImplementedException();
}
}
@@ -11,138 +11,144 @@ using System.Linq;
using System.Reactive.Linq;
using static bts.api.orderman.CustomOrderDefinition;
namespace mbts.spark
{
static partial class OrderTypeVMFactory
{
class InlineTriggerOrderProperties
{
public InlineTriggerOrderProperties (CustomOneofCase selected_child_order_type, IReadOnlyCollection<CustomOneofCase> child_order_types)
{
namespace mbts.spark {
static partial class OrderTypeVMFactory {
class InlineTriggerOrderProperties {
public readonly InlineUserProperty<CustomOneofCase> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<CustomOneofCase>> child_order_types;
public readonly InlineUserProperty<TriggerPriceType> trigger_price_type;
public readonly InlineUserProperty<TriggerPayupPrice.Types.TriggerPayupPriceType> payup_price_type;
public readonly InlineUserProperty<double> fixed_price;
public readonly InlineUserProperty<int> payup_ticks;
public readonly InlineUserProperty<bool> use_fixed_price, is_priceout_checked, is_timeout_checked;
public readonly InlineUserProperty<int> timeout_secs;
public InlineTriggerOrderProperties(CustomOneofCase selected_child_order_type, IReadOnlyCollection<CustomOneofCase> child_order_types) {
ExceptionAssert.InvalidOperation.That(child_order_types.Contains(selected_child_order_type), $"Child order type {selected_child_order_type} is not in child_order_types");
this.selected_child_order_type = new InlineUserProperty<CustomOneofCase>(selected_child_order_type, true);
this.child_order_types = new InlineUserProperty<IReadOnlyCollection<CustomOneofCase>>(child_order_types, true);
trigger_price_type = new InlineUserProperty<TriggerPriceType>(TriggerPriceType.Bid, false);
order_price = new InlineUserProperty<double>(double.NaN, true);
payup_price_type = new InlineUserProperty<TriggerPayupPrice.Types.TriggerPayupPriceType>();
use_fixed_price = new InlineUserProperty<bool>(false);
fixed_price = new InlineUserProperty<double>();
payup_ticks = new InlineUserProperty<int>();
is_priceout_checked = new InlineUserProperty<bool>();
is_timeout_checked = new InlineUserProperty<bool>();
timeout_secs = new InlineUserProperty<int>(10);
}
public readonly InlineUserProperty<CustomOneofCase> selected_child_order_type;
public readonly InlineUserProperty<IReadOnlyCollection<CustomOneofCase>> child_order_types;
public readonly InlineUserProperty<TriggerPriceType> trigger_price_type;
public readonly InlineUserProperty<double> order_price;
}
class TriggerOrderVM : OrderTypeVMBase<TriggerOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable
{
class TriggerOrderVM : OrderTypeVMBase<TriggerOrderDefinition>, IHierarchicalOrderTypeVM, IDisposable {
readonly IObservable<SecurityMD> _security_md_source;
SecurityImmutable? _security;
readonly UserProperty<TriggerPayupPrice.Types.TriggerPayupPriceType> _payup_price_type;
readonly UserProperty<TriggerPriceType> _trigger_price_type;
readonly UserProperty<double> _fixed_price;
readonly UserProperty<int> _payup_ticks, _timeout_secs;
readonly UserProperty<bool> _use_fixed_price, _is_timeout_checked, _is_priceout_checked;
SecurityMD? _security_md;
SecurityImmutable? _security => _security_md.HasValue ? _security_md.Value.security : null;
ObservableCollection<CustomOneofCase> _order_types = new ObservableCollection<CustomOneofCase>();
ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase> _child_order_choices;
InlineTriggerOrderProperties _inline_props;
IOrderTypeVM _child_order;
IDisposable _dispose, _child_order_errors_sub;
public TriggerPriceType trigger_price_type { get; set; } = TriggerPriceType.Bid;
public double order_price { get; set; } = double.NaN;
ulong _bbo_ref = 0, _last_trade_ref = 0;
double _best_bid = double.NaN, _best_ask = double.NaN, _last_trade_price = double.NaN;
public TriggerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source)
: this(model, security_md_source, security_md_source.Select(smd =>
new InlineTriggerOrderProperties(model.factory.default_order_type(smd.security), model.factory.default_order_types(smd.security).ToList()))) { }
public TriggerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source,
IObservable<InlineTriggerOrderProperties> inline_properties) : base(model)
{
public TriggerOrderVM(OrdersModel model, IObservable<SecurityMD> security_md_source, IObservable<InlineTriggerOrderProperties> inline_properties) : base(model) {
_trigger_price_type = create_user_prop(nameof(trigger_price_type), TriggerPriceType.Bid);
_use_fixed_price = create_user_prop(nameof(use_fixed_price), true);
_fixed_price = create_user_prop(nameof(fixed_price), double.NaN);
_payup_price_type = create_user_prop(nameof(payup_price_type), TriggerPayupPrice.Types.TriggerPayupPriceType.Trigger);
_payup_ticks = create_user_prop(nameof(payup_ticks), 0);
_is_priceout_checked = create_user_prop(nameof(is_priceout_checked), false);
_is_timeout_checked = create_user_prop(nameof(is_timeout_checked), false);
_timeout_secs = create_user_prop(nameof(timeout_secs), 0);
_security_md_source = security_md_source;
_dispose = Disposable.Create(
security_md_source.OnDispatcher()
.Subscribe(smd => _security = smd.security),
.Subscribe(smd => {
_security_md = smd;
_refresh_md();
if (double.IsNaN(fixed_price) || !_fixed_price.setter_called) {
switch (trigger_price_type) {
case TriggerPriceType.Bid: _fixed_price.bypass_setter(_best_bid); break;
case TriggerPriceType.Ask: _fixed_price.bypass_setter(_best_ask); break;
case TriggerPriceType.LastTradePrice: _fixed_price.bypass_setter(_last_trade_price); break;
}
}
}),
inline_properties.OnDispatcher()
.Subscribe(p => {
if (_order_types.Count == 0 || p.child_order_types.force_override)
{
if (_order_types.Count == 0 || p.child_order_types.force_override) {
_order_types.SetItems(p.child_order_types.value);
}
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override))
{
if (_child_order_choices != null && (_child_order == null || p.selected_child_order_type.force_override)) {
_select_child_order(p.selected_child_order_type.value);
}
if (p.trigger_price_type.force_override)
{
trigger_price_type = p.trigger_price_type.value;
RaisePropertyChanged(nameof(trigger_price_type));
}
if (p.order_price.force_override)
{
order_price = p.order_price.value;
RaisePropertyChanged(nameof(order_price));
}
// trigger price
_trigger_price_type.on_inline_prop(p.trigger_price_type);
// fixed price
_use_fixed_price.on_inline_prop(p.use_fixed_price);
_fixed_price.on_inline_prop(p.fixed_price);
// payup
_payup_price_type.on_inline_prop(p.payup_price_type);
_payup_ticks.on_inline_prop(p.payup_ticks);
// exit
_is_priceout_checked.on_inline_prop(p.is_priceout_checked);
_is_timeout_checked.on_inline_prop(p.is_timeout_checked);
_timeout_secs.on_inline_prop(p.timeout_secs);
_inline_props = p;
_validate();
})
);
_validate();
}
public IEnumerable<TriggerPriceType> trigger_price_types => EnumHelper.get_values_except<TriggerPriceType>(TriggerPriceType.LastTradePrice);
public override void assign_to(CustomOrderDefinition value)
{
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors)
{
var i = factory.trigger_order();
i.TriggerCondition = new TriggerCondition()
{
PriceType = trigger_price_type,
AbsolutePriceTrigger = new AbsolutePriceTrigger() { TriggerQuantity = new TriggerQuantity() }
};
i.TriggerAction = new TriggerAction()
{
Price = order_price,
SecurityId = _security.Value.Id
};
child_order.assign_to(i.Child);
value.Trigger = i;
//
UserProperty<T> create_user_prop<T>(string name, T default_value = default) {
var rv = user_backing(name, default_value);
rv.Changed += validation_callback;
return rv;
}
}
public double price_tick
{
get { return _security.Value.ContractSpec.LowTick; }
}
public ContractSpecificationImmutable spec
{
get { return _security.Value.ContractSpec; }
void validation_callback<T>(T oldval, T newval) => _validate();
}
public ICollection<IOrderTypeVM> child_order_types
{
get
{
if (_child_order_choices == null)
// trigger price
public IEnumerable<TriggerPriceType> trigger_price_types => EnumHelper.get_values_except(TriggerPriceType.LastTradePrice);
public TriggerPriceType trigger_price_type { get => _trigger_price_type.Value; set => _trigger_price_type.Value = value; }
// fixed price
public bool use_fixed_price { get => _use_fixed_price.Value; set => _use_fixed_price.Value = value; }
public double fixed_price { get => _fixed_price.Value; set => _fixed_price.Value = value; }
// payup
public IEnumerable<TriggerPayupPrice.Types.TriggerPayupPriceType> payup_price_types => new[] { TriggerPayupPrice.Types.TriggerPayupPriceType.Trigger };
public TriggerPayupPrice.Types.TriggerPayupPriceType payup_price_type { get => _payup_price_type.Value; set => _payup_price_type.Value = value; }
public int payup_ticks { get => _payup_ticks.Value; set => _payup_ticks.Value = value; }
// exit
public bool is_priceout_checked { get => _is_priceout_checked.Value; set => _is_priceout_checked.Value = value; }
public bool is_timeout_checked { get => _is_timeout_checked.Value; set => _is_timeout_checked.Value = value; }
public int timeout_secs { get => _timeout_secs.Value; set => _timeout_secs.Value = value; }
//
public ContractSpecificationImmutable spec => _security.spec_or_default();
public ICollection<IOrderTypeVM> child_order_types {
get {
if (_child_order_choices == null)
_child_order_choices = new ObservableAutoWrapper<IOrderTypeVM, CustomOneofCase>(_order_types, ot => create(ot, model, _security_md_source));
return _child_order_choices;
}
}
public IOrderTypeVM child_order
{
get
{
public IOrderTypeVM child_order {
get {
init();
return _child_order;
}
set
{
set {
Disposable.dispose(ref _child_order_errors_sub);
_child_order = value;
_child_order?.init();
if (_child_order is INotifyDataErrorInfo ndei)
{
if (_child_order is INotifyDataErrorInfo ndei) {
ndei.ErrorsChanged += on_errors_changed;
void on_errors_changed(object s, DataErrorsChangedEventArgs e) =>
_validate();
@@ -151,40 +157,80 @@ namespace mbts.spark
_validate();
RaisePropertyChanged(nameof(child_order));
}
}
}
public void Dispose()
{
public override void assign_to(CustomOrderDefinition value) {
if (_child_order == null)
_select_child_order(model.factory.default_order_type(_security.Value, true));
_validate();
if (!HasErrors) {
var i = factory.trigger_order();
i.TriggerAction = new TriggerAction {
SecurityId = _security.Value.Id,
};
i.TriggerCondition = new TriggerCondition() {
PriceType = trigger_price_type,
AbsolutePriceTrigger = new AbsolutePriceTrigger() { TriggerQuantity = new TriggerQuantity() },
};
i.ExitCondition = new TriggerExitCondition {
ConditionalCancel = is_priceout_checked,
TimeoutEnabled = is_timeout_checked,
TimeoutSeconds = (uint)(timeout_secs)
};
if (use_fixed_price) {
// should already be null, setting it here for clarity
i.TriggerAction.Payup = null;
i.TriggerAction.Price = fixed_price;
} else {
i.TriggerAction.Price = double.NaN;
i.TriggerAction.Payup = new TriggerPayupPrice {
PayupTicks = payup_ticks,
PayupPriceType = payup_price_type
};
}
child_order.assign_to(i.Child);
value.Trigger = i;
}
}
public void Dispose() {
Disposable.dispose(ref _dispose);
if (_child_order_choices != null)
_child_order_choices.OfType<IDisposable>().DisposeAll();
}
public override void init()
{
public override void init() {
if (_child_order == null && _security.HasValue)
_select_child_order();
_validate();
}
void _select_child_order()
{
void _refresh_md() {
if (_security.HasValue) {
_security_md.Value.md.get_bbo(ref _bbo_ref, out co2.NativePriceSize bid, out co2.NativePriceSize ask);
_best_bid = bid.price;
_best_ask = ask.price;
_security_md.Value.md.get_last_trade(ref _last_trade_ref, out co2.NativePriceSize ps, out DateTime ts, out ulong v);
}
}
void _select_child_order() {
CustomOneofCase ot = _inline_props != null && _inline_props.selected_child_order_type.has_value ?
_inline_props.selected_child_order_type.value :
model.factory.default_order_type(_security.Value, true);
_select_child_order(ot);
}
void _select_child_order(CustomOneofCase ot)
{
void _select_child_order(CustomOneofCase ot) {
_child_order = child_order_types.FirstOrDefault(vm => vm.order_type == ot);
if (_child_order == null)
_child_order = child_order_types.FirstOrDefault();
RaisePropertyChanged(nameof(child_order));
}
void _validate()
{
void _validate() {
assert(!use_fixed_price || !double.IsNaN(fixed_price), nameof(fixed_price));
assert(!is_timeout_checked || timeout_secs > 0, nameof(timeout_secs));
if (_child_order == null || (_child_order is INotifyDataErrorInfo ndei && ndei.HasErrors))
set_error(nameof(child_order), string.Empty, true);
else clear_error(nameof(child_order));
+46 -12
View File
@@ -1,15 +1,18 @@
using bts.api;
using bts.api.core;
using bts.api.orderman;
using bts.api.position;
using bts.spark;
using mbts.collections;
using mbts.spark.utilities;
using mbts.utils;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Specialized;
using System.ComponentModel.Composition;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Threading.Tasks;
@@ -19,30 +22,40 @@ namespace mbts.spark {
readonly IBus _bus;
readonly OrderFactory _factory;
readonly OrderService _service;
readonly PositionService _position_service;
readonly SpreaderModel _spreader;
readonly ErrorReporter _error;
readonly OrderActivitySummarizer _activity;
readonly TableUpdateDemuxer<OrderRecordImmutable, uint, uint> _security_orders_demuxer;
readonly TableUpdateDemuxer<PositionUnitImmutable, int, uint> _security_positions_demuxer;
IDisposable _dispose;
[ImportingConstructor]
private OrdersModel(IBus bus, OrderFactory factory, OrderService service, SpreaderModel spreader, ErrorReporter error) {
private OrdersModel(IBus bus, OrderFactory factory, OrderService service, PositionService position_service, SpreaderModel spreader, ErrorReporter error) {
_bus = bus;
_factory = factory;
_service = service;
_position_service = position_service;
_spreader = spreader;
_error = error;
on_orders = _service.subscribei_orders().Table().Cache();
IReadOnlyDictionary<uint, OrderRecordImmutable> empty_orders = new Dictionary<uint, OrderRecordImmutable>();
var scheduler = ThreadPoolScheduler.Instance;
var interval = TimeSpan.FromMilliseconds(100);
on_orders = _service.subscribei_orders().Naggle(interval, scheduler).Table().Cache();
on_positions = _position_service.subscribei_position_data().Table().Cache();
working_orders =
on_orders.Scan(empty_orders, (worders, table) => _update_working_orders(worders, table)).Replay(1).RefCount();
on_orders.Scan(
ImmutableDictionary<uint,OrderRecordImmutable>.Empty,
(workers, table) => _update_working_orders(workers, table))
.Replay(1).RefCount();
on_order_tuples = OrderRecordTupleSource.create_observable(bus.subscribe(SparkTags.SecuritiesTag), on_orders);
on_fills = _service.subscribei_fills().Table().Cache();
on_fills = _service.subscribei_fills().Naggle(interval, scheduler).Table().Cache();
_activity = new OrderActivitySummarizer(bus, on_orders);
on_fill_tuples = FillTupleSource.create_observable(bus.subscribe(SparkTags.SecuritiesTag), on_orders, on_fills);
_security_orders_demuxer = new TableUpdateDemuxer<OrderRecordImmutable, uint, uint>(o => o.Key, o => o.security_key());
_security_positions_demuxer = new TableUpdateDemuxer<PositionUnitImmutable, int, uint>(o => o.RecordId, p => p.SecurityId);
_dispose = Disposable.Create(
on_orders.Subscribe(_security_orders_demuxer),
on_orders.AddRemoveOnly().Subscribe(_security_orders_demuxer),
on_positions.AddRemoveOnly().Subscribe(_security_positions_demuxer),
_bus.subscribe(SparkTags.CreateOrder).Subscribe(a => send_order(a.definition, a.price, a.size).ignore()),
_bus.subscribe(SparkTags.RecreateOrder).Subscribe(a => a.ForEach(x => send_order(x.definition, x.price, x.size).ignore())),
_bus.subscribe(SparkTags.CancelOrders).Subscribe(x => cancel_orders(x).ignore()),
@@ -59,9 +72,13 @@ namespace mbts.spark {
public IObservable<TableUpdate<FillImmutable, string>> on_fills { get; }
public IObservable<IIncrementalUpdate<FillTuple, FillTupleKey>> on_fill_tuples { get; }
public IObservable<IReadOnlyDictionary<uint,OrderRecordImmutable>> working_orders { get; }
public IObservable<TableUpdate<PositionUnitImmutable, int>> on_positions { get; }
public IObservable<ITableUpdateTransform<OrderRecordImmutable, uint>> on_security_orders(uint security) =>
_security_orders_demuxer.subscribe(security);
public IObservable<ITableUpdateTransform<PositionUnitImmutable, int>> on_security_positions(uint security) =>
_security_positions_demuxer.subscribe(security);
#endregion
#region Input
@@ -122,17 +139,27 @@ namespace mbts.spark {
public void Dispose() =>
Disposable.dispose(ref _dispose);
static IReadOnlyDictionary<uint, OrderRecordImmutable> _update_working_orders(IReadOnlyDictionary<uint, OrderRecordImmutable> target, TableUpdate<OrderRecordImmutable, uint> table) {
var clone = new Dictionary<uint, OrderRecordImmutable>((IDictionary<uint, OrderRecordImmutable>)target);
static ImmutableDictionary<uint, OrderRecordImmutable> _update_working_orders(ImmutableDictionary<uint, OrderRecordImmutable> target, TableUpdate<OrderRecordImmutable, uint> table) {
var clone = target.ToBuilder();
foreach (var o in table.removed) {
if (o.is_active())
if (o.is_active()) {
clone.Remove(o.Key);
}
}
foreach (var o in table.changed) {
if (o.is_active()) {
clone[o.Key] = o;
}
else {
clone.Remove(o.Key);
}
}
foreach (var o in table.added) {
if (o.is_active())
if (o.is_active()) {
clone.Add(o.Key, o);
}
}
return clone;
return clone.ToImmutableDictionary();
}
}
@@ -176,6 +203,13 @@ namespace mbts.spark {
.Select(t => t.state.Any(kv => kv.Value.is_active()))
.StartWith(false);
public static IObservable<double> security_total_position(this OrdersModel orders_model, uint security_key, string account) =>
// PositionUnit.Account is actually the clearing account; this code assumes that clearing account and account are equivalent.
// However, it still must match account to PositionUnit.Account.Trimmed() because the exchange likes to slap spaces on the end.
orders_model.on_security_positions(security_key).filter(p => p.Account == account).Scan(0.0, (pos, table) =>
// the state should always have 1 element, since the PositionUnit-identity is security + account
pos + (table.added.Sum(p => p.total_pos()) - table.removed.Sum(p => p.total_pos())));
public static IObservable<ITableUpdateTransform<OrderRecordImmutable, uint>> on_security_root_orders(this OrdersModel orders_model, uint security_key) =>
orders_model.on_security_orders(security_key).Scan(new RootOrderData(), (rod, table) => {
// ** using HashSet/List pairs, rather than a Dictionary, because TableUpdateTransform calls for IReadOnlyLists, while Dictionary.Values only implements IReadOnlyCollection.
@@ -235,7 +269,7 @@ namespace mbts.spark {
}
// ** [continue comment at top of method] this call would otherwise be:
// rod.last_update = rod.last_update.update(removed_dict.Values.ToList(), added_dict.Values.ToList(), o => o.Key) **
rod.last_update = rod.last_update.update(removed_roots, added_roots, o => o.Key);
//rod.last_update = rod.last_update.update(removed_roots, added_roots, o => o.Key);
return rod;
}).Select(r => r.last_update);
@@ -3,6 +3,7 @@ using bts.api.orderman;
using bts.shell;
using mbts.spark;
using mbts.ui.settings;
using mbts.utils;
using ProtoBuf;
using System;
using System.Collections.Generic;
@@ -24,7 +25,7 @@ namespace mbts {
}
[ProtoContract]
class OrderCanceledEventPredicate : IPredicateBuilder<OrderRecordTuple>, IEquatable<OrderCanceledEventPredicate> {
class OrderCanceledEventPredicate : IPredicateBuilder<OrderRecordTuple, INotificationServiceDataCache>, IEquatable<OrderCanceledEventPredicate> {
public enum PredicateTypeOneofCase {
[Description("(any order)")]
AnyOrder,
@@ -44,56 +45,46 @@ namespace mbts {
}
public IPredicate<OrderRecordTuple> create(object obj) =>
create((INotificationServiceDataCache)obj);
create_predicate((INotificationServiceDataCache)obj);
public IPredicate<OrderRecordTuple> create(INotificationServiceDataCache data_cache) {
IPredicate<OrderRecordTuple> predicate = new MyPredicate(data_cache);
if (security != null) {
predicate = predicate.and<OrderRecordTuple>(security.create(data_cache).wrap<OrderRecordTuple, SecurityImmutable>(o => (o.security_md?.security) ?? SecurityDataHelper.Defaults.SecurityImmutable));
}
return predicate;
}
public IPredicate<OrderRecordTuple> create_predicate(INotificationServiceDataCache data_cache) =>
OrderEventPredicateHelper.create_status_transition_predicate(OrderStatus.Canceled, security, data_cache);
public INotificationPredicate<OrderRecordTuple> create_toast(INotificationServiceDataCache data_cache) =>
new MyToaster(create(data_cache), data_cache);
new MyToaster(security?.create(data_cache), data_cache);
public bool Equals(OrderCanceledEventPredicate other) => other != null && other.security.safe_equals(other.security);
public override bool Equals(object obj) => Equals(obj as OrderCanceledEventPredicate);
public override int GetHashCode() => security == null ? 0 : security.GetHashCode();
class MyPredicate : IPredicate<OrderRecordTuple> {
readonly INotificationServiceDataCache _data_cache;
public MyPredicate(INotificationServiceDataCache data_cache) =>
_data_cache = data_cache;
public bool trigger(OrderRecordTuple order) =>
_data_cache.order_history.TryGetValue(order.order.Key, out List<TimeStampedData<OrderRecordTuple>> l) && l.Count > 1 &&
l[l.Count - 2].data.order.status() != OrderStatus.Canceled && order.order.status() == OrderStatus.Canceled;
public bool trigger(object obj) => trigger(obj as OrderRecordTuple);
}
static bool _is_canceled(OrderRecordImmutable o) =>
o.HasState && o.State.Status == OrderStatus.Canceled;
class MyToaster : INotificationPredicate<OrderRecordTuple>, IEquatable<MyToaster> {
readonly IPredicate<OrderRecordTuple> _predicate;
readonly IPredicate<SecurityImmutable> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
public MyToaster(IPredicate<OrderRecordTuple> predicate, INotificationServiceDataCache data_cache) {
_predicate = predicate;
public MyToaster(IPredicate<SecurityImmutable> security_predicate, INotificationServiceDataCache data_cache) {
_security_predicate = security_predicate;
_data_cache = data_cache;
}
public IToastNotification trigger(OrderRecordTuple order) =>
_predicate.trigger(order) && _data_cache.get_previous_order_state(order.order.Key) is OrderRecordTuple oldval ?
ToastNotifications.order_status_changed(order.order.Key, oldval.order.status(), order.order.status(), order.security_md?.security) : ToastNotifications.empty;
OrderEventPredicateHelper.check_order_transition_trigger(order, _is_canceled, _security_predicate, _data_cache, out OrderRecordTuple oldval) ?
ToastNotifications.order_status_changed(order.order.Key, OrderEventPredicateHelper.get_nullable_status(oldval), OrderStatus.Canceled, order.security_md.HasValue ? order.security_md.Value.security : new SecurityImmutable?()) :
ToastNotifications.empty;
bool IPredicate<OrderRecordTuple>.trigger(OrderRecordTuple order) => _predicate.trigger(order);
bool IPredicate<OrderRecordTuple>.trigger(OrderRecordTuple order) =>
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_canceled, _security_predicate, _data_cache);
public bool Equals(MyToaster other) =>
other != null && _predicate.Equals(other._predicate);
other != null && EqualityComparer.null_check_equals(_security_predicate, other._security_predicate);
public override bool Equals(object obj) => Equals(obj as MyToaster);
public override int GetHashCode() => _predicate.GetHashCode();
public override bool Equals(object obj) =>
Equals(obj as MyToaster);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash((int)OrderStatus.Canceled, _security_predicate == null ? 0 : _security_predicate.GetHashCode());
}
}
}
@@ -3,6 +3,7 @@ using bts.api.orderman;
using bts.shell;
using mbts.spark;
using mbts.ui.settings;
using mbts.utils;
using ProtoBuf;
using System;
using System.Collections.Generic;
@@ -46,54 +47,43 @@ namespace mbts {
public IPredicate<OrderRecordTuple> create(object obj) =>
create_predicate((INotificationServiceDataCache)obj);
public IPredicate<OrderRecordTuple> create_predicate(INotificationServiceDataCache data_cache) {
IPredicate<OrderRecordTuple> predicate = new MyPredicate(data_cache);
if (security != null) {
predicate = predicate.and<OrderRecordTuple>(security.create(data_cache).wrap<OrderRecordTuple, SecurityImmutable>(o => (o.security_md?.security) ?? SecurityDataHelper.Defaults.SecurityImmutable));
}
return predicate;
}
public IPredicate<OrderRecordTuple> create_predicate(INotificationServiceDataCache data_cache) =>
OrderEventPredicateHelper.create_status_transition_predicate(OrderStatus.Completed, security, data_cache);
public INotificationPredicate<OrderRecordTuple> create_toast(INotificationServiceDataCache data_cache) =>
new MyToaster(create_predicate(data_cache), data_cache);
new MyToaster(security?.create(data_cache), data_cache);
public bool Equals(OrderCompletedEventPredicate other) => other != null && other.security.safe_equals(other.security);
public override bool Equals(object obj) => Equals(obj as OrderCompletedEventPredicate);
public override int GetHashCode() => security == null ? 0 : security.GetHashCode();
class MyPredicate : IPredicate<OrderRecordTuple> {
readonly INotificationServiceDataCache _data_cache;
public MyPredicate(INotificationServiceDataCache data_cache) =>
_data_cache = data_cache;
public bool trigger(OrderRecordTuple order) =>
_data_cache.get_previous_order_state(order.order.Key) is OrderRecordTuple oldval &&
oldval.order.status() != OrderStatus.Completed && order.order.status() == OrderStatus.Completed;
public bool trigger(object obj) => trigger(obj as OrderRecordTuple);
}
static bool _is_completed(OrderRecordImmutable o) =>
o.HasState && o.State.Status == OrderStatus.Completed;
class MyToaster : INotificationPredicate<OrderRecordTuple>, IEquatable<MyToaster> {
readonly IPredicate<OrderRecordTuple> _predicate;
readonly IPredicate<SecurityImmutable> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
public MyToaster(IPredicate<OrderRecordTuple> predicate, INotificationServiceDataCache data_cache) {
_predicate = predicate;
public MyToaster(IPredicate<SecurityImmutable> security_predicate, INotificationServiceDataCache data_cache) {
_security_predicate = security_predicate;
_data_cache = data_cache;
}
public IToastNotification trigger(OrderRecordTuple order) =>
_predicate.trigger(order) && _data_cache.get_previous_order_state(order.order.Key) is OrderRecordTuple oldval ?
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_completed, _security_predicate, _data_cache) ?
ToastNotifications.order_completed(order) : ToastNotifications.empty;
bool IPredicate<OrderRecordTuple>.trigger(OrderRecordTuple order) => _predicate.trigger(order);
bool IPredicate<OrderRecordTuple>.trigger(OrderRecordTuple order) =>
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_completed, _security_predicate, _data_cache);
public bool Equals(MyToaster other) =>
other != null && _predicate.Equals(other._predicate);
other != null && EqualityComparer.null_check_equals(_security_predicate, other._security_predicate);
public override bool Equals(object obj) => Equals(obj as MyToaster);
public override int GetHashCode() => _predicate.GetHashCode();
public override bool Equals(object obj) =>
Equals(obj as MyToaster);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash((int)OrderStatus.Completed, _security_predicate == null ? 0 : _security_predicate.GetHashCode());
}
}
}
@@ -0,0 +1,67 @@
using bts.api;
using bts.api.orderman;
using bts.shell;
using mbts.spark;
using mbts.utils;
using System;
namespace mbts {
static class OrderEventPredicateHelper {
/// <summary>
/// Checks if the order has transitioned from 'not passing the predicate, or not existing' to 'passing the predicate.'
/// </summary>
public static bool check_order_transition_predicate(OrderRecordTuple order, Func<OrderRecordImmutable, bool> order_predicate_core, IPredicate<SecurityImmutable> security_predicate, INotificationServiceDataCache data_cache) =>
check_order_transition_trigger(order, order_predicate_core, security_predicate, data_cache, out OrderRecordTuple _);
/// <summary>
/// Checks if the order has transitioned from 'not passing the predicate, or not existing' to 'passing the predicate.' Oldval will be null if the order did not previously exist, or does not currently pass the predicate.
/// </summary>
public static bool check_order_transition_trigger(OrderRecordTuple order, Func<OrderRecordImmutable, bool> order_predicate_core, IPredicate<SecurityImmutable> security_predicate, INotificationServiceDataCache data_cache, out OrderRecordTuple oldval) {
if (check_security_predicate(order, security_predicate) && order_predicate_core(order.order)) {
oldval = data_cache.get_previous_order_state(order.order.Key);
return oldval == null ? !data_cache.is_first_order_update : order_predicate_core(oldval.order);
}
oldval = null;
return false;
}
/// <summary>
/// Checks if the 'security predicate is null,' or 'it is not null, and the order has a non-null security which passes.'
/// </summary>
public static bool check_security_predicate(OrderRecordTuple order, IPredicate<SecurityImmutable> security_predicate) =>
security_predicate == null || (order.security_md.HasValue && security_predicate.trigger(order.security_md.Value.security));
public static OrderStatus? get_nullable_status(OrderRecordTuple order) {
if (order == null && order.order.HasState)
return order.order.State.Status;
return null;
}
public static IPredicate<OrderRecordTuple> create_status_transition_predicate(OrderStatus status, SecurityPredicate security_predicate, INotificationServiceDataCache data_cache) =>
new OrderStatusTransitionPredicate(status, security_predicate?.create(data_cache), data_cache);
class OrderStatusTransitionPredicate : IPredicate<OrderRecordTuple>, IEquatable<OrderStatusTransitionPredicate> {
readonly IPredicate<SecurityImmutable> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
readonly OrderStatus _status;
public OrderStatusTransitionPredicate(OrderStatus status, IPredicate<SecurityImmutable> security_predicate, INotificationServiceDataCache data_cache) {
_status = status;
_security_predicate = security_predicate;
_data_cache = data_cache;
}
public bool trigger(OrderRecordTuple value) =>
check_order_transition_predicate(value, o => o.HasState && o.State.Status == _status, _security_predicate, _data_cache);
public bool Equals(OrderStatusTransitionPredicate other) =>
other != null && _status == other._status && EqualityComparer.null_check_equals(_security_predicate, other._security_predicate);
public override bool Equals(object obj) =>
Equals(obj as OrderStatusTransitionPredicate);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash((int)_status, _security_predicate == null ? 0 : _security_predicate.GetHashCode());
}
}
}
@@ -57,7 +57,6 @@ namespace mbts {
FillTriggerModel _create_model(INotificationServiceDataCache nsdc) =>
new FillTriggerModel(nsdc, security?.create(nsdc));
class FillTriggerModel {
readonly IPredicate<SecurityImmutable> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
@@ -68,9 +67,15 @@ namespace mbts {
}
public (bool trigger, OrderRecordTuple oldval, OrderRecordTuple newval) get_filled_order_args(OrderRecordTuple ort) {
if (ort.order.is_exchange_order() && (_security_predicate == null || (ort.security_md.HasValue && _security_predicate.trigger(ort.security_md.Value.security)))) {
if (ort.order.is_exchange_order() && OrderEventPredicateHelper.check_security_predicate(ort, _security_predicate)) {
if (_data_cache.get_previous_order_state(ort.order.Key) is OrderRecordTuple oldval)
return (ort.order.filled() > oldval.order.filled(), oldval, ort);
else if (!_data_cache.is_first_order_update && ort.order.filled() > 0) {
// old order will be a copy of new order, except with filledQuantity set to 0
var old_state = ort.order.State.CloneToMutable();
old_state.FilledQuantity = 0;
return (true, new OrderRecordTuple(ort.order.with(state: old_state), ort.security_md), ort);
}
}
return (false, null, null);
}
@@ -188,7 +188,7 @@ namespace mbts.ui.settings {
public PredicatePlaceholderVM(Action<TPredicateBuilder> set = null) =>
_set = set;
public string key => null;
public string key => PredicateTemplateKeys.None;
public void assign_to(TPredicateBuilder value) => _set?.Invoke(value);
public void load_from(TPredicateBuilder value) { }
public override string ToString() => string.Empty;
+4 -4
View File
@@ -74,9 +74,9 @@ namespace bts.spark
// Support
public static SparkCommand ShowManual =>
SparkCommand.create("Manual", Icons.Book, SparkTags.ShowUri, new Uri("bts://m/"));
SparkCommand.create("Manual", Icons.Browser, SparkTags.ShowUri, new Uri("https://www.bluetradingsystems.com/documentation/"));
public static SparkCommand ShowReleaseNotes =>
public static SparkCommand ShowReleaseNotes =>
SparkCommand.create("Release Notes", Icons.Browser, SparkTags.ShowUri, new Uri("bts://files/release_notes.txt"));
public static SparkCommand DoNothing =>
@@ -112,6 +112,6 @@ namespace bts.spark
SparkCommand.create("Recreate", Icons.Beaker, SparkTags.RecreateOrder);
public static SparkCommand grid_settings_command(IDialogCommand launch_settings_editor) =>
new SparkCommandWrapper("Grid Settings", Icons.ViewSettings, launch_settings_editor);
new SparkCommandWrapper("Window Settings", Icons.Tools, launch_settings_editor);
}
}
}
@@ -4,6 +4,11 @@ using System.Collections.ObjectModel;
using System.Windows.Input;
namespace mbts.collections {
static class ObservableEditableCollection {
public static ObservableEditableCollection<T> create<T>() where T : new() =>
new ObservableEditableCollection<T>(() => new T());
}
class ObservableEditableCollection<T> : ObservableCollection<T> {
public ObservableEditableCollection(Func<T> factory, bool insert_new_item_at_front = false) {
AddItemCommand = insert_new_item_at_front ? new DelegateCommand(() => Insert(0, factory())) : new DelegateCommand(() => Add(factory()));
@@ -15,6 +15,11 @@ namespace mbts.utils {
throw new ArgumentException($"Must not be of type {typeof(T)}.", name);
}
public static void must_be_so(bool condition, string condition_description, string name) {
if (!condition)
throw ExceptionBuilder.Argument.must_be(condition_description, name);
}
public static void NotNull(object argument, string name) {
if (argument == null)
throw new ArgumentNullException(name);
@@ -0,0 +1,10 @@
using System;
namespace mbts.utils {
static class ExceptionBuilder {
public static class Argument {
public static ArgumentException must_be(string description, string name) =>
new ArgumentException($"Must be {description}.", name);
}
}
}
@@ -7,7 +7,7 @@ namespace mbts.ui {
// Some colos are also available as static resources in colors.xaml
public static class BTSColors {
static Brush _header_brush, _header_text_brush, _header_alternate_brush, _header_error_text_brush;
static BTSColors() {
_init_brush(header, out _header_brush);
_init_brush(header_text, out _header_text_brush);
@@ -67,8 +67,8 @@ namespace mbts.ui {
[DisplayInfo(name = "Cross Sell Alert")]
public static BTSColor cross_sell { get { return BTSCoreColors.red_light; } }
[DisplayInfo(name = "Proximity Sell Alert")]
public static BTSColor proximity_sell { get { return BTSCoreColors.red_lighter; } }
public static BTSColor proximity_sell { get { return BTSCoreColors.red_lighter; } }
}
public static class MarketData {
@@ -79,20 +79,22 @@ namespace mbts.ui {
// therefore need to ensure that _bid/_ask are not null before instantiating bid_brush/ask_brush
bid = new BTSColor(0x16, 0x7e, 0xd3);
ask = BTSCoreColors.red_darker;
session_low = new BTSColor(89, 89, 107);
session_high = new BTSColor(35, 155, 0);
_bid_brush = bid;
_ask_brush = ask;
}
// Base Colors
[DisplayInfo(name = "Market Data")]
public static BTSColor default_background { get { return BTSCoreColors.blue_light_lighter; } }
public static BTSColor default_background { get { return BTSCoreColors.blue_light_lighter; } }
public static BTSColor default_text { get { return BTSCoreColors.black; } }
//Another bid color option: 40,70,200
public static BTSColor bid { get; }
public static BTSColor bid_alt { get { return BTSCoreColors.blue_light; } }
public static BTSColor ask { get; }
public static BTSColor ask_alt { get { return BTSCoreColors.red_light_dark; } }
public static BTSColor last { get { return BTSCoreColors.black; } }
public static BTSColor bid_ask_alt_blend => BTSCoreColors.purple_light;
public static Brush bid_brush => _bid_brush;
public static Brush ask_brush => _ask_brush;
@@ -104,8 +106,9 @@ namespace mbts.ui {
[DisplayInfo(name = "ATM")]
public static BTSColor atm_background { get { return BTSCoreColors.gray_dark; } }
public static BTSColor session_low { get; }
public static BTSColor session_high { get; }
public static BTSColor session_low { get; } = new BTSColor(89, 89, 107);
public static BTSColor session_high { get; } = new BTSColor(35, 155, 0);
public static BTSColor session_range_fill { get; } = Colors.Black;
// Alerts
[DisplayInfo(name = "Trade Alert")]
@@ -113,7 +116,7 @@ namespace mbts.ui {
[DisplayInfo(name = "Trade price over Theo Alert")]
public static BTSColor trade_price_over_theo { get { return BTSCoreColors.red_pale_dark; } }
[DisplayInfo(name = "Trade price under Theo Alert")]
public static BTSColor trade_price_under_theo { get { return BTSCoreColors.blue_bright_dark; } }
public static BTSColor trade_price_under_theo { get { return BTSCoreColors.blue_bright_dark; } }
}
@@ -185,9 +188,9 @@ namespace mbts.ui {
public static readonly Brush working_order_background_brush;
public static BTSColor filled { get { return BTSCoreColors.green_light_light_saturated; } }
public static BTSColor filled_dark => BTSCoreColors.green;
public static BTSColor filled_dark => BTSCoreColors.green;
public static readonly Brush filled_dark_brush; // used in ladder log viewer
public static BTSColor modified => orange;
public static BTSColor modified => orange;
public static readonly Brush modified_brush; // used in the ladder log viewer
[DisplayInfo(name = "Order Buy Text")]
@@ -263,7 +266,7 @@ namespace mbts.ui {
public static class Presave
{
[DisplayInfo(name = "Presave")]
public static BTSColor default_background { get { return BTSCoreColors.yellow_light; } }
public static BTSColor default_background { get { return BTSCoreColors.yellow_light; } }
public static BTSColor default_text { get { return BTSCoreColors.black; } }
}
@@ -305,14 +308,13 @@ namespace mbts.ui {
public static BTSColor grid_line { get { return new BTSColor(64, 0, 0, 0); } }
}
public static class UI
{
public static class UI {
[DisplayInfo(name = "Shell Background")]
public static BTSColor default_background { get { return new BTSColor(0xf6, 0xf6, 0xf6); } }
[DisplayInfo(name = "Shell Text")]
public static BTSColor default_text { get { return new BTSColor(0x22); } }
public static BTSColor alternate_text { get { return BTSCoreColors.white; } }
public static BTSColor menu_expander_mouseover { get { return BTSCoreColors.blue_bright; } }
public static BTSColor spark_menu_background { get { return new BTSColor(0xe9); } }
@@ -323,6 +325,7 @@ namespace mbts.ui {
public static BTSColor input_mouseover_background { get { return new BTSColor(0xAB, 0xAD, 0xB3); } }
public static BTSColor input_selected_border { get { return new BTSColor(0x7E, 0xB4, 0xEA); } }
public static BTSColor input_selected_background { get { return new BTSColor(0xAB, 0xAD, 0xB3); } }
public static BTSColor text_prompt_foreground_color => 0x99999999;
public static BTSColor input_disabled_text => new BTSColor(0x87);
public static BTSColor input_disabled_text_dark => new BTSColor(0x66);
@@ -334,6 +337,9 @@ namespace mbts.ui {
public static BTSColor input_dirty_border => warning;
public static Brush text_prompt_foreground_brush { get; } = text_prompt_foreground_color.to_brush().frozen();
public static Brush input_disabled_text_brush { get; } = input_disabled_text.to_brush().frozen();
public static class ComboBox
{
// Normal
@@ -375,7 +381,7 @@ namespace mbts.ui {
public static BTSColor unfocused_glyph { get { return normal_text; } }
public static BTSColor unfocused_button_border { get { return UI.transparent; } }
public static BTSColor unfocused_button_background { get { return UI.transparent; } }
// Selected
public static BTSColor selected_border { get { return UI.input_selected_border; } }
public static BTSColor selected_background { get { return input_selected_background; } }
@@ -383,7 +389,7 @@ namespace mbts.ui {
public static BTSColor selected_glyph { get { return normal_text; } }
public static BTSColor selected_button_border { get { return UI.transparent; } }
public static BTSColor selected_button_background { get { return UI.transparent; } }
// Disabled
public static BTSColor disabled_border { get { return UI.input_disabled_border; } }
public static BTSColor disabled_background { get { return UI.input_disabled_background; } }
@@ -391,7 +397,7 @@ namespace mbts.ui {
public static BTSColor disabled_glyph { get { return normal_text; } }
public static BTSColor disabled_button_border { get { return UI.transparent; } }
public static BTSColor disabled_button_background { get { return UI.transparent; } }
// Valid
public static BTSColor valid_background { get { return normal_background; } }
public static BTSColor valid_border { get { return normal_border; } }
@@ -518,7 +524,7 @@ namespace mbts.ui {
public static BTSColor warning_dark { get { return new BTSColor(114, 61, 0); } }
public static BTSColor warning_light { get { return new BTSColor(Colors.LightYellow); } }
public static BTSColor brand_lightest { get { return new BTSColor(230, 243, 249); } }
public static BTSColor brand_lighter { get { return new BTSColor(191, 225, 239); } }
[DisplayInfo(name = "BTS Brand Light")]
@@ -552,8 +558,8 @@ namespace mbts.ui {
public static BTSColor gray_lightest { get { return BTSCoreColors.gray_lightest; } }
public static BTSColor transparent { get { return new BTSColor(0, 0, 0, 0); } }
}
public static class LauncherColors
@@ -563,7 +569,7 @@ namespace mbts.ui {
public static BTSColor alternate_text { get { return UI.alternate_text; } }
public static BTSColor separator { get { return new BTSColor(0x99); } }
}
public static class VolSurfaceGraph
{
@@ -576,7 +582,7 @@ namespace mbts.ui {
[DisplayInfo(name = "Vol Surface ATM")]
public static BTSColor main_curve_atm { get { return BTSCoreColors.green; } }
[DisplayInfo(name = "Vol Surface Call Special")]
public static BTSColor call_special { get { return BTSCoreColors.red; } }
public static BTSColor call_special { get { return BTSCoreColors.red; } }
[DisplayInfo(name = "Vol Surface Put Implied Vol")]
public static BTSColor implied_put { get { return BTSCoreColors.blue_bright_light; } }
[DisplayInfo(name = "Vol Surface ATM Implied Vol")]
@@ -644,8 +650,8 @@ namespace mbts.ui {
public static Color logo_gray { get { return Color.FromRgb(179, 179, 179); } }
public static Brush logo_gray_brush { get { return new SolidColorBrush(logo_gray); } }
public static Color common_background { get { return UI.default_background; } }
public static Brush common_background_brush { get { return new SolidColorBrush(common_background); } }
public static Color common_background => UI.default_background;
public static Brush common_background_brush { get; } = common_background.to_brush().frozen();
public static Color accent1 { get { return UI.accent_light; } }
public static Brush accent1_brush { get { return new SolidColorBrush(accent1); } }
@@ -125,5 +125,9 @@ namespace mbts.ui
public static BTSColor orange_light = new BTSColor(0xff, 0x98, 0x52); //FF9852
public static BTSColor orange = new BTSColor(0xed, 0x79, 0x2a); //ED792A
public static BTSColor orange_dark = new BTSColor(0xc0, 0x56, 0x0f); //C0560F
// Purple
public static BTSColor purple_light = new BTSColor(0xcc, 0xb8, 0xc8); //CCB8C8
}
}
@@ -10,5 +10,19 @@ namespace mbts {
public static double CoerceNaNOrInfinity(double value) => CoerceNaNOrInfinity(value, 0.0);
public static double CoerceNaNOrInfinity(double value, double if_nan_or_infinity) => IsNaNOrInfinity(value) ? if_nan_or_infinity : value;
public static double MultiplyIfNotNaN(double value, double mult) => double.IsNaN(mult) ? value : value * mult;
public static uint safe_convert_to_uint(double value) {
switch (value) {
case double.PositiveInfinity: return uint.MaxValue;
case double.NegativeInfinity:
case double.NaN: return 0;
default:
if (value < 0) {
return 0;
} else if (value > uint.MaxValue) {
return uint.MaxValue;
}
return (uint)value;
}
}
}
}
@@ -359,6 +359,24 @@ namespace System.Collections.Generic {
foreach (IDisposable d in source)
d.Dispose();
}
public static IEnumerable<T> return_if<T>(bool condition, Func<T> get_value) {
if (condition)
yield return get_value();
}
/// <summary>
/// Uses <see cref="ObjectHelper.try_convert{TResult}(object)"/> to convert the elements of an <see cref="IEnumerable"/> to the specified type.
/// </summary>
/// <typeparam name="TResult">The type to convert the elements of source to.</typeparam>
/// <param name="source">The <see cref="IEnumerable"/> that contains the elements to be cast to type <typeparamref name="TResult"/></param>
/// <returns>An <see cref="IEnumerable{TResult}"/> that contains each element of the source sequence cast to the specified type.</returns>
/// <exception cref="ArgumentNullException"><paramref name="source"/> is null.</exception>
public static IEnumerable<TResult> convert<TResult>(this IEnumerable source) {
ExceptionAssert.Argument.NotNull(source, nameof(source));
foreach (object obj in source)
yield return ObjectHelper.try_convert<TResult>(obj);
}
}
public static class CollectionExtensions
@@ -70,10 +70,6 @@ namespace mbts
}
#endregion
public static T choose<T>(this Random r, IEnumerable<T> range) {
var index = r.Next(0, range.Count());
return range.Skip(index).First();
}
// Iterate through a list 1,2,3,4 and return the items in pairwise tuples (1,2), (2,3), (3,4)
// This is better than using Zip+Skip because it iterates the collectiononly once
@@ -1,4 +1,6 @@
namespace System
using mbts.ui.utility;
namespace System
{
public static class ObjectHelper
{
@@ -18,7 +20,7 @@
result = obj;
return true;
} else if (type.IsEnum && obj is string) {
result = Enum.Parse(type, obj.ToString());
result = EnumHelper.try_parse(type, obj.ToString());
return true;
} else if (type.IsNullable()) {
return try_convert(type.GetGenericArguments()[0], obj, out result);
@@ -5,6 +5,7 @@ using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Reactive.Linq;
using System.Runtime.CompilerServices;
@@ -30,6 +31,10 @@ namespace mbts.spark {
void load_from(T value);
}
interface IMutableValueWrapperVM<T> : INotifyPropertyChanged {
T value { get; set; }
}
interface IViewValue {
object value { get; }
object view { get; }
@@ -70,6 +75,12 @@ namespace mbts.spark {
return vm;
}
public static IMutableValueWrapperVM<T> create_mutable_vm<T>(T init = default) =>
create_mutable_vm(EqualityComparer<T>.Default, init);
public static IMutableValueWrapperVM<T> create_mutable_vm<T>(IEqualityComparer<T> comparer, T init = default) =>
new MutableValueWrapperVM<T>(comparer, init);
public static ITemplatedPropertyWrapperVM<TSource> create_vm<TSource, TValue>(string template_key, Func<TSource, TValue> get, Action<TSource, TValue> set, Dictionary<string, IObservable<object>> named_params = null) =>
new DelegatePropertyWrapperVM<TSource, TValue>(template_key, get, set, named_params);
@@ -88,6 +99,20 @@ namespace mbts.spark {
public static IPropertyWrapperVM<TOutter> link<TOutter, TInner>(this IPropertyWrapperVM<TInner> inner, Func<TOutter, TInner> get, Action<TOutter, TInner> set) =>
new LinkedPropertyWrapperVM<TOutter, TInner>(inner, get, set);
class MutableValueWrapperVM<T> : ViewModelBase, IMutableValueWrapperVM<T> {
readonly IEqualityComparer<T> _comparer;
readonly Property<T> _value;
public MutableValueWrapperVM(IEqualityComparer<T> comparer, T init) {
_comparer = comparer;
_value = backing(nameof(value), comparer, init);
}
public T value { get => _value.Value; set => _value.set(value); }
public override string ToString() => value?.ToString();
}
class LinkedPropertyWrapperVM<TOutter, TInner> : ViewModelBase, IPropertyWrapperVM<TOutter> {
readonly Func<TOutter, TInner> _get;
readonly Action<TOutter, TInner> _set;
@@ -4,7 +4,6 @@ using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Threading;
namespace mbts.utils {
interface IObservableDemuxer<TKey, in TInput, out TOutput> : IObserver<TInput> {
@@ -13,28 +12,26 @@ namespace mbts.utils {
abstract class ObservableDemuxerBase<TKey, TInput, TOutput> : IObservableDemuxer<TKey, TInput, TOutput>, IDisposable {
readonly ConcurrentDictionary<TKey, Data> _cache = new ConcurrentDictionary<TKey, Data>();
#pragma warning disable CS0612 // Type or member is obsolete
readonly DisposableSingle _dispose;
#pragma warning restore CS0612 // Type or member is obsolete
readonly ThreadSafeDisposable _dispose;
protected ObservableDemuxerBase() { }
protected ObservableDemuxerBase(IObservable<TInput> source) {
var sub = source.Subscribe(this);
#pragma warning disable CS0612 // Type or member is obsolete
_dispose = new DisposableSingle(() => {
#pragma warning restore CS0612 // Type or member is obsolete
_dispose = new ThreadSafeDisposable(dispose_core);
//
void dispose_core() {
sub.Dispose();
Dispose(true);
});
}
}
public IObservable<TOutput> subscribe(TKey key) {
_dispose.check_not_disposed();
return _cache.GetOrAdd(key, k => new Data(this));
}
public IObservable<TOutput> subscribe(TKey key) =>
_cache.GetOrAdd(key, k => new Data(this));
public void OnNext(TInput input) {
_dispose.check_not_disposed();
if (_dispose.has_dispose_started) {
return;
}
var output = demux(input);
foreach (var kv in output) {
_cache.AddOrUpdate(kv.Key,
@@ -81,7 +78,7 @@ namespace mbts.utils {
protected override IDictionary<TKey, TValue> demux(IDictionary<TKey, TValue> input) => input;
}
class TableUpdateDemuxer<T, TKey, TGroupKey> : IObservableDemuxer<TGroupKey, TableUpdate<T, TKey>, ITableUpdateTransform<T, TKey>>
class TableUpdateDemuxer<T, TKey, TGroupKey> : IObservableDemuxer<TGroupKey, LegacyTableUpdate<T, TKey>, ITableUpdateTransform<T, TKey>>
where TKey : IEquatable<TKey>
where TGroupKey : IEquatable<TGroupKey> {
readonly ConcurrentDictionary<TGroupKey, Data> _map = new ConcurrentDictionary<TGroupKey, Data>();
@@ -96,7 +93,7 @@ namespace mbts.utils {
public IObservable<ITableUpdateTransform<T, TKey>> subscribe(TGroupKey group_key) =>
Observable.Create<ITableUpdateTransform<T, TKey>>(o => {
var data = _map.GetOrAdd(group_key, gk => new Data());
using (data.read()) {
lock (data) {
o.OnNext(data.current.as_snapshot());
return data.subject.Subscribe(o);
}
@@ -104,7 +101,7 @@ namespace mbts.utils {
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(TableUpdate<T, TKey> table) {
public void OnNext(LegacyTableUpdate<T, TKey> table) {
var changes = new Dictionary<TGroupKey, ChangeSet>();
foreach (T value in table.added)
changes.AddOrUpdate(_group_key(value), gk => ChangeSet.from_added(value), (gk, cs) => cs.added.Add(value));
@@ -116,29 +113,15 @@ namespace mbts.utils {
}
Data _update(Data data, ChangeSet changes) {
using (data.write())
lock (data) {
data.subject.OnNext(data.current = data.current.update(changes.removed, changes.added, _key));
return data;
return data;
}
}
class Data {
int _n_read_ops, _n_write_ops;
public readonly Subject<TableUpdateTransform<T, TKey>> subject = new Subject<TableUpdateTransform<T, TKey>>();
public TableUpdateTransform<T, TKey> current = new TableUpdateTransform<T, TKey>();
public IDisposable read() {
while (_n_write_ops > 0)
Thread.Yield();
Interlocked.Increment(ref _n_read_ops);
return Disposable.Create(() => Interlocked.Decrement(ref _n_read_ops));
}
public IDisposable write() {
while (_n_read_ops > 0)
Thread.Yield();
Interlocked.Increment(ref _n_write_ops);
return Disposable.Create(() => Interlocked.Decrement(ref _n_write_ops));
}
}
// [John]I prefer this class over anonymous tuples bc it is easy to mix up Item1/Item2
@@ -14,8 +14,8 @@ namespace mbts.utils {
interface ITableUpdateTransform<T, TKey> where TKey : IEquatable<TKey> {
IReadOnlyDictionary<TKey, T> state { get; }
IReadOnlyList<T> added { get; }
IReadOnlyList<T> removed { get; }
IEnumerable<T> added { get; }
IEnumerable<T> removed { get; }
}
class IncrementalUpdate<T, TKey> : IIncrementalUpdate<T, TKey> where TKey : IEquatable<TKey> {
@@ -33,20 +33,20 @@ namespace mbts.utils {
class TableUpdateTransform<T, TKey> : ITableUpdateTransform<T, TKey> where TKey : IEquatable<TKey> {
readonly Dictionary<TKey, T> _state;
readonly IReadOnlyList<T> _added, _removed;
readonly IEnumerable<T> _added, _removed;
internal TableUpdateTransform() :
this(new Dictionary<TKey, T>(), new List<T>(0), new List<T>(0)) { }
internal TableUpdateTransform(Dictionary<TKey, T> init, IReadOnlyList<T> added, IReadOnlyList<T> removed) {
internal TableUpdateTransform(Dictionary<TKey, T> init, IEnumerable<T> added, IEnumerable<T> removed) {
_state = init;
_added = added;
_removed = removed;
}
public IReadOnlyDictionary<TKey, T> state => _state;
public IReadOnlyList<T> added => _added;
public IReadOnlyList<T> removed => _removed;
public IEnumerable<T> added => _added;
public IEnumerable<T> removed => _removed;
public TableUpdateTransform<T, TKey> update(Update<T, TKey> update) =>
this.update(update.removed, update.added, update.key);
@@ -54,7 +54,7 @@ namespace mbts.utils {
public TableUpdateTransform<T, TKey> update(TableUpdate<T, TKey> update, Func<T, TKey> key) =>
this.update(update.removed, update.added, key);
public TableUpdateTransform<T, TKey> update(IReadOnlyList<T> removed, IReadOnlyList<T> added, Func<T, TKey> key) {
public TableUpdateTransform<T, TKey> update(IEnumerable<T> removed, IEnumerable<T> added, Func<T, TKey> key) {
var table = new TableUpdateTransform<T, TKey>(new Dictionary<TKey, T>(_state), added, removed);
foreach (var item in removed)
table._state.Remove(key(item));
@@ -86,7 +86,7 @@ namespace mbts.utils {
public static IObservable<ITableUpdateTransform<T, TKey>> filter<T, TKey>(this IObservable<ITableUpdateTransform<T, TKey>> source, Func<T, bool> predicate)
where TKey : IEquatable<TKey> => source
.Select(u => new FilteredTableUpdateTransform<T, TKey>(u, predicate))
.Where(u => u.added.Count > 0 || u.removed.Count > 0);
.Where(u => u.added.Any() || u.removed.Any());
/// <summary>
/// Makes a 1:1 conversion to an IncrementalUpdate sequence of TResult (TKey remains the same).
@@ -143,8 +143,8 @@ namespace mbts.utils {
}
public IReadOnlyDictionary<TKey, T> state { get; }
public IReadOnlyList<T> added { get; }
public IReadOnlyList<T> removed { get; }
public IEnumerable<T> added { get; }
public IEnumerable<T> removed { get; }
}
class PivotIncrementalUpdate<T, TKey, TResult, TResultKey> : IIncrementalUpdate<TResult, TResultKey> where TKey : IEquatable<TKey> where TResultKey : IEquatable<TResultKey> {
@@ -208,7 +208,7 @@ namespace mbts.utils {
internal PivotTableUpdateTransform(Func<T, TResult> selector, Func<TResult, TResultKey> result_key, Func<T, TKey> key) :
this(new Dictionary<TResultKey, TResult>(), new List<TResult>(0), new List<TResult>(0), new SetMap<TResultKey, TKey>(), selector, result_key, key) { }
PivotTableUpdateTransform(Dictionary<TResultKey, TResult> state, IReadOnlyList<TResult> added, IReadOnlyList<TResult> removed,
PivotTableUpdateTransform(Dictionary<TResultKey, TResult> state, IEnumerable<TResult> added, IEnumerable<TResult> removed,
SetMap<TResultKey, TKey> key_map, Func<T, TResult> selector, Func<TResult, TResultKey> result_key, Func<T, TKey> key) {
//
_state = state;
@@ -221,8 +221,8 @@ namespace mbts.utils {
}
public IReadOnlyDictionary<TResultKey, TResult> state => _state;
public IReadOnlyList<TResult> added { get; }
public IReadOnlyList<TResult> removed { get; }
public IEnumerable<TResult> added { get; }
public IEnumerable<TResult> removed { get; }
public PivotTableUpdateTransform<T, TKey, TResult, TResultKey> update(ITableUpdateTransform<T, TKey> table) {
Dictionary<TResultKey, TResult> removed = new Dictionary<TResultKey, TResult>(), added = new Dictionary<TResultKey, TResult>();
+28 -3
View File
@@ -113,8 +113,11 @@ namespace mbts.ui.shell
protected delegate void PropertyChange<T>(T oldval, T newval);
// use nameof() to add compile time checks
protected Property<T> backing<T>(string name, T default_value = default(T)) {
return new Property<T>(this, name, default_value);
protected Property<T> backing<T>(string name, T default_value = default(T)) =>
backing(name, EqualityComparer<T>.Default, default_value);
protected Property<T> backing<T>(string name, IEqualityComparer<T> comparer, T default_value = default(T)) {
return new Property<T>(this, name, comparer, default_value);
}
protected Property<T> backing<T>(Expression<Func<T>> member, T default_value) {
@@ -134,12 +137,17 @@ namespace mbts.ui.shell
protected class Property<T> : IObservable<(T oldval,T newval)> {
readonly string _propname;
readonly IEqualityComparer<T> _comparer;
readonly ViewModelBase _owner;
T _value;
public Property(ViewModelBase owner, string name, T default_value) {
public Property(ViewModelBase owner, string name, T default_value)
: this(owner, name, EqualityComparer<T>.Default, default_value) { }
public Property(ViewModelBase owner, string name, IEqualityComparer<T> comparer, T default_value) {
_owner = owner;
_propname = name;
_comparer = comparer;
_value = default_value;
}
@@ -288,6 +296,16 @@ namespace mbts.ui.shell
/// Sets 'setter_called' to false.
/// </summary>
public void reset() => setter_called = false;
public void on_inline_prop(InlineUserProperty<T> inline_prop) {
if (inline_prop.force_override || (inline_prop.has_value && !setter_called))
bypass_setter(inline_prop.value);
}
public void on_inline_prop<TIn>(InlineUserProperty<TIn> inline_prop, Func<TIn, T> select) {
if (inline_prop.force_override || (inline_prop.has_value && !setter_called))
bypass_setter(select(inline_prop.value));
}
}
#endregion
@@ -447,6 +465,13 @@ namespace mbts.ui.shell
return prop;
}
protected UserProperty<T> user_backing<T>(string name, T default_value = default) =>
new UserProperty<T>(backing(name, default_value));
protected UserProperty<T> user_backing<T>(Property<T> property) =>
new UserProperty<T>(property);
// TODO: maybe include a revert_on_error flag?
protected class PropertyValidation<T> {
public readonly Func<T, (bool valid, string msg)> validate;
@@ -0,0 +1,21 @@
using System;
namespace bts {
struct AccountTuple : IEquatable<AccountTuple> {
public readonly uint id;
public readonly string name;
public AccountTuple(uint id, string name) {
this.id = id;
this.name = name;
}
public bool Equals(AccountTuple other) => other.id == id && other.name == name;
public override bool Equals(object obj) => obj is AccountTuple other && Equals(other);
public override int GetHashCode() => id.GetHashCode();
public override string ToString() => name;
public static bool operator ==(AccountTuple a, AccountTuple b) => a.Equals(b);
public static bool operator !=(AccountTuple a, AccountTuple b) => !a.Equals(b);
}
}
+21
View File
@@ -0,0 +1,21 @@
using System;
namespace bts {
struct UserTuple : IEquatable<UserTuple> {
public readonly uint id;
public readonly string name;
public UserTuple(uint id, string name) {
this.id = id;
this.name = name;
}
public bool Equals(UserTuple other) => other.id == id && other.name == name;
public override bool Equals(object obj) => obj is UserTuple other && Equals(other);
public override int GetHashCode() => id.GetHashCode();
public override string ToString() => name;
public static bool operator ==(UserTuple a, UserTuple b) => a.Equals(b);
public static bool operator !=(UserTuple a, UserTuple b) => !a.Equals(b);
}
}
-2
View File
@@ -75,6 +75,4 @@
<SolidColorBrush x:Key="ComboBox.Disabled.Editable.Button.Background" Color="Transparent"/>
<SolidColorBrush x:Key="ComboBox.Disabled.Editable.Button.Border" Color="Transparent"/>
<SolidColorBrush x:Key="ComboBox.Static.Glyph" Color="#FF606060"/>
<SolidColorBrush x:Key="Text.Prompt.Foreground.Brush" Color="{StaticResource Text.Prompt.Foreground.Color}"/>
</ResourceDictionary>
+140 -2
View File
@@ -1,9 +1,12 @@
using bts.api;
using bts.api.orderman;
using mbts.spark;
using mbts.ui.utility.text;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
@@ -26,8 +29,16 @@ namespace mbts.ui.controls {
DefaultWidth = 63; // **
public static readonly FontFamily DefaultFontFamily = new FontFamily("Consolas");
// I am thinking that depending on how people have different ladder windows configured, the vertex points may be at different positions
//static ConcurrentDictionary<(Point p1, Point p2, Point p3), StreamGeometry> _sg_cache = new ConcurrentDictionary<(Point p1, Point p2, Point p3), StreamGeometry>();
readonly GlyphContentRect _gcr = new GlyphContentRect();
Brush _background, _foreground, _border_brush;
Brush _background, _foreground, _border_brush, _parent_algo_type_brush;
bool _is_exchange_order, _has_multiple_orders_at_level, _is_hedge_order;
CustomOrderDefinition.CustomOneofCase _parent_algo_type;
(Point p1, Point p2, Point p3) _current_triangle_vertices;
StreamGeometry _triangle_geometry;
static Badge() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(typeof(Badge)));
@@ -166,6 +177,9 @@ namespace mbts.ui.controls {
_border_brush = BorderBrush;
_gcr.font_size = FontSize;
_gcr.text_lines = TextLines;
_is_exchange_order = IsExchangeOrder;
_has_multiple_orders_at_level = HasMultipleOrdersAtLevel;
_is_hedge_order = IsHedgeOrder;
_gcr.glyph_context = GlyphContext.create(FontFamily, FontWeight);
}
@@ -190,6 +204,66 @@ namespace mbts.ui.controls {
public static readonly DependencyProperty CornerRadiusProperty =
WPFHelper.create_dp<double, Badge>(nameof(CornerRadius), DefaultCornerRadius);
public bool IsExchangeOrder {
get { return (bool)GetValue(IsExchangeOrderProperty); }
set { SetValue(IsExchangeOrderProperty, value); }
}
public static readonly DependencyProperty IsExchangeOrderProperty =
WPFHelper.create_dp<bool, Badge>(
nameof(IsExchangeOrder),
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._is_exchange_order = v,
false);
public bool HasMultipleOrdersAtLevel {
get { return (bool)GetValue(IsMultipleOrdersAtLevelProperty); }
set { SetValue(IsMultipleOrdersAtLevelProperty, value); }
}
public static readonly DependencyProperty IsMultipleOrdersAtLevelProperty =
WPFHelper.create_dp<bool, Badge>(
nameof(HasMultipleOrdersAtLevel),
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._has_multiple_orders_at_level = v,
false);
public CustomOrderDefinition.CustomOneofCase ParentAlgoType {
get { return (CustomOrderDefinition.CustomOneofCase)GetValue(ParentAlgoTypeProperty); }
set { SetValue(ParentAlgoTypeProperty, value); }
}
public static readonly DependencyProperty ParentAlgoTypeProperty =
WPFHelper.create_dp<CustomOrderDefinition.CustomOneofCase, Badge>(
nameof(ParentAlgoType),
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._parent_algo_type = v,
CustomOrderDefinition.CustomOneofCase.None);
public Brush ParentAlgoTypeBrush {
get { return (Brush)GetValue(ParentAlgoTypeBrushProperty); }
set { SetValue(ParentAlgoTypeBrushProperty, value); }
}
public static readonly DependencyProperty ParentAlgoTypeBrushProperty =
WPFHelper.create_dp<Brush, Badge>(
nameof(ParentAlgoTypeBrush),
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._parent_algo_type_brush = v,
Brushes.White);
public bool IsHedgeOrder {
get { return (bool)GetValue(IsHedgeOrderProperty); }
set { SetValue(IsHedgeOrderProperty, value); }
}
public static readonly DependencyProperty IsHedgeOrderProperty =
WPFHelper.create_dp<bool, Badge>(
nameof(IsHedgeOrder),
FrameworkPropertyMetadataOptions.AffectsRender,
(b, v) => b._is_hedge_order = v,
false);
protected override Size ArrangeOverride(Size finalSize) => finalSize;
protected override Size MeasureOverride(Size availableSize) {
@@ -199,12 +273,76 @@ namespace mbts.ui.controls {
protected override void OnRender(DrawingContext dc) {
base.OnRender(dc);
// this is the main badge rectangle
double border_thickness = BorderThickness.Top;
var pen = new Pen(BorderBrush, border_thickness);
Pen pen = new Pen(BorderBrush, border_thickness);
pen = pen.frozen();
dc.DrawRoundedRectangle(Background, pen, new Rect(0, border_thickness, _gcr.layout_size.Width, _gcr.layout_size.Height), CornerRadius, CornerRadius);
if (HasMultipleOrdersAtLevel) {
_draw_triangle(
new Point(_gcr.layout_size.Width - (2 * border_thickness - CornerRadius), _gcr.layout_size.Height - 5), // top right
new Point(_gcr.layout_size.Width - (2 * border_thickness - CornerRadius), _gcr.layout_size.Height), // bottom right
new Point(_gcr.layout_size.Width - (2 * border_thickness - CornerRadius) - 5, _gcr.layout_size.Height), // bottom left
Brushes.IndianRed
);
} else {
if (IsExchangeOrder) {
// for the y-component, since we start the main badge RoundedRectangle at border_thickness,
// we have to include that in our y pos start position as well.
(pen = new Pen(Brushes.Black, border_thickness)).Freeze();
dc.DrawEllipse(Brushes.Black, pen, new Point(_gcr.layout_size.Width - 2 * border_thickness - CornerRadius, 0 + border_thickness + 2 * border_thickness + CornerRadius), 2, 2);
}
if (IsHedgeOrder) {
(pen = new Pen(Brushes.Black, border_thickness)).Freeze();
dc.DrawLine(pen,
new Point(2 * border_thickness, 0 + 2 * border_thickness),
new Point(2 * border_thickness, _gcr.layout_size.Height)
);
}
if (ParentAlgoType != CustomOrderDefinition.CustomOneofCase.None) {
dc.DrawRectangle(ParentAlgoTypeBrush, null, new Rect(4 * border_thickness, 0 + 2 * border_thickness, 10, _gcr.layout_size.Height - 2 * border_thickness));
//var chars = Enumerable.Range('A', 26).Select(x => (char)x).ToArray();
//var text = new string(chars);
var palgo_type_name = utility.EnumHelper.get_display_name(ParentAlgoType);
if (palgo_type_name.Length > 1) {
var palgo_letter = palgo_type_name.Substring(0, 1);
var a_glyph_context = _gcr.glyph_context;
var a_glyph_run = a_glyph_context.get_glyph_run(
palgo_letter,
12,
_gcr.layout_size.Width,
_gcr.layout_size.Height,
HorizontalAlignment.Left,
4 * border_thickness + 1,
VerticalAlignment.Center,
0);
dc.DrawGlyphRun(Brushes.Black, a_glyph_run);
}
}
}
var gr = _gcr.glyph_run;
if (gr != null)
dc.DrawGlyphRun(_foreground, gr);
void _draw_triangle(Point p1, Point p2, Point p3, Brush b) {
if (!(p1 == _current_triangle_vertices.p1 && p2 == _current_triangle_vertices.p2 && p3 == _current_triangle_vertices.p3)) {
_triangle_geometry = new StreamGeometry();
using (var sgc = _triangle_geometry.Open()) {
sgc.BeginFigure(p1, true, true);
sgc.PolyLineTo(new Point[] { p2, p3 }, true, true);
}
_current_triangle_vertices = (p1, p2, p3);
_triangle_geometry.Freeze();
}
(pen = new Pen(b, 1)).Freeze();
dc.DrawGeometry(b, pen, _triangle_geometry);
}
}
}
@@ -14,10 +14,7 @@ namespace mbts.ui.settings {
readonly Property<SoundNotification.SoundTypeOneofCase> _selected_sound_type;
public SoundAnimationVM() {
_system_sound = PropertyWrapperVMUtils.create_selector_vm<SoundNotification, SoundNotification.SystemSound>(
SoundActionTemplateKeys.SystemSound,
RXCollection.from_enumerable(EnumHelper.get_values<SoundNotification.SystemSound>()),
a => a.system_sound.Value, (a, s) => a.system_sound = s);
_system_sound = create_system_sound_vm();
_custom_sound = PropertyWrapperVMUtils.create_selector_vm<SoundNotification, string>(
SoundActionTemplateKeys.CustomSound,
RXCollection.from_enumerable(new string[0]),
@@ -46,6 +43,12 @@ namespace mbts.ui.settings {
}
}
public static IPropertyWrapperVM<SoundNotification> create_system_sound_vm() =>
PropertyWrapperVMUtils.create_selector_vm<SoundNotification, SoundNotification.SystemSound>(
SoundActionTemplateKeys.SystemSound,
RXCollection.from_enumerable(EnumHelper.get_values<SoundNotification.SystemSound>()),
a => a.system_sound.Value, (a, s) => a.system_sound = s);
public void load_from(SoundNotification action) {
selected_sound_type = action.sound_type_case;
selected_sound?.load_from(action);
@@ -21,8 +21,8 @@
<u:WindowStyle.TitleContentTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Margin="3,1" Source="{x:Static u:Icons.ViewSettings}"/>
<TextBlock Text="{Binding owner_title, StringFormat='{}\&apos;{0}\&apos; Grid Settings'}"/>
<Image Margin="3,1" Source="{x:Static u:Icons.Tools}"/>
<TextBlock Text="{Binding owner_title, StringFormat='{}\&apos;{0}\&apos; Window Settings'}"/>
</StackPanel>
</DataTemplate>
</u:WindowStyle.TitleContentTemplate>
@@ -133,35 +133,32 @@ namespace mbts.spark {
}
public class PredicateRowAnimationVM : DisposableViewModelBase, IValueFactory<(TPredicateBuilder predicate, IEnumerable<RowAnimation> animations, IEnumerable<SoundNotification> sounds)> {
readonly Property<bool> _show_animations, _show_sounds;
readonly Property<bool> _show_animations, _play_sound;
public PredicateRowAnimationVM(IPropertyWrapperVM<TPredicateBuilder> predicate) {
this.predicate = predicate;
_show_animations = backing(nameof(show_animations), true);
_show_sounds = backing(nameof(show_sounds), true);
_play_sound = backing(nameof(play_sound), true);
animations = new ObservableEditableCollection<RowAnimationVM>(() => {
var vm = new RowAnimationVM();
vm.selected_animation_type = vm.animation_types.FirstOrDefault();
return vm;
}, true);
sounds = new ObservableEditableCollection<SoundAnimationVM>(() => {
var vm = new SoundAnimationVM();
vm.selected_sound_type = vm.sound_types.FirstOrDefault();
return vm;
}, true);
animations.CollectionChanged += WPFHelper.create_collection_changed_cb(on_items_added: (_, __) => _show_animations.set(true));
_dispose = predicate as IDisposable;
}
public IPropertyWrapperVM<TPredicateBuilder> predicate { get; }
public ObservableEditableCollection<RowAnimationVM> animations { get; }
public ObservableEditableCollection<SoundAnimationVM> sounds { get; }
public IEnumerable<CellAnimation.AnimationTypeOneofCase> animation_types { get; } = EnumHelper.get_values_except(CellAnimation.AnimationTypeOneofCase.None);
public bool show_animations { get => _show_animations.Value; set => _show_animations.set(value); }
public bool show_sounds { get => _show_sounds.Value; set => _show_sounds.set(value); }
public bool play_sound { get => _play_sound.Value; set => _play_sound.set(value); }
public IPropertyWrapperVM<SoundNotification> sound { get; } = SoundAnimationVM.create_system_sound_vm();
public (TPredicateBuilder predicate, IEnumerable<RowAnimation> animations, IEnumerable<SoundNotification> sounds) create() =>
(predicate.create_assigned(), animations.Select(a => a.create_assigned()), sounds.Select(s => s.create_assigned()));
(predicate.create_assigned(),
animations.Select(a => a.create_assigned()),
EnumerableExtensions.return_if(play_sound, () => sound.create_assigned()));
public void load_from((TPredicateBuilder predicate, IEnumerable<RowAnimation> animations, IEnumerable<SoundNotification> sounds) args) {
predicate.load_from(args.predicate);
@@ -170,11 +167,11 @@ namespace mbts.spark {
vm.load_from(a);
return vm;
}));
sounds.SetItems(args.sounds.Select(s => {
var vm = new SoundAnimationVM();
vm.load_from(s);
return vm;
}));
var en = args.sounds.GetEnumerator();
if (en.MoveNext()) {
_play_sound.set(true);
sound.load_from(en.Current);
} else _play_sound.set(false);
}
}
}
@@ -37,7 +37,7 @@
<sys:Double x:Key="ControlShortWidth">60</sys:Double>
<sys:Double x:Key="ControlShortestWidth">30</sys:Double>
<sys:Double x:Key="CollapsedAnimationItemsHeight">24</sys:Double>
<sys:Double x:Key="AnimationExpanderToggleWidth">102</sys:Double>
<sys:Double x:Key="AnimationExpanderToggleWidth">142</sys:Double>
<Thickness x:Key="OutterMarginTL" Left="8" Top="{StaticResource HorizontalPush}" />
<Thickness x:Key="LeftPush" Left="{StaticResource HorizontalPush}"/>
<Thickness x:Key="ExpanderChildMargin" Left="8" Top="{StaticResource VerticalPush}"/>
@@ -133,18 +133,25 @@
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush}}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ComboBox Style="{StaticResource PredicateTypeComboBoxStyle}">
<ComboBox x:Name="PART_Predicates" Style="{StaticResource PredicateTypeComboBoxStyle}">
<ComboBox.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource ComboBox.DelineatedGroupContainerStyle}"/>
</ComboBox.GroupStyle>
</ComboBox>
<ContentControl
x:Name="PART_Content"
Grid.Column="2"
HorizontalAlignment="Stretch"
Content="{Binding selected_predicate}"
ContentTemplateSelector="{DynamicResource PredicateTemplateSelector}"
/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding selected_predicate.key}" Value="None">
<Setter TargetName="PART_Predicates" Property="Grid.ColumnSpan" Value="3"/>
<Setter TargetName="PART_Content" Property="Visibility" Value="Collapsed"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</u:TemplateSelectorKeyValue>
<u:TemplateSelectorKeyValue Key="{x:Static usp:PredicateTemplateKeys.DoubleValue}">
@@ -352,7 +359,7 @@
<GroupBox.Header>
<StackPanel Orientation="Horizontal">
<c:ExpanderToggleButton x:Name="PredicateAnimationsExpanderToggle" IsChecked="{Binding show_predicate_animations}">
Row Animation, Sound, and Notification Triggers
Sound/Notification Triggers
</c:ExpanderToggleButton>
<TextBlock Margin="{StaticResource LeftPush}">
<Hyperlink Command="{Binding predicate_animations.AddItemCommand}">(click to add)</Hyperlink>
@@ -379,8 +386,6 @@
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button
@@ -437,51 +442,67 @@
ItemTemplate="{StaticResource RowAnimationItemTemplate}"
/>
</GroupBox>
<GroupBox
x:Name="SoundsGroupBox"
<Grid
Grid.Row="4"
Grid.Column="1"
HorizontalAlignment="Stretch"
Margin="{StaticResource ExpanderChildMargin}"
>
<GroupBox.Style>
<Style TargetType="GroupBox" BasedOn="{StaticResource {x:Type GroupBox}}">
<Style.Triggers>
<DataTrigger Binding="{Binding show_sounds}" Value="{u:False}">
<Setter Property="Height" Value="{StaticResource CollapsedAnimationItemsHeight}"/>
<Setter Property="BorderThickness" Value="0"/>
</DataTrigger>
</Style.Triggers>
</Style>
</GroupBox.Style>
<GroupBox.Header>
<StackPanel Orientation="Horizontal">
<Grid Width="{StaticResource AnimationExpanderToggleWidth}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<c:ExpanderToggleButton x:Name="SoundsExpanderToggle" IsChecked="{Binding show_sounds}" Visibility="{Binding sounds.Count, Converter={StaticResource IntNotZeroVisibilityConverter}}">
Sounds
</c:ExpanderToggleButton>
<TextBlock FontStyle="Italic" Foreground="Gray" Visibility="{Binding Visibility, ElementName=SoundsExpanderToggle, Converter={StaticResource ReverseVisibilityConverter}}">
No Sounds
</TextBlock>
<Line Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Margin="2" Stroke="Black" X2="{Binding ActualWidth, RelativeSource={RelativeSource Self}}" StrokeDashArray="2 2" StrokeThickness="1"/>
</Grid>
<TextBlock>
<Hyperlink Command="{Binding sounds.AddItemCommand}">(click to add)</Hyperlink>
</TextBlock>
</StackPanel>
</GroupBox.Header>
<ItemsControl
x:Name="Sounds"
Grid.IsSharedSizeScope="True"
ItemsSource="{Binding sounds}"
ItemTemplate="{StaticResource SoundItemTemplate}"
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalGap}}"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSplit}}"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<CheckBox Grid.Column="1" VerticalAlignment="Center" IsChecked="{Binding play_sound}">Play Sound</CheckBox>
<ComboBox
Grid.Column="3"
ItemsSource="{Binding sound.items}"
SelectedItem="{Binding sound.value}"
ItemTemplate="{StaticResource EnumDescriptionTemplate}"
Visibility="{Binding play_sound, Converter={StaticResource BooleanToVisibilityConverter}}"
/>
</GroupBox>
<CheckBox Grid.Row="6" Grid.Column="1" IsEnabled="{Binding predicate.can_enable_toast_notifications}" IsChecked="{Binding predicate.toast_notifications_enabled}">Enable Toast Notifications</CheckBox>
<ComboBox
Grid.Column="3"
Visibility="{Binding play_sound, Converter={StaticResource FalseVisibilityConverter}}"
Style="{StaticResource DisabledPlaceholderComboBox}"
/>
<Button
Grid.Column="4"
Margin="2,0,0,0"
Command="{x:Static c:SoundAnimationView.PreviewSoundCommand}"
CommandParameter="{Binding sound.value}"
Visibility="{Binding play_sound, Converter={StaticResource BooleanToVisibilityConverter}}"
Style="{StaticResource HelpButtonBaseStyle}"
ToolTip="{Binding sound.value, Converter={x:Static c:SoundAnimationView.LicenseInfoTextConverter}}"
>
<Button.CommandBindings>
<CommandBinding
Command="{x:Static u:ApplicationCommandsEx.CopyToClipboardCommand}"
Executed="{x:Static u:ApplicationCommandsEx.CopyToClipboardExecutedHandler}"
/>
<CommandBinding
Command="{x:Static u:ApplicationCommandsEx.OpenUriCommand}"
CanExecute="{x:Static u:ApplicationCommandsEx.OpenUriCanExecuteHandler}"
Executed="{x:Static u:ApplicationCommandsEx.OpenUriExecutedHandler}"
/>
</Button.CommandBindings>
<Button.InputBindings>
<MouseBinding Command="{x:Static u:ApplicationCommandsEx.CopyToClipboardCommand}" CommandParameter="{Binding sound.value, Converter={x:Static c:SoundAnimationView.LicenseInfoClipboardTextConverter}}">
<MouseBinding.Gesture>
<MouseGesture MouseAction="LeftClick" Modifiers="Ctrl"/>
</MouseBinding.Gesture>
</MouseBinding>
</Button.InputBindings>
</Button>
<CheckBox Grid.Row="2" Grid.Column="1" IsEnabled="{Binding predicate.can_enable_toast_notifications}" IsChecked="{Binding predicate.toast_notifications_enabled}">
Show Notification
</CheckBox>
</Grid>
</Grid>
</Border>
<DataTemplate.Triggers>
@@ -492,10 +513,6 @@
<Setter TargetName="AnimationsGroupBox" Property="Padding" Value="0"/>
<Setter TargetName="AnimationsGroupBox" Property="BorderThickness" Value="0"/>
</DataTrigger>
<DataTrigger Binding="{Binding sounds.Count}" Value="0">
<Setter TargetName="SoundsGroupBox" Property="Padding" Value="0"/>
<Setter TargetName="SoundsGroupBox" Property="BorderThickness" Value="0"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
@@ -1,8 +1,11 @@
<ResourceDictionary 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:usp="clr-namespace:mbts.ui.spark"
xmlns:uag="clr-namespace:mbts.ui.spark.algo">
<ResourceDictionary
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:usp="clr-namespace:mbts.ui.spark"
xmlns:uag="clr-namespace:mbts.ui.spark.algo"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/view/Resources/Converters.xaml"/>
<ResourceDictionary Source="/view/Resources/ComboBoxes.xaml"/>
@@ -13,6 +16,8 @@
<ResourceDictionary Source="/view/Controls/Order/QuantityMeasureControl.xaml"/>
<ResourceDictionary Source="/Modules/Spreader/ExecutionStrategyEditor.xaml"/>
</ResourceDictionary.MergedDictionaries>
<sys:Double x:Key="HorizontalPush">4</sys:Double>
<sys:Double x:Key="VerticalPush">4</sys:Double>
<Style TargetType="uag:OrderDetailsPopupControl">
<Setter Property="Background" Value="{StaticResource ComboBox.Static.Background}"/>
<Setter Property="BorderBrush" Value="{StaticResource ComboBox.Static.Border}"/>
@@ -55,6 +60,11 @@
IsOpen="{Binding IsOpen, RelativeSource={RelativeSource TemplatedParent}}"
Visibility="{Binding HasEditableProperties, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource BoolToVisibility}}"
>
<c:PopupControl.Resources>
<Style TargetType="GroupBox">
<Setter Property="Padding" Value="4"/>
</Style>
</c:PopupControl.Resources>
<c:PopupControl.PopupContainerStyle>
<Style TargetType="Border" BasedOn="{StaticResource PopupContainerStyleBase}">
<Setter Property="Padding" Value="4"/>
@@ -261,8 +271,8 @@
<TextBlock Grid.Row="1" VerticalAlignment="Center">Join Thresh</TextBlock>
<uag:QuantityMeasureControl Grid.Row="1" Grid.Column="2" QuantityMeasure="{Binding join_threshold}"/>
<CheckBox Grid.Row="3" Grid.Column="2" VerticalAlignment="Center" Margin="0,0,0,0" IsChecked="{Binding enable_hedge}">Enable Hedge</CheckBox>
<TextBlock Grid.Row="5" VerticalAlignment="Center" IsEnabled="{Binding enable_hedge}" >Hedge Ticks</TextBlock>
<c:TickUpDownInt Grid.Row="5" Grid.Column="2" IsEnabled="{Binding enable_hedge}" Value="{Binding hedge_ticks}"/>
<TextBlock Grid.Row="5" VerticalAlignment="Center">Hedge Ticks</TextBlock>
<c:TickUpDownInt Grid.Row="5" Grid.Column="2" Value="{Binding hedge_ticks}"/>
<TextBlock Grid.Row="7">Hedge</TextBlock>
<uag:OrderDetailsPopupControl
Grid.Row="7" Grid.Column="2"
@@ -336,7 +346,7 @@
</Grid>
</DataTemplate>
</usp:OrderModificationTemplateSelector.TopOrderTemplate>
<usp:OrderModificationTemplateSelector.TriggerOrderTemplate>
<usp:OrderModificationTemplateSelector.CoverOrderTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
@@ -346,7 +356,7 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="4" />
<RowDefinition Height="Auto"/>
<RowDefinition Height="4" />
<RowDefinition Height="4" />
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
@@ -354,15 +364,16 @@
<ColumnDefinition Width="12"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" VerticalAlignment="Center">Trigger Price Type</TextBlock>
<ComboBox
Grid.Row="1" Grid.Column="2"
ItemsSource="{Binding trigger_price_types}"
ItemTemplate="{StaticResource EnumDescriptionTemplate}"
SelectedItem="{Binding trigger_price_type}"
/>
<TextBlock Grid.Row="3" VerticalAlignment="Center">Order Price</TextBlock>
<usp:PriceEntryControl Grid.Row="3" Grid.Column="2" Value="{Binding order_price}" ContractSpec="{Binding spec}" />
<TextBlock Grid.Row="1" VerticalAlignment="Center" IsEnabled="{Binding enable_hedge}" >Hedge Ticks</TextBlock>
<c:TickUpDownInt Grid.Row="1" Grid.Column="2" IsEnabled="{Binding enable_hedge}" Value="{Binding hedge_ticks}"/>
<TextBlock Grid.Row="3">Hedge</TextBlock>
<uag:OrderDetailsPopupControl
Grid.Row="3" Grid.Column="2"
IsOpen="{Binding hedge_order.editable_properties_open, FallbackValue=False}"
ItemsSource="{Binding hedge_order_types}"
SelectedItem="{Binding hedge_order}"
HasEditableProperties="{Binding hedge_order.has_editable_properties, FallbackValue=False}"
/>
<TextBlock Grid.Row="5">Child</TextBlock>
<uag:OrderDetailsPopupControl
Grid.Row="5" Grid.Column="2"
@@ -373,6 +384,146 @@
/>
</Grid>
</DataTemplate>
</usp:OrderModificationTemplateSelector.CoverOrderTemplate>
<usp:OrderModificationTemplateSelector.TriggerOrderTemplate>
<DataTemplate>
<Grid Grid.IsSharedSizeScope="True">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition/>
</Grid.RowDefinitions>
<GroupBox Header="Trigger Condition" HeaderTemplate="{StaticResource BoldHeaderTemplate}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="c0"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush}}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" VerticalAlignment="Center">Price Type</TextBlock>
<ComboBox
Grid.Row="1"
Grid.Column="2"
ItemsSource="{Binding trigger_price_types}"
ItemTemplate="{StaticResource EnumDescriptionTemplate}"
SelectedItem="{Binding trigger_price_type}"
/>
</Grid>
</GroupBox>
<GroupBox Grid.Row="2" Header="Trigger Action" HeaderTemplate="{StaticResource BoldHeaderTemplate}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="c0"/>
<ColumnDefinition MaxWidth="{Binding Source={StaticResource HorizontalPush}}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0">
Child
</TextBlock>
<uag:OrderDetailsPopupControl
Grid.Row="0"
Grid.Column="2"
IsOpen="{Binding child_order.editable_properties_open, FallbackValue=False}"
ItemsSource="{Binding child_order_types}"
SelectedItem="{Binding child_order}"
HasEditableProperties="{Binding child_order.has_editable_properties, FallbackValue=False}"
/>
<GroupBox Grid.Row="2" Grid.ColumnSpan="3" Header="Price" HeaderTemplate="{StaticResource SemiBoldHeaderTemplate}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush}}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<RadioButton
x:Name="fixed_price_rb"
Grid.Row="0"
GroupName="price-type"
IsChecked="{Binding use_fixed_price, Mode=TwoWay}"
VerticalContentAlignment="Center"
>
Fixed
</RadioButton>
<usp:PriceEntryControl
Grid.Row="0"
Grid.Column="2"
ContractSpec="{Binding spec}"
IsEnabled="{Binding IsChecked, ElementName=fixed_price_rb, Mode=OneWay}"
Value="{Binding fixed_price}"
/>
<RadioButton
x:Name="payup_price_rb"
Grid.Row="2"
GroupName="price-type"
VerticalContentAlignment="Center"
IsChecked="{Binding use_fixed_price, Converter={StaticResource NotConverter}, Mode=TwoWay}"
>
Payup/less
</RadioButton>
<Grid Grid.Row="2" Grid.Column="2">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<c:TickUpDownInt
IsEnabled="{Binding IsChecked, ElementName=payup_price_rb, Mode=OneWay}"
Value="{Binding payup_ticks}"
Width="34"
/>
<ComboBox
Grid.Column="2"
IsEnabled="{Binding use_fixed_price, Converter={StaticResource NotConverter}, Mode=OneWay}"
ItemsSource="{Binding payup_price_types}"
SelectedItem="{Binding payup_price_type}"
>
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={x:Static uag:OrderDetailsPopupControl.TriggerPayupTypeDescriptionConverter}}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Grid>
</GroupBox>
</Grid>
</GroupBox>
<GroupBox Grid.Row="4" Header="Trigger Exit" HeaderTemplate="{StaticResource BoldHeaderTemplate}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="c0"/>
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalPush}}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalPush}}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<CheckBox IsChecked="{Binding is_timeout_checked}" VerticalContentAlignment="Center">
Timeout (secs)
</CheckBox>
<c:TickUpDownInt Grid.Column="2" IsEnabled="{Binding is_timeout_checked, Mode=OneWay}" Minimum="0" Value="{Binding timeout_secs}"/>
<CheckBox Grid.Row="2" Grid.ColumnSpan="3" IsChecked="{Binding is_priceout_checked}" VerticalAlignment="Center">
Price Conditional
</CheckBox>
</Grid>
</GroupBox>
</Grid>
</DataTemplate>
</usp:OrderModificationTemplateSelector.TriggerOrderTemplate>
<usp:OrderModificationTemplateSelector.IcebergOrderTemplate>
<DataTemplate>
@@ -425,6 +576,48 @@
</Grid>
</DataTemplate>
</usp:OrderModificationTemplateSelector.SpreaderTemplate>
<usp:OrderModificationTemplateSelector.DynamicOrderTemplate>
<DataTemplate>
<Grid Grid.IsSharedSizeScope="True" >
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="4" />
<RowDefinition Height="Auto"/>
<RowDefinition Height="4" />
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="c0"/>
<ColumnDefinition Width="12"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ItemsControl Grid.Row = "1" ItemsSource="{Binding parameters}" Grid.ColumnSpan="3">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="c0"/>
<ColumnDefinition Width="12"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding name}"/>
<TextBox HorizontalAlignment="Stretch" Grid.Column="2" Text="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<TextBlock Grid.Row="3">Child</TextBlock>
<uag:OrderDetailsPopupControl
Grid.Row="3" Grid.Column="2"
IsOpen="{Binding child_order.editable_properties_open, FallbackValue=False}"
ItemsSource="{Binding child_order_types}"
SelectedItem="{Binding child_order}"
HasEditableProperties="{Binding child_order.has_editable_properties, FallbackValue=False}"
/>
</Grid>
</DataTemplate>
</usp:OrderModificationTemplateSelector.DynamicOrderTemplate>
</usp:OrderModificationTemplateSelector>
</c:PopupControl.ContentTemplateSelector>
</c:PopupControl>
@@ -1,4 +1,7 @@
using mbts.spark;
using bts.api.orderman;
using mbts.spark;
using mbts.ui.converters;
using mbts.ui.utilities;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
@@ -6,16 +9,23 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
namespace mbts.ui.spark.algo
{
namespace mbts.ui.spark.algo {
/// <summary>
/// Interaction logic for OrderDetailsPopupControl.xaml
/// </summary>
class OrderDetailsPopupControl : Control
{
class OrderDetailsPopupControl : Control {
static OrderDetailsPopupControl() =>
DefaultStyleKeyProperty.OverrideMetadata(typeof(OrderDetailsPopupControl), new FrameworkPropertyMetadata(typeof(OrderDetailsPopupControl)));
public static IValueConverter TriggerPayupTypeDescriptionConverter =
ValueConverter.create<TriggerPayupPrice.Types.TriggerPayupPriceType, string>(
t => {
switch (t) {
case TriggerPayupPrice.Types.TriggerPayupPriceType.LastTradePrice: return "Last Trade";
default: return DisplayNameHelper.camel_to_title_case(t.ToString());
}
});
#region ExpandDirection
public static readonly DependencyProperty ExpandDirectionProperty = DependencyProperty.Register(nameof(ExpandDirection), typeof(ExpandDirection), typeof(OrderDetailsPopupControl),
new PropertyMetadata(ExpandDirection.Right, OnExpandDirectionChanged, CoerceExpandDirection));
@@ -1,4 +1,5 @@
using System;
using mbts.spark.utilities;
using System;
using System.Windows;
using System.Windows.Controls;
@@ -10,10 +11,42 @@ namespace mbts.ui.controls
DefaultStyleKeyProperty.OverrideMetadata(typeof(TickUpDownInt), new FrameworkPropertyMetadata(typeof(TickUpDownInt)));
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(int), typeof(TickUpDownInt), new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
public static readonly DependencyProperty MinimumProperty =
WPFHelper.create_dp<int, TickUpDownInt>(
nameof(Minimum),
(o, v) => o.CoerceValue(ValueProperty),
int.MinValue);
public int Minimum {
get => (int)GetValue(MinimumProperty);
set => SetValue(MinimumProperty, value);
}
public static readonly DependencyProperty MaximumProperty =
WPFHelper.create_dp<int, TickUpDownInt>(
nameof(Maximum),
(o, v) => o.CoerceValue(ValueProperty),
int.MaxValue);
public int Maximum {
get => (int)GetValue(MaximumProperty);
set => SetValue(MaximumProperty, value);
}
public static readonly DependencyProperty ValueProperty =
WPFHelper.create_dp<int, TickUpDownInt>(
nameof(Value),
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
(o, v) => MathUtils.within_range(o.Minimum, o.Maximum, v),
0);
public int Value {
get => (int)GetValue(ValueProperty);
set => SetValue(ValueProperty, value);
}
public static readonly DependencyProperty IncrementProperty = DependencyProperty.Register("Increment", typeof(int), typeof(TickUpDownInt), new FrameworkPropertyMetadata(1));
public int Value { get { return (int)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } }
public int Increment { get { return (int)GetValue(IncrementProperty); } set { SetValue(IncrementProperty, value); } }
public override void OnApplyTemplate() {
@@ -66,7 +66,7 @@
</ControlTemplate.Triggers>
</ControlTemplate>
<Style x:Key="TextPromptStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Text.Prompt.Foreground.Brush}"/>
<Setter Property="Foreground" Value="{x:Static text_prompt_foreground_brush, MemberType={u:Nested u:BTSColors.UI}}"/>
<Setter Property="Margin" Value="4,0,0,0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="IsHitTestVisible" Value="False"/>
@@ -13,7 +13,7 @@
<cv:KeyValue Key="{x:Null}" Value="{u:Visibility Visible}"/>
</cv:ValueMap>
<Style x:Key="TextPromptStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource Text.Prompt.Foreground.Brush}"/>
<Setter Property="Foreground" Value="{x:Static text_prompt_foreground_brush, MemberType={u:Nested u:BTSColors.UI}}"/>
<Setter Property="Margin" Value="4,0,0,0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="IsHitTestVisible" Value="False"/>
@@ -1,9 +1,7 @@
using System;
namespace mbts.ui.converters
{
public class EnumerableDoubleStringConverter : EnumerableStringConverter<double>
{
namespace mbts.ui.converters {
class EnumerableDoubleStringConverter : EnumerableStringConverter<double> {
protected override double convert_item_back(string item_str) {
double result;
if (Double.TryParse(item_str, out result))
@@ -1,26 +1,22 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Data;
namespace mbts.ui.converters
{
public abstract class EnumerableStringConverter<T> : IValueConverter
{
protected EnumerableStringConverter() {
namespace mbts.ui.converters {
abstract class EnumerableStringConverter<T> : IValueConverter {
protected EnumerableStringConverter() =>
Separator = " ";
}
public string Separator { get; set; }
protected virtual string convert_item(T item) { return item.ToString(); }
protected virtual T convert_item_back(string item_str) { throw new NotImplementedException(); }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if (value is IEnumerable<T>)
return ((IEnumerable<T>)value).Select(convert_item).list_string(Separator);
else
throw new ArgumentException("Expected 'Convert' input value to be {0}".fmt(typeof(IEnumerable<T>)));
if (value is IEnumerable<T> vals) {
return _format(vals);
} else if (value is IEnumerable ng_vals) {
return _format(ng_vals.convert<T>());
} else return value?.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
@@ -33,9 +29,13 @@ namespace mbts.ui.converters
} else
throw new ArgumentException("Expected 'ConvertBack' input value to be {0}".fmt(typeof(string)));
}
protected virtual string convert_item(T item) { return item.ToString(); }
protected virtual T convert_item_back(string item_str) { throw new NotImplementedException(); }
string _format(IEnumerable<T> vals) =>
string.Join(Separator, vals.Select(convert_item));
}
public class EnumerableStringConverter : EnumerableStringConverter<object>
{
}
class EnumerableStringConverter : EnumerableStringConverter<object> { }
}
@@ -68,6 +68,9 @@ namespace mbts.ui {
return Color.FromRgb(bytes[2], bytes[1], bytes[0]);
}
public static SolidColorBrush to_brush(this BTSColor color) =>
new SolidColorBrush(color);
public static Brush rgb_brush(this uint color) {
var brush = new SolidColorBrush(rgb_color(color));
brush.Freeze();
+18 -13
View File
@@ -1,4 +1,4 @@
<ResourceDictionary
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mbts="clr-namespace:mbts.ui"
@@ -59,7 +59,7 @@
<Border Name="border"
Background="{TemplateBinding Background}"
BorderThickness="0"
HorizontalAlignment="Stretch"
HorizontalAlignment="Stretch"
Padding="5">
<ContentPresenter />
</Border>
@@ -70,7 +70,7 @@
</Trigger>
<Trigger Property="IsPressed" Value="true">
<Setter TargetName="border" Property="Background" Value="{mbts:BTSColor UI.Button.pressed_background}" />
<Setter TargetName="border" Property="BorderBrush" Value="{mbts:BTSColor UI.Button.pressed_background}" />
<Setter TargetName="border" Property="BorderBrush" Value="{mbts:BTSColor UI.Button.pressed_background}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
@@ -89,7 +89,7 @@
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="controls:SparkMenuItem">
<Border Name="launcher_button_border"
BorderThickness="0"
MinWidth="150"
@@ -108,7 +108,7 @@
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Canvas>
<Polygon
<Polygon
Name="menu_item_animated_arrow"
Points="0,0 290,0 300,22.5 290,45 0,45 10,22.5"
Margin="-300 0 0 0"
@@ -116,7 +116,7 @@
Fill="{DynamicResource StartMenuMouseOverBackground}"
/>
</Canvas>
<Polygon
<Polygon
Name="menu_item_arrow"
Grid.Column="0"
Points="0,0 10,22.5 0,45"
@@ -396,6 +396,11 @@
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid Width="{TemplateBinding Width}" Height="{TemplateBinding Height}">
<Grid.ToolTip>
<ToolTip MaxWidth="300">
<TextBlock Text="{TemplateBinding ToolTip}" TextWrapping="Wrap" />
</ToolTip>
</Grid.ToolTip>
<Ellipse HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Fill="{TemplateBinding Background}" Opacity="0" x:Name="_el" />
<TextBlock Text="?" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>
@@ -472,16 +477,16 @@
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border
<Border
x:Name="Border"
CornerRadius="0"
CornerRadius="0"
BorderThickness="1"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
Padding="{TemplateBinding Padding}"
Height="Auto"
SnapsToDevicePixels="True">
<ContentPresenter
<ContentPresenter
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="Center"
RecognizesAccessKey="True"
@@ -608,11 +613,11 @@
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Border x:Name="background"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
<Border x:Name="background"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="8"
Background="{TemplateBinding Background}"
Background="{TemplateBinding Background}"
Width="54" Height="18">
<Canvas>
<Ellipse x:Name="lever" VerticalAlignment="Center" Width="9" Height="9" Fill="Black" Canvas.Top="3" Canvas.Left="3" />
@@ -63,8 +63,8 @@
<cv:ValueMap x:Key="IsEnabledOpacityConverter" Default="{u:Double 1}">
<cv:KeyValue Key="{u:False}" Value="{u:Double 0.56}" />
</cv:ValueMap>
<cv:ValueMap x:Key="IsEnabledForegroundConverter" Default="{u:Brush Black}">
<cv:KeyValue Key="{u:False}" Value="{u:Brush Gray}"/>
<cv:ValueMap x:Key="IsEnabledForegroundConverter" Default="{x:Static Brushes.Black}">
<cv:KeyValue Key="{u:False}" Value="{x:Static input_disabled_text_brush, MemberType={u:Nested u:BTSColors.UI}}"/>
</cv:ValueMap>
<uspcv:TickDisplayConverter x:Key="TickDisplayConverter"/>
<cv:ImageSourceIconConverter x:Key="IconConverter"/>
@@ -167,9 +167,9 @@ namespace mbts.spark {
}
public static string order_sub_type_display_name(OrderSubType sub_type, bool use_long_name) {
switch(sub_type) {
switch (sub_type) {
case OrderSubType.HedgingLeg:
return use_long_name ? "Hedging (H)": "H";
return use_long_name ? "Hedging (H)" : "H";
case OrderSubType.QuotingLeg:
return use_long_name ? "Quoting (Q)" : "Q";
case OrderSubType.None:
@@ -178,5 +178,6 @@ namespace mbts.spark {
return string.Empty;
}
}
}
}
+5 -17
View File
@@ -1,5 +1,6 @@
using bts.api;
using bts.api.core;
using bts.api.position;
using mbts.collections.extensions;
using mbts.ui;
using mbts.utils;
@@ -74,6 +75,10 @@ namespace mbts.spark {
return (smd, smd.security.Id == security_key);
}
public static double sod_pos(this PositionUnitImmutable position_unit) => position_unit.SodLongPos - position_unit.SodShortPos;
public static double day_pos(this PositionUnitImmutable position_unit) => position_unit.DayLongPos - position_unit.DayShortPos;
public static double total_pos(this PositionUnitImmutable position_unit) => position_unit.sod_pos() + position_unit.day_pos();
public static void lazy_assert(bool test, Func<string> get_msg) {
if (!test)
Logger.assert(false, get_msg());
@@ -94,23 +99,6 @@ namespace mbts.spark {
public static bool try_get<T, TKey>(this TableUpdate<T, TKey> table, TKey key, out T result) where TKey : IEquatable<TKey> =>
table.state.TryGetValue(key, out result);
public static void detect_changed_keys<T, TKey>(this TableUpdate<T, TKey> table, Func<T, TKey> key_selector, out HashSet<TKey> removed_keys, out HashSet<TKey> added_keys, out HashSet<TKey> changed_keys)
where TKey : IEquatable<TKey> {
removed_keys = new HashSet<TKey>(table.removed.Select(key_selector));
added_keys = new HashSet<TKey>(table.added.Select(key_selector));
changed_keys = new HashSet<TKey>(removed_keys.Intersect(added_keys));
removed_keys.ExceptWith(changed_keys);
added_keys.ExceptWith(changed_keys);
}
public static void detect_changed_keys<T, TKey>(this ITableUpdateTransform<T, TKey> table, Func<T, TKey> key_selector, out HashSet<TKey> removed_keys, out HashSet<TKey> added_keys, out HashSet<TKey> changed_keys)
where TKey : IEquatable<TKey> {
removed_keys = new HashSet<TKey>(table.removed.Select(key_selector));
added_keys = new HashSet<TKey>(table.added.Select(key_selector));
changed_keys = new HashSet<TKey>(removed_keys.Intersect(added_keys));
removed_keys.ExceptWith(changed_keys);
added_keys.ExceptWith(changed_keys);
}
#endregion
public static class UI {
@@ -30,6 +30,7 @@ namespace mbts.spark {
_ask_mkt_break_vis = new DrawingVisual(),
_session_low_vis = new DrawingVisual(),
_session_high_vis = new DrawingVisual(),
_session_range_vis = new DrawingVisual(),
_gridvis = new DrawingVisual();
readonly VisualGlyphTuple
_bid_vis_tup = new VisualGlyphTuple(),
@@ -280,6 +281,7 @@ namespace mbts.spark {
foreach (var col in columns)
if (col.settings.show && col.visual_tup != null)
col.visual_tup.visual.Offset = new Vector(col.x_left, 0);
_session_range_vis.Offset = _price_column.visual_tup.visual.Offset;
}
void _adjust_column_width(Column column, double adjustment) {
@@ -315,8 +317,10 @@ namespace mbts.spark {
case ColumnType.Ask: render_market_col(_asks); break;
}
if (Array.IndexOf(columns, column) <= Array.IndexOf(columns, _price_column)) {
_render_session_line(_session_low_vis, _mkt_break_lines.session_low, _settings.session_low_line.color);
_render_session_line(_session_high_vis, _mkt_break_lines.session_high, _settings.session_high_line.color);
if (_mkt_break_lines.low_render_index.HasValue)
_render_session_line(_session_low_vis, _mkt_break_lines.low_render_index.Value, _settings.session_low_line.color);
if (_mkt_break_lines.high_render_index.HasValue)
_render_session_line(_session_high_vis, _mkt_break_lines.high_render_index.Value, _settings.session_high_line.color);
}
void render_market_col(NativePriceSize[] depth) {
var mid = LadderRender.index_of(_price_list, _last_origin_price, _price_comparer);
@@ -376,111 +380,175 @@ namespace mbts.spark {
}
}
static readonly TimeSpan _price_out_of_range_render_interval = TimeSpan.FromSeconds(5);
DateTime _last_price_range_calc_time = DateTime.MinValue;
#region Timer.Tick, Refresh Methods
void _tick() {
if (_settings != null) {
ulong unused = 0;
_vm.md.get_last_trade(ref unused, out NativePriceSize last, out DateTime _, out ulong __);
bool last_trade_changed = _vm.md.get_last_trade(ref unused, out _last_trade, out DateTime _, out ulong __);
bool depth_changed = _vm.md.get_depth(ref _prices_updated, ref _bids, ref _asks);
//
_mkt_break_lines.refresh();
bool update_prices =
bool prices_changed =
_price_dirty ||
(double.IsNaN(_last_origin_price) && !double.IsNaN(_mkt_break_lines.origin)) ||
_mkt_break_lines.origin >= _price_list[0] || _mkt_break_lines.origin <= _price_list[_price_list.Length - 1];
if (!update_prices && _prices_out_of_range(out double low, out double high)) {
// The market can be wider than the 1001 rows (ticks) we [initially] allot.
// Rendering prices is expensive, and will lock up the ui if done continuously.
// Therefore, ensure a minimum time interval has elapsed before rendering prices again.
var now = DateTime.Now;
if ((now - _last_price_range_calc_time) > _price_out_of_range_render_interval) {
SparkUtils.lazy_warn(!double.IsNaN(_mkt_break_lines.origin) && _mkt_break_lines.origin >= low && _mkt_break_lines.origin <= high,
() => fmt_log_msg($"market break ({_mkt_break_lines.origin}) is unacceptable for the market range ({low} - {high})"));
int prev_row_count = _row_count;
int n_ticks_to_low = TickUtils.normalized_tick_diff(security.ContractSpec, _mkt_break_lines.origin, low);
int n_ticks_to_high = TickUtils.normalized_tick_diff(security.ContractSpec, high, _mkt_break_lines.origin);
int desired_row_count = Math.Max(n_ticks_to_low, n_ticks_to_high) * 2 + 1;
_row_count = Math.Min(_max_row_count, desired_row_count);
if (_row_count != prev_row_count) {
if (desired_row_count > _max_row_count)
Logger.warn(bts.log.Subsystem.Ui, fmt_log_msg($"ticks between market range ({low} - {high}) exceeds the maximum number of rows allowed ({_max_row_count})"));
else
Logger.info(bts.log.Subsystem.Ui, fmt_log_msg($"increase row count to {_row_count} to accomodate market range ({low} - {high})"));
update_prices = true;
_reset_height();
} else {
update_prices = _mkt_break_lines.origin != _last_origin_price;
}
_last_price_range_calc_time = now;
//
string fmt_log_msg(string msg) =>
$"Ladder {security} (id:{security.Id}, low/high tick:{security.ContractSpec.LowTick}/{security.ContractSpec.HighTick}): {msg}.";
if (!prices_changed && _prices_out_of_range(out double low, out double high)) {
prices_changed = _refresh_price_range(low, high);
}
if (prices_changed) {
_refresh_prices();
_refresh_bid_mkt_break();
_refresh_ask_mkt_break();
_refresh_mid_mkt_break();
_refresh_session_low_line();
_refresh_session_high_line();
_refresh_session_range();
_refresh_last_trade();
_refresh_depth();
_refresh_sizes();
} else {
if (_mkt_break_lines.bid_dirty)
_refresh_bid_mkt_break();
if (_mkt_break_lines.ask_dirty)
_refresh_ask_mkt_break();
if (_mkt_break_lines.mid_dirty)
_refresh_mid_mkt_break();
if (_mkt_break_lines.session_low_dirty)
_refresh_session_low_line();
if (_mkt_break_lines.session_high_dirty)
_refresh_session_high_line();
if (_mkt_break_lines.session_range_dirty)
_refresh_session_range();
if (last_trade_changed) {
var last_index = LadderRender.index_of(_price_list, _last_trade.price, _price_comparer);
if (last_index > 0)
LadderRender.render_last(_last_vis_tup.visual, _last_vis_tup.glyph_context, _last_trade, last_index, _settings.row_height, _settings.last_column);
}
}
if (update_prices) {
var prev_price_list = _price_list;
_price_list = LadderRender.render_prices(_price_vis_tup.visual, _price_vis_tup.glyph_context, _mkt_break_lines.origin, _row_count, _settings.row_height, _settings.price_column, security.ContractSpec);
_ordershost.update_settings(_price_list, _price_comparer, _settings.row_height, _settings.orders_column);
if (prev_price_list != null) {
// maintain previous visible price range if possible
double percent_scroll_offset = _scrollViewer.VerticalOffset / _scrollViewer.ScrollableHeight;
int prev_target_index = (int)(percent_scroll_offset * prev_price_list.Length);
if (prev_price_list.try_get_at_index(prev_target_index, out double prev_target_price)) {
int new_target_index = LadderRender.index_of(_price_list, prev_target_price, _price_comparer);
if (_price_list.within_range(new_target_index)) {
// force _scrollViewer to re-calculate ScrollableHeight
_scrollViewer.UpdateLayout();
double new_vertical_offset = ((double)new_target_index / _price_list.Length) * _scrollViewer.ScrollableHeight;
_scrollViewer.ScrollToVerticalOffset(new_vertical_offset);
}
}
if (depth_changed) {
Logger.assert_d(_price_list != null);
int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer);
LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security.ContractSpec, _settings.bid_column);
LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security.ContractSpec, _settings.ask_column);
}
}
// render market breaks
if (update_prices || _mkt_break_lines.bid_dirty)
render_mkt_break(_bid_mkt_break_vis, _mkt_break_lines.bid, _settings.bid_break_line.color);
if (update_prices || _mkt_break_lines.ask_dirty)
render_mkt_break(_ask_mkt_break_vis, _mkt_break_lines.ask, _settings.ask_break_line.color);
if (update_prices || _mkt_break_lines.mid_dirty)
render_mkt_break(_mid_mkt_break_vis, _mkt_break_lines.mid, _settings.mid_break_line.color);
if (update_prices || _mkt_break_lines.session_low_dirty) {
if (_settings.session_low_line.show)
_render_session_line(_session_low_vis, _mkt_break_lines.session_low, _settings.session_low_line.color);
}
if (update_prices || _mkt_break_lines.session_high_dirty) {
if (_settings.session_high_line.show)
_render_session_line(_session_high_vis, _mkt_break_lines.session_high, _settings.session_high_line.color);
}
//
if (update_prices || _last_trade != last) {
_last_trade = last;
var last_index = LadderRender.index_of(_price_list, last.price, _price_comparer);
if (last_index > 0) {
LadderRender.render_last(_last_vis_tup.visual, _last_vis_tup.glyph_context, last, last_index, _settings.row_height, _settings.last_column);
}
}
if (update_prices || depth_changed) {
Logger.assert_d(_price_list != null);
int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer);
LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security.ContractSpec, _settings.bid_column);
LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security.ContractSpec, _settings.ask_column);
}
_last_origin_price = _mkt_break_lines.origin;
_price_dirty = false;
//
void render_mkt_break(DrawingVisual vis, double price, uint color) =>
LadderRender.render_mkt_break(vis, _row_for_price(price), _settings.row_height, color);
}
}
void _refresh_session_range() {
if (_mkt_break_lines.low_render_index.HasValue && _mkt_break_lines.high_render_index.HasValue)
LadderRender.render_session_range(_session_range_vis, _settings.session_range_fill.color, _price_column.settings, _mkt_break_lines.low_render_index.Value, _mkt_break_lines.high_render_index.Value, _price_list, _settings.row_height);
}
void _refresh_bid_mkt_break() =>
_render_mkt_break(_bid_mkt_break_vis, _mkt_break_lines.bid, _settings.bid_break_line.color);
void _refresh_ask_mkt_break() =>
_render_mkt_break(_ask_mkt_break_vis, _mkt_break_lines.ask, _settings.ask_break_line.color);
void _refresh_mid_mkt_break() =>
_render_mkt_break(_mid_mkt_break_vis, _mkt_break_lines.mid, _settings.mid_break_line.color);
void _refresh_session_low_line() {
if (_settings.session_low_line.show && _mkt_break_lines.low_render_index.HasValue)
_render_session_line(_session_low_vis, _mkt_break_lines.low_render_index.Value, _settings.session_low_line.color);
}
void _refresh_session_high_line() {
if (_settings.session_high_line.show && _mkt_break_lines.high_render_index.HasValue)
_render_session_line(_session_high_vis, _mkt_break_lines.high_render_index.Value, _settings.session_high_line.color);
}
void _refresh_last_trade() {
var last_index = LadderRender.index_of(_price_list, _last_trade.price, _price_comparer);
if (last_index > 0)
LadderRender.render_last(_last_vis_tup.visual, _last_vis_tup.glyph_context, _last_trade, last_index, _settings.row_height, _settings.last_column);
}
void _refresh_sizes() {
Logger.assert_d(_price_list != null);
int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer);
LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security.ContractSpec, _settings.bid_column);
LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security.ContractSpec, _settings.ask_column);
}
void _refresh_depth() {
Logger.assert_d(_price_list != null);
int origin_index = LadderRender.index_of(_price_list, _mkt_break_lines.origin, _price_comparer);
LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security.ContractSpec, _settings.bid_column);
LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security.ContractSpec, _settings.ask_column);
}
static readonly TimeSpan _price_out_of_range_render_interval = TimeSpan.FromSeconds(5);
DateTime _last_price_range_calc_time = DateTime.MinValue;
void _refresh_prices() {
var prev_price_list = _price_list;
_price_list = LadderRender.render_prices(_price_vis_tup.visual, _price_vis_tup.glyph_context, _mkt_break_lines.origin, _row_count, _settings.row_height, _settings.price_column, security.ContractSpec);
_ordershost.update_settings(_price_list, _price_comparer, _settings.row_height, _settings.orders_column);
if (prev_price_list != null) {
// maintain previous visible price range if possible
double percent_scroll_offset = _scrollViewer.VerticalOffset / _scrollViewer.ScrollableHeight;
int prev_target_index = (int)(percent_scroll_offset * prev_price_list.Length);
if (prev_price_list.try_get_at_index(prev_target_index, out double prev_target_price)) {
int new_target_index = LadderRender.index_of(_price_list, prev_target_price, _price_comparer);
if (_price_list.within_range(new_target_index)) {
// force _scrollViewer to re-calculate ScrollableHeight
_scrollViewer.UpdateLayout();
double new_vertical_offset = ((double)new_target_index / _price_list.Length) * _scrollViewer.ScrollableHeight;
_scrollViewer.ScrollToVerticalOffset(new_vertical_offset);
}
}
}
}
bool _refresh_price_range(double low, double high) {
bool prices_changed = false;
// The market can be wider than the 1001 rows (ticks) we [initially] allot.
// Rendering prices is expensive, and will lock up the ui if done continuously.
// Therefore, ensure a minimum time interval has elapsed before rendering prices again.
var now = DateTime.Now;
if ((now - _last_price_range_calc_time) > _price_out_of_range_render_interval) {
SparkUtils.lazy_warn(!double.IsNaN(_mkt_break_lines.origin) && _mkt_break_lines.origin >= low && _mkt_break_lines.origin <= high,
() => fmt_log_msg($"market break ({_mkt_break_lines.origin}) is unacceptable for the market range ({low} - {high})"));
int prev_row_count = _row_count;
int n_ticks_to_low = TickUtils.normalized_tick_diff(security.ContractSpec, _mkt_break_lines.origin, low);
int n_ticks_to_high = TickUtils.normalized_tick_diff(security.ContractSpec, high, _mkt_break_lines.origin);
int desired_row_count = Math.Max(n_ticks_to_low, n_ticks_to_high) * 2 + 1;
_row_count = Math.Min(_max_row_count, desired_row_count);
if (_row_count != prev_row_count) {
if (desired_row_count > _max_row_count)
Logger.warn(bts.log.Subsystem.Ui, fmt_log_msg($"ticks between market range ({low} - {high}) exceeds the maximum number of rows allowed ({_max_row_count})"));
else
Logger.info(bts.log.Subsystem.Ui, fmt_log_msg($"increase row count to {_row_count} to accomodate market range ({low} - {high})"));
prices_changed = true;
_reset_height();
} else {
prices_changed = _mkt_break_lines.origin != _last_origin_price;
}
_last_price_range_calc_time = now;
//
string fmt_log_msg(string msg) =>
$"Ladder {security} (id:{security.Id}, low/high tick:{security.ContractSpec.LowTick}/{security.ContractSpec.HighTick}): {msg}.";
}
return prices_changed;
}
bool _prices_out_of_range(out double low, out double high) {
low = _bids == null ? double.NaN : TickUtils.low_tick(_bids, _asks);
high = _asks == null ? double.NaN : TickUtils.high_tick(_bids, _asks);
return
(!double.IsNaN(low) && _price_list[_price_list.Length - 1] > low) ||
(!double.IsNaN(high) && _price_list[0] < high);
}
void _reset_height() {
double height = _row_count * _settings.row_height;
_visualHost.Height = height;
_ordershost.Height = height;
_render_grid_background();
}
#endregion
#region Market Break, Session Low/High Utils
static double _get_top_price(NativePriceSize[] prices) =>
@@ -513,8 +581,11 @@ namespace mbts.spark {
double _get_session_low() => _vm.md.session_low;
double _get_session_high() => _vm.md.session_high;
void _render_session_line(DrawingVisual vis, double price, uint color) =>
LadderRender.render_single_grid_line(vis, _row_for_price(price), _settings.row_height, color, _price_column.x_left, _settings.price_column.width);
void _render_mkt_break(DrawingVisual vis, double price, uint color) =>
LadderRender.render_mkt_break(vis, _row_for_price(price), _settings.row_height, color);
void _render_session_line(DrawingVisual vis, int row, uint color) =>
LadderRender.render_single_grid_line(vis, row, _settings.row_height, color, _price_column.x_left, _settings.price_column.width);
#endregion
void _settings_updated(LadderSettings s) {
@@ -556,6 +627,7 @@ namespace mbts.spark {
_visualHost.AddVisualChild(_bid_mkt_break_vis);
_visualHost.AddVisualChild(_session_low_vis);
_visualHost.AddVisualChild(_session_high_vis);
_visualHost.AddVisualChild(_session_range_vis);
_render_grid_background();
_init_tactile_adorner();
// this effectively sets the background of the "Last" column
@@ -573,14 +645,6 @@ namespace mbts.spark {
_tactile_adorner = new LadderTactileAdorner(this, _visualHost, _scrollViewer);
}
bool _prices_out_of_range(out double low, out double high) {
low = _bids == null ? double.NaN : TickUtils.low_tick(_bids, _asks);
high = _asks == null ? double.NaN : TickUtils.high_tick(_bids, _asks);
return
(!double.IsNaN(low) && _price_list[_price_list.Length - 1] > low) ||
(!double.IsNaN(high) && _price_list[0] < high);
}
void _render_grid_background() {
LadderRender.render_grid(_gridvis, columns, _row_count, _settings.row_height, _settings.grid_line_color);
}
@@ -632,9 +696,12 @@ namespace mbts.spark {
!(x == y);
}
// This class represents interesting price points as they should be rendered on the LadderGridHost
// Note: The values contained here do NOT necessarily represent true data, as they will be NaN/null if their respective visual is hidden in LadderSettings
class MarketBreakLines {
readonly LadderGridHost _owner;
double _bid, _ask, _mid, _origin, _session_low, _session_high;
int? _low_index, _high_index;
public MarketBreakLines(LadderGridHost owner) =>
_owner = owner;
@@ -644,6 +711,7 @@ namespace mbts.spark {
public bool mid_dirty { get; private set; }
public bool session_low_dirty { get; private set; }
public bool session_high_dirty { get; private set; }
public bool session_range_dirty => session_low_dirty || session_high_dirty;
public bool origin_dirty { get; private set; }
public double bid => _bid;
@@ -652,6 +720,40 @@ namespace mbts.spark {
public double session_low => _session_low;
public double session_high => _session_high;
public double origin => _origin;
public int? low_render_index => low_index.HasValue ? low_index.Value + 1 : new int?();
public int? low_index {
get {
if (!_low_index.HasValue && !double.IsNaN(_session_low)) {
if (_high_index.HasValue) {
// relative lookup
_low_index = _high_index.Value + _get_session_range_size();
} else {
// binary search
_low_index = _owner._row_for_price(_session_low);
}
}
return _low_index;
}
}
// only reason for the high_render_index prop is naming consistency with low_render_index
public int? high_render_index => high_index;
public int? high_index {
get {
if (!_high_index.HasValue && !double.IsNaN(_session_high)) {
if (_low_index.HasValue) {
// relative lookup
_high_index = _low_index.Value - _get_session_range_size();
} else {
// binary search
_high_index = _owner._row_for_price(_session_high);
}
}
return _high_index;
}
}
int _get_session_range_size() =>
TickUtils.normalized_tick_diff(_owner.security.spec_or_default(), _session_high, _session_low);
LadderSettings _settings => _owner._settings;
@@ -659,8 +761,12 @@ namespace mbts.spark {
bid_dirty = ObjectHelper.update_value_type(ref _bid, _settings.bid_break_line.show ? _owner._get_bid_market_break() : double.NaN);
ask_dirty = ObjectHelper.update_value_type(ref _ask, _settings.ask_break_line.show ? _owner._get_ask_market_break() : double.NaN);
mid_dirty = ObjectHelper.update_value_type(ref _mid, _settings.mid_break_line.show ? _owner._get_mid_market_break() : double.NaN);
session_low_dirty = ObjectHelper.update_value_type(ref _session_low, _owner._get_session_low());
session_high_dirty = ObjectHelper.update_value_type(ref _session_high, _owner._get_session_high());
session_low_dirty = ObjectHelper.update_value_type(ref _session_low, (_settings.session_low_line.show || _settings.session_range_fill.show) ? _owner._get_session_low() : double.NaN);
session_high_dirty = ObjectHelper.update_value_type(ref _session_high, (_settings.session_high_line.show || _settings.session_range_fill.show) ? _owner._get_session_high() : double.NaN);
if (session_low_dirty)
_low_index = null;
if (session_high_dirty)
_high_index = null;
//
double new_origin;
if (!double.IsNaN(bid))
@@ -34,7 +34,9 @@ namespace mbts.spark {
readonly Property<FontFamily> _font_family;
readonly Property<FontWeight> _font_weight;
readonly Property<double> _font_size;
readonly Property<Brush> _foreground, _background, _hoverbackground, _border;
readonly Property<Brush> _foreground, _background, _hoverbackground, _border, _parent_algo_type_brush;
readonly Property<bool> _is_exchange_order, _has_multiple_orders_at_same_level, _is_hedge_order;
readonly Property<CustomOrderDefinition.CustomOneofCase> _parent_algo_type;
readonly Property<string> _summary, _description;
IObservable<LadderSettings.BadgeStyle> _bs;
LadderSettings.BadgeStyle _current_badge_style;
@@ -62,6 +64,11 @@ namespace mbts.spark {
_border = backing(nameof(border), _color_bg_brush);
_summary = backing(nameof(summary), string.Empty);
_description = backing(nameof(description), string.Empty);
_is_exchange_order = backing(nameof(is_exchange_order), false);
_has_multiple_orders_at_same_level = backing(nameof(has_multiple_orders_at_same_level), false);
_is_hedge_order = backing(nameof(is_hedge_order), false);
_parent_algo_type = backing(nameof(parent_algo_type), CustomOrderDefinition.CustomOneofCase.None);
_parent_algo_type_brush = backing(nameof(parent_algo_type_brush), _color_bg_brush);
FontFamily get_font_family(LadderSettings s) => new FontFamily(s.orders_column.font_family);
FontWeight get_font_weight(LadderSettings s) => ui.utility.text.TextUtils.from_open_type_weight_safe(s.orders_column.font_weight);
double get_font_size(LadderSettings s) => s.orders_column.font_size;
@@ -80,28 +87,45 @@ namespace mbts.spark {
// update brushes
Color color;
switch (side) {
case Side.Buy: color = BTSColors.MarketData.bid; break;
case Side.Sell: color = BTSColors.MarketData.ask; break;
case Side.Buy: color = BTSColors.MarketData.bid_alt; break;
case Side.Sell: color = BTSColors.MarketData.ask_alt; break;
case Side.Undefined:
default:
color = Colors.MediumPurple; break;
color = BTSColors.MarketData.bid_ask_alt_blend; break;
}
var darker = BTSColor.darken2(color.R, color.G, color.B, 0.75);
Color dark = new Color() { A = 255, R = darker.r, G = darker.g, B = darker.b };
//var completion = _parent_and_child_not_sharing_slot().Sum(order => OrderUtils.filled(order)) / _parent_and_child_not_sharing_slot().Sum(order => OrderUtils.quantity(order));
background = _color_bg_brush; //mkbrush(color, _colorbg, 0);
bts.spark.OrderMetadata parent_algo_metadata = _parent.model.order_gateway.factory.get_metadata(parent_algo_type);
parent_algo_type_brush = parent_algo_metadata.Color.rgb_brush();
var buy_sell_background_fill_color = new SolidColorBrush(color);
buy_sell_background_fill_color.Freeze();
background = buy_sell_background_fill_color;
hoverbackground = mkbrush(dark, _darkbg, 0);
border = new SolidColorBrush(color);
filled = _parent_and_child_not_sharing_slot().Select(order => OrderUtils.filled(order)).Sum();
working_quantity = _parent_and_child_not_sharing_slot().Select(order => order.working_quantity()).Sum();
quantity = _parent_and_child_not_sharing_slot().Select(order => order.State.Quantity).Sum();
if (_orders.Count > 0)
{
// if this badge only represents a single order, then is_exchange_order and the border (= algo color)
// should be set appropriately
if (_orders.Count == 1) {
var single_order = _orders.Values.First();
var single_order_metadata = _parent.model.order_gateway.factory.get_metadata(single_order);
border = single_order_metadata.Color.rgb_brush();
is_exchange_order = OrderUtils.is_exchange_order(_orders.Values.First());
} else {
border = new SolidColorBrush(color);
is_exchange_order = false;
}
has_multiple_orders_at_same_level = _orders.Count > 1;
is_hedge_order = _orders.Any(o => o.Value.sub_type() == OrderSubType.HedgingLeg);
if (_orders.Any()) {
summary = _orders.Values.Select(order => order.short_description(_parent.security.ContractSpec)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}");
description = _orders.Values.Select(order => order.full_description(_parent.security)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}");
}
_set_badge_text();
}
private void _set_badge_text() {
@@ -140,6 +164,7 @@ namespace mbts.spark {
IEnumerable<OrderRecordImmutable> _parent_and_child_not_sharing_slot() => _orders.Values.Where(o => !_orders.ContainsKey(o.ParentKey));
public IReadOnlyList<string> text_lines { get; private set; }
public bool has_parent => _orders.Values.Any( order => order.has_parent());
public bool has_phantom_price => !double.IsNaN(_phantom_price);
@@ -161,6 +186,13 @@ namespace mbts.spark {
public Brush border { get => _border.Value; private set => _border.Value = value; }
public string summary { get => _summary.Value; private set => _summary.Value = value; }
public string description { get => _description.Value; private set => _description.Value = value; }
public bool is_exchange_order { get => _is_exchange_order.Value; private set => _is_exchange_order.Value = value; }
public bool has_multiple_orders_at_same_level { get => _has_multiple_orders_at_same_level.Value; private set => _has_multiple_orders_at_same_level.Value = value; }
public bool is_hedge_order { get => _is_hedge_order.Value; private set => _is_hedge_order.Value = value; }
public Brush parent_algo_type_brush { get => _parent_algo_type_brush.Value; private set => _parent_algo_type_brush.Value = value; }
// the setter is public so that the LadderVM can set this field
public CustomOrderDefinition.CustomOneofCase parent_algo_type { get => _parent_algo_type.Value; set => _parent_algo_type.Value = value; }
public IEnumerable<OrderRecordImmutable> orders => _orders.Values;
void _cancel_order() {
@@ -7,6 +7,7 @@ using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
Loaded 100 of 169 files, more files were not shown because too many files have changed in this diff. Show more