This commit is contained in:
Pedro Pinto committed 2018-07-18 16:48:47 -04:00
commit 78cefa187a
38 files changed
+967 -555

No files matched your search

@@ -42,7 +42,7 @@ namespace mbts.spark {
_orders_model = orders_model;
_security_text = smd.security.ToString();
_security_key_text = security_key.ToString();
string format_price(double price) => security.ContractSpec.format(price);
string format_price(double price) => security.format(price);
_position = new CellProperty<int>(0);
_bid_price = backing(nameof(bid_price), double.NaN);
_ask_price = backing(nameof(ask_price), double.NaN);
@@ -106,8 +106,8 @@ namespace mbts.spark {
public double session_high => _session_high.Value;
public int working_bid_volume => _working_bid_volume.value;
public int working_ask_volume => _working_ask_volume.value;
public string working_bids_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_bid, _order_summarizer.best_working_bid_qty, _order_summarizer.working_bid_qty, security.ContractSpec);
public string working_asks_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_ask, _order_summarizer.best_working_ask_qty, _order_summarizer.working_ask_qty, security.ContractSpec);
public string working_bids_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_bid, _order_summarizer.best_working_bid_qty, _order_summarizer.working_bid_qty, security);
public string working_asks_text => OrderUtils.order_collection_summary(_order_summarizer.best_working_ask, _order_summarizer.best_working_ask_qty, _order_summarizer.working_ask_qty, security);
public double working_best_bid => _working_best_bid.value;
public double working_best_ask => _working_best_ask.value;
public IList<CellAnimation> animations => _animation.get_animations().ToList();
@@ -76,7 +76,7 @@ namespace mbts.spark {
BindingBase price_binding(string prop) {
var mb = new MultiBinding { Converter = price_converter };
mb.Bindings.Add(new Binding(prop) { Mode = BindingMode.OneWay });
mb.Bindings.Add(new Binding($"{nameof(Row.security)}.{nameof(SecurityImmutable.ContractSpec)}") { Mode = BindingMode.OneWay });
mb.Bindings.Add(new Binding($"{nameof(Row.security)}") { Mode = BindingMode.OneWay });
return mb;
}
//
@@ -101,7 +101,7 @@ namespace mbts.spark {
show_ladder = new DelegateCommand(() => parent._show_ladder_async(this).ignore());
_security_text = security.ToString();
_time_text = time.ToString("M/d h:mm:ss tt");
_price_text = security.ContractSpec.format(price);
_price_text = security.format(price);
_size_text = size.ToString();
_trade_key_text = _trade_key.ToString();
_security_key_text = security_key.ToString();
@@ -1,6 +1,7 @@
using bts.api;
using bts.shell;
using bts.spark;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.spark;
@@ -23,7 +24,7 @@ namespace mbts.spark {
/// The view model designed to serve as the DataContext for the SyntheticEditorView
/// </summary>
partial class SyntheticEditorVM : DisposableViewModelBase, IRequestViewClose, IRequestBindingSourceUpdate, IDisposable {
readonly ObservableCollection<TickFactors> _available_tick_factors = new ObservableCollection<TickFactors>(TickUtils.all_present_ticks());
readonly ObservableCollection<TickFactors> _available_tick_factors = new ObservableCollection<TickFactors>(TickUtils.synthetic_presets);
readonly QuantityModel _quantity_model;
readonly PriceMultiplierModel _price_mult_model;
readonly List<IDisposable> _resources = new List<IDisposable>();
@@ -41,7 +42,7 @@ namespace mbts.spark {
public SyntheticEditorVM(SpreaderModel model, SecurityImmutable synthetic, ExecutionStrategyImmutable strategy, IObservable<bool> security_has_working_orders)
: this(synthetic, strategy, false) {
ExceptionAssert.InvalidOperation.That(synthetic.Id != 0, "This constructor may only be used for already-existing synthetic securities (id must be non-zero).");
_tick_factors = TickUtils.get_regional_ticks(synthetic.ContractSpec).low_tick;
_tick_factors = TickUtils.get_regional_ticks(synthetic).low_tick;
title = $"Edit '{synthetic.Synthetic.Name}'";
icon = Icons.ModifySynthetic;
_has_working_orders = backing(nameof(has_working_orders), security_has_working_orders.OnDispatcher());
@@ -94,7 +95,7 @@ namespace mbts.spark {
_set_ticks_automatically = false;
_set_quantities_automatically = false;
_set_price_mults_automatically = false;
_tick_factors = TickUtils.get_regional_ticks(_synthetic.ContractSpec).low_tick;
_tick_factors = TickUtils.get_regional_ticks(_synthetic).low_tick;
} else {
_deduce_name();
_deduce_ticks();
@@ -153,6 +154,7 @@ namespace mbts.spark {
_set_quantities_automatically = is_new;
_set_price_mults_automatically = is_new;
available_tick_factors_view = CollectionViewSource.GetDefaultView(_available_tick_factors);
((ListCollectionView)available_tick_factors_view).CustomSort = TickUtils.CompareUtils.base_unit_comparer.as_non_generic();
available_tick_factors_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(TickFactors.tick_base)));
_quantity_model = new QuantityModel(!is_new);
@@ -328,7 +330,7 @@ namespace mbts.spark {
void _deduce_ticks() {
_tick_factors = TickUtils.deduce_ticks(leg_tuples.Select(l => l.leg.Security.ContractSpec));
if (_tick_factors != null && !_available_tick_factors.Contains(tick_factors))
if (_tick_factors != null && !_available_tick_factors.Contains(_tick_factors))
_available_tick_factors.Add(_tick_factors);
RaisePropertyChanged(nameof(tick_factors));
}
@@ -1,6 +1,7 @@
using bts.api;
using bts.spark;
using mbts.spark;
using mbts.spark.filters;
using mbts.ui;
using mbts.ui.spark;
using ProtoBuf;
@@ -20,7 +21,6 @@ namespace bts.shell {
_dispose = bus.subscribe(SparkTags.ShowPAndLTag).OnDispatcher().Subscribe(show);
}
public override Task<IShellWindow> load(PAndLStartupData state) {
var w = new PAndLWindow(_model, this, _bus, state, SparkCommands.ShowPAndL.icon) as IShellWindow;
return Task.FromResult(w);
@@ -33,6 +33,58 @@ namespace bts.shell {
[ProtoContract]
public class PAndLStartupData {
/// <summary>
/// Parameterless constructor for protobuf
/// </summary>
public PAndLStartupData() { }
public PAndLStartupData(List<SortingCriteria> sorting_criteria, FilterStates filters, pnl_calc_type calc_type, TimeSpan start_of_day_time) {
this.sort_criteria = sorting_criteria;
this.filters = filters;
this.calc_type = calc_type;
this.start_of_day_time = start_of_day_time;
}
[ProtoMember(5)]
public readonly List<SortingCriteria> sort_criteria;
[ProtoMember(10)]
public FilterStates filters;
[ProtoMember(15)]
public pnl_calc_type calc_type;
[ProtoMember(20)]
public TimeSpan? start_of_day_time;
}
[ProtoContract]
public class FilterStates {
[ProtoMember(1)]
public string account_regex;
[ProtoMember(2)]
public string exchange_regex;
[ProtoMember(3)]
public string symbol_regex;
[ProtoMember(4)]
public string security_regex;
[ProtoMember(5)]
public IntMinMaxState start_net_pos;
[ProtoMember(6)]
public DoubleMinMaxState start_pnl;
[ProtoMember(7)]
public UIntMinMaxState day_long_pos;
[ProtoMember(8)]
public UIntMinMaxState day_short_pos;
[ProtoMember(9)]
public DoubleMinMaxState day_pnl;
[ProtoMember(10)]
public IntMinMaxState total_net_pos;
[ProtoMember(11)]
public DoubleMinMaxState total_pnl;
[ProtoMember(12)]
public DoubleMinMaxState pnl_price;
}
}
@@ -38,23 +38,23 @@ namespace bts.spark {
#region formatting
(SecurityImmutable?, ContractSpecificationImmutable?) get_security(uint security_key) {
SecurityImmutable? get_security(uint security_key) {
if (_security.TryGetValue(security_key, out SecurityMD md)) {
return (md.security, md.security.ContractSpec);
return md.security;
}
return (null, null);
return null;
}
string format_order_success(uint key, double price, uint size, Side side, ContractSpecificationImmutable? spec) {
return $"({key}) {side.ToString().ToLower()} {size} @ {spec.format(price)}";
string format_order_success(uint key, double price, uint size, Side side, SecurityImmutable? security) {
return $"({key}) {side.ToString().ToLower()} {size} @ {security.format(price)}";
}
string format_order_fail(double price, uint size, Side side, ContractSpecificationImmutable? spec, string error) {
return $"Failed to {side.ToString().ToLower()} {size} @ {spec.format(price)}. {error}";
string format_order_fail(double price, uint size, Side side, SecurityImmutable? security, string error) {
return $"Failed to {side.ToString().ToLower()} {size} @ {security.format(price)}. {error}";
}
string format_cancel_success(OrderRecordImmutable order, ContractSpecificationImmutable? spec) {
return $"({order.Key}) Canceled {order.short_description(spec)}, was working {order.working_quantity()}";
string format_cancel_success(OrderRecordImmutable order, SecurityImmutable? security) {
return $"({order.Key}) Canceled {order.short_description(security)}, was working {order.working_quantity()}";
}
string format_cancel_error(OrderRecordImmutable order, ContractSpecificationImmutable? spec, string error) {
return $"({order.Key}) Failed to cancel {order.short_description(spec)}: {error}";
string format_cancel_error(OrderRecordImmutable order, SecurityImmutable? security, string error) {
return $"({order.Key}) Failed to cancel {order.short_description(security)}: {error}";
}
string format_fill_summary(OrderRecordImmutable before, OrderRecordImmutable after) {
int fb = (int)before.State.FilledQuantity;
@@ -65,14 +65,14 @@ namespace bts.spark {
return $"({key}) Status changed from {old_status} to {new_status}";
}
public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, ContractSpecificationImmutable? spec) {
public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, SecurityImmutable? security) {
double old_price = old_order.State.Price, new_price = new_order.State.Price;
uint old_size = old_order.State.Quantity, new_size = new_order.State.Quantity;
string modified_size_partial_description(int working_size) {
return $"size from {old_size} to {new_size}, working {working_size}";
}
string modified_price_partial_description() {
return $"price from {spec.format(old_price)} to {spec.format(new_price)}";
return $"price from {security.format(old_price)} to {security.format(new_price)}";
}
if (old_price != new_price || old_size != new_size) {
StringBuilder sb = new StringBuilder($"({old_order.Key}) Changed ");
@@ -102,7 +102,7 @@ namespace bts.spark {
foreach (var order in added) {
if (!string.IsNullOrEmpty(order.State.LastMsg) && order.State.Created.ToDateTime().Date == DateTime.Today) {
(var security, var spec) = get_security(order.Def.SecurityKey);
var security = get_security(order.Def.SecurityKey);
if (security.HasValue) {
log_status(ActivityLogCategory.warn, security, order.State.LastMsg);
}
@@ -111,10 +111,10 @@ namespace bts.spark {
foreach (var neworder in changed) {
var oldorder = removed[neworder.Key];
(var security, var spec) = get_security(neworder.Def.SecurityKey);
var security = get_security(neworder.Def.SecurityKey);
//
// description
var mod_desc = modified_description(oldorder, neworder, spec);
var mod_desc = modified_description(oldorder, neworder, security);
if (!string.IsNullOrEmpty(mod_desc)) {
log_status(ActivityLogCategory.modify, security, mod_desc);
}
@@ -145,31 +145,31 @@ namespace bts.spark {
}
internal void on_send_order(OrderDefinitionImmutable order, double price, uint size, uint? key, string error) {
(var security, var spec) = get_security(order.SecurityKey);
var security = get_security(order.SecurityKey);
log_status(ActivityLogCategory.order, security, key.HasValue ?
format_order_success(key.Value, price, size, order.Side, spec) :
format_order_fail(price, size, order.Side, spec, error));
format_order_success(key.Value, price, size, order.Side, security) :
format_order_fail(price, size, order.Side, security, error));
}
internal void on_cancel_order(OrderRecordImmutable order, bool success, string error) {
(var security, var spec) = get_security(order.Def.SecurityKey);
var security = get_security(order.Def.SecurityKey);
log_status(ActivityLogCategory.cancel, security, success ?
format_cancel_success(order, spec):
format_cancel_error(order, spec, error));
format_cancel_success(order, security):
format_cancel_error(order, security, error));
}
internal void update_order(OrderRecordImmutable order, double price, uint size) {
(var security, var spec) = get_security(order.Def.SecurityKey);
var security = get_security(order.Def.SecurityKey);
log_status(ActivityLogCategory.modify,
security,
$"({order.Key}) change from {order.State.Quantity}@{spec.format(order.State.Price)} to {size}@{spec.format(price)}");
$"({order.Key}) change from {order.State.Quantity}@{security.format(order.State.Price)} to {size}@{security.format(price)}");
}
internal void update_order_failed(OrderRecordImmutable order, double price, uint size) {
(var security, var spec) = get_security(order.Def.SecurityKey);
var security = get_security(order.Def.SecurityKey);
log_status(ActivityLogCategory.modify,
security,
$"({order.Key}) failed to change from {order.State.Quantity}@{spec.format(order.State.Price)} to {size}@{spec.format(price)}");
$"({order.Key}) failed to change from {order.State.Quantity}@{security.format(order.State.Price)} to {size}@{security.format(price)}");
}
}
@@ -74,7 +74,7 @@
<usp:PriceEntryControl
Grid.ColumnSpan="2"
usp:OrderModificationControl.IsDirty="{Binding price_dirty, FallbackValue={x:Null}}"
ContractSpec="{Binding security.ContractSpec}"
Security="{Binding security}"
Focusable="false"
TickDefaultValue="{Binding current_price, Converter={StaticResource TickDefaultPriceConverter}, FallbackValue={u:Double 0}}"
Value="{Binding price}"
@@ -97,13 +97,13 @@
<Button Command="{Binding set_price_command}" CommandParameter="{Binding bbo.bid}" Foreground="{u:BTSColor MarketData.bid}" FontWeight="Bold">
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="bbo.bid"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</Button>
<Button Grid.Column="2" Command="{Binding set_price_command}" CommandParameter="{Binding bbo.ask}" Foreground="{u:BTSColor MarketData.ask}" FontWeight="Bold">
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="bbo.ask"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</Button>
</Grid>
@@ -77,7 +77,7 @@
<Run.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="bid"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</Run.Text>
</Run>
@@ -85,7 +85,7 @@
<Run.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="ask"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</Run.Text>
</Run>
+2 -2
View File
@@ -126,7 +126,7 @@
<Run.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="bid"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</Run.Text>
</Run>
@@ -134,7 +134,7 @@
<Run.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="ask"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</Run.Text>
</Run>
@@ -1,7 +1,6 @@
using bts.api;
using bts.api.orderman;
using mbts.spark.utilities;
using mbts.utils;
namespace mbts.spark {
static partial class OrderTypeVMFactory {
private class StopLimitOrderVM : OrderTypeVMBase<StopLimitOrderDefinition> {
@@ -17,8 +16,8 @@ namespace mbts.spark {
}
}
public ContractSpecificationImmutable spec { get; private set; } =
SecurityDataHelper.Defaults.ContractSpecificationImmutable;
public SecurityImmutable security { get; private set; } =
SecurityDataHelper.Defaults.Security;
public override void assign_to(CustomOrderDefinition value) {
if (!HasErrors) {
@@ -6,6 +6,7 @@ using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Threading;
using bts.api.core;
using IronPython.Runtime.Types;
using mbts;
@@ -49,6 +50,9 @@ namespace bts.api.diagnostic {
readonly StringBuilder _pending = new StringBuilder();
readonly OutputPublisher _out;
readonly Thread _thread;
Dispatcher _dispatcher;
public ShellScriptServer(ServiceContext context, ShellDiagnosticsServiceServer parent, string qualifier) : base(context, qualifier) {
_parent = parent;
_out = make_output_publisher();
@@ -59,11 +63,19 @@ namespace bts.api.diagnostic {
_scope.SetVariable("shell_objects", new Func<object,object>(o => get_exports(o,null)));
_scope.SetVariable("shell_named_object", new Func<object,string,object>(get_export));
_scope.SetVariable("shell_named_objects", new Func<object,string,object>(get_exports));
_thread = new Thread(_ => {
_dispatcher = Dispatcher.CurrentDispatcher;
Thread.CurrentThread.Name = $"ShellScriptServer-{qualifier}";
Dispatcher.Run();
});
}
public override Task<VoidMessage> dispose(VoidMessage request) {
log("Finished", true);
_parent.terminate(this);
_dispatcher.BeginInvokeShutdown(DispatcherPriority.ApplicationIdle);
return Task.FromResult(new VoidMessage());
}
@@ -124,44 +136,58 @@ namespace bts.api.diagnostic {
});
}
Task<ScriptResultMessage> run_code(ScriptSource code) {
ScriptResultMessage run_code(ScriptSource code) {
try {
object result = code.Execute(_scope);
return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Complete, Message = (result?.ToString()) ?? "" });
return new ScriptResultMessage { Res = ScriptResult.Complete, Message = (result?.ToString()) ?? "" };
}
catch (Exception e) {
//log($"Exception: {e.Message}");
return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.RunError, Message = e.Message });
return (new ScriptResultMessage { Res = ScriptResult.RunError, Message = e.Message });
}
}
public override Task<ScriptResultMessage> run(ScriptLines request) {
// append lines to _pending
foreach (var line in request.Lines) {
_pending.AppendLine(line);
}
// CreateScriptSource from pending
var code = _engine.CreateScriptSourceFromString(_pending.ToString().TrimStart(' ', '\n', '\r'), SourceCodeKind.InteractiveCode);
var parse_result = code.GetCodeProperties();
if (parse_result == ScriptCodeParseResult.IncompleteStatement && code.GetCode().EndsWith(Environment.NewLine+Environment.NewLine)) {
parse_result = Microsoft.Scripting.ScriptCodeParseResult.Complete;
}
// todo: If code is 'incomplete' but we have 2 blank lines run it!
switch (parse_result) {
// If 'complete' run code
case ScriptCodeParseResult.Complete:
_pending.Clear();
return run_code(code);
// if 'invalid' return error
case ScriptCodeParseResult.Invalid:
Console.WriteLine("Invalid");
_pending.Clear();
return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Invalid, Message = code.GetCode() });
// otherwise continue buffering
default:
Console.WriteLine("Incomplete");
return Task.FromResult(new ScriptResultMessage { Res = ScriptResult.Incomplete });
var tcs = new TaskCompletionSource<ScriptResultMessage>();
void ret(ScriptResultMessage r) {
tcs.TrySetResult(r);
}
_dispatcher.BeginInvoke(() => {
// append lines to _pending
foreach (var line in request.Lines) {
_pending.AppendLine(line);
}
// CreateScriptSource from pending
var code = _engine.CreateScriptSourceFromString(_pending.ToString().TrimStart(' ', '\n', '\r'), SourceCodeKind.InteractiveCode);
var parse_result = code.GetCodeProperties();
if (parse_result == ScriptCodeParseResult.IncompleteStatement && code.GetCode().EndsWith(Environment.NewLine+Environment.NewLine)) {
parse_result = Microsoft.Scripting.ScriptCodeParseResult.Complete;
}
// todo: If code is 'incomplete' but we have 2 blank lines run it!
switch (parse_result) {
// If 'complete' run code
case ScriptCodeParseResult.Complete:
_pending.Clear();
ret(run_code(code));
break;
// if 'invalid' return error
case ScriptCodeParseResult.Invalid:
Console.WriteLine("Invalid");
_pending.Clear();
ret(new ScriptResultMessage { Res = ScriptResult.Invalid, Message = code.GetCode() });
break;
// otherwise continue buffering
default:
Console.WriteLine("Incomplete");
ret(new ScriptResultMessage { Res = ScriptResult.Incomplete });
break;
}
});
return tcs.Task;
}
}
}
@@ -17,8 +17,10 @@ namespace mbts {
public static double tick_unit_frac(this TickFactors tick) =>
tick.tick_unit / tick.tick_base;
public static double reduced_base(this TickFactors tick) => factor_out(tick.tick_base, 10);
public static string format(this TickFactors tick, double value) =>
format(tick, value, double.NaN, true, _nan_text);
format(tick, value, double.NaN, false, _nan_text);
public static string format(this TickFactors tick, double value, bool show_commas) =>
format(tick, value, double.NaN, show_commas, _nan_text);
@@ -176,9 +178,10 @@ namespace mbts {
if (DoubleHelper.IsNaNOrInfinity(input)) return input;
return input <= regional_tick.low_tick_inclusive_end ? regional_tick.low_tick.round(input) : regional_tick.high_tick.round(input);
}
public static int display_digits(this TickFactors tick) => display_digits(tick.tick_base);
#endregion
public static int n_display_digits(double tick_base) {
public static int display_digits(double tick_base) {
double log_tick_base = Math.Log10(tick_base);
int floor = (int)Math.Floor(log_tick_base);
double dec = log_tick_base - floor;
@@ -216,7 +219,7 @@ namespace mbts {
if (numerator_part >= tick_base) numerator_part /= Math.Pow(10, Math.Ceiling(Math.Log10(numerator_part) - Math.Log10(tick_base)));
else {
//e.g [tick_base 640] 1989-8 == 1989-80, or 1989-32 == 1989-320
int ndd_diff = n_display_digits(tick_base) - numerator_text.Length;
int ndd_diff = display_digits(tick_base) - numerator_text.Length;
if (ndd_diff > 0) numerator_part *= Math.Pow(10, ndd_diff);
if (numerator_part >= tick_base) numerator_part /= 10;
}
@@ -255,14 +258,18 @@ namespace mbts {
double numerator_dec = value - integer_part;
double unit_frac = tick.tick_unit / tick.tick_base;
int n_units = (int)Math.Round(numerator_dec / unit_frac);
if (n_units == tick.tick_base) return (integer_part + 1).ToString() + tick.separator() + new string('0', n_display_digits(tick.tick_base));
if (n_units == tick.tick_base) return (integer_part + 1).ToString() + tick.separator() + new string('0', display_digits(tick.tick_base));
double decimal_part = n_units * tick.tick_unit;
if (decimal_part == tick.tick_base) {
++integer_part;
decimal_part = 0;
} else {
// some ticks are not formatted with 100% precision, using less than the required display_digits
// for such cases, we need to truncate the decimal part rather than round it.
decimal_part = Math.Floor(decimal_part);
}
string integer_part_text = show_commas ? integer_part.ToString("#,0") : integer_part.ToString();
return integer_part_text + tick.separator() + decimal_part.ToString(new string('0', n_display_digits(tick.tick_base)));
return integer_part_text + tick.separator() + decimal_part.ToString(new string('0', display_digits(tick.tick_base)));
}
} catch (OverflowException ex) {
Logger.warn(bts.log.Subsystem.Ui, $"Arithmetic overflow exception in format_tick (tick:{tick}, value:{value}):{ex}");
@@ -1,4 +1,6 @@
using System;
using System.Collections;
using System.Collections.Generic;
namespace mbts.utils {
public static class CompareUtils {
@@ -19,5 +21,19 @@ namespace mbts.utils {
b.HasValue ? compare(a.Value, b.Value) : 1 :
b.HasValue ? -1 : 0;
#endregion
#region Comparer
public static IComparer as_non_generic<T>(this IComparer<T> comparer) =>
new NonGenericComparerWrapper<T>(comparer);
class NonGenericComparerWrapper<T> : IComparer {
readonly IComparer<T> _comparer;
public NonGenericComparerWrapper(IComparer<T> comparer) => _comparer = comparer;
public int Compare(object x, object y) =>
_comparer.Compare(ObjectHelper.try_convert<T>(x), ObjectHelper.try_convert<T>(y));
}
#endregion
}
}
@@ -21,7 +21,7 @@ namespace mbts.ui.controls {
double _glyph_width, _font_size, _value;
GlyphRun _glyph_run;
GlyphContext _glyph_context;
ContractSpecificationImmutable _spec;
SecurityImmutable _security;
static PriceCell() =>
WPFHelper.override_metadata<HorizontalAlignment, PriceCell>(
@@ -41,7 +41,7 @@ namespace mbts.ui.controls {
_padding = Padding;
_font_size = FontSize;
_value = Value;
_spec = ContractSpec;
_security = Security;
_glyph_context = GlyphContext.create(FontFamily, FontWeight);
}
@@ -147,20 +147,20 @@ namespace mbts.ui.controls {
public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
#endregion
#region ContractSpec
public static readonly DependencyProperty ContractSpecProperty =
WPFHelper.create_dp<ContractSpecificationImmutable, PriceCell>(
nameof(ContractSpec),
#region Security
public static readonly DependencyProperty SecurityProperty =
WPFHelper.create_dp<SecurityImmutable, PriceCell>(
nameof(Security),
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender,
(p, v) => {
p._spec = v;
p._security = v;
p._glyph_run = null;
}, SecurityDataHelper.Defaults.ContractSpecificationImmutable);
}, SecurityDataHelper.Defaults.SecurityImmutable);
public ContractSpecificationImmutable ContractSpec {
get => (ContractSpecificationImmutable)GetValue(ContractSpecProperty);
set => SetValue(ContractSpecProperty, value);
public SecurityImmutable Security {
get => (SecurityImmutable)GetValue(SecurityProperty);
set => SetValue(SecurityProperty, value);
}
#endregion
@@ -178,7 +178,7 @@ namespace mbts.ui.controls {
}
void _set_glyph(Size size) {
_glyph_run = _glyph_context.get_glyph_run(_spec.format(_value), _font_size, size, _horizontal_alignment, VerticalAlignment.Center, _padding);
_glyph_run = _glyph_context.get_glyph_run(_security.format(_value), _font_size, size, _horizontal_alignment, VerticalAlignment.Center, _padding);
_glyph_width = _glyph_run == null ? 0 : _glyph_run.AdvanceWidths.Sum();
}
@@ -22,7 +22,7 @@ namespace mbts.ui.controls {
public override FrameworkElement view_factory() {
var v = new PriceCell();
v.SetBinding(PriceCell.ValueProperty, _binding_factory());
v.SetBinding(PriceCell.ContractSpecProperty, _spec_binding_factory());
v.SetBinding(PriceCell.SecurityProperty, _spec_binding_factory());
return v;
}
}
@@ -70,7 +70,7 @@
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Stop Price</TextBlock>
<usp:PriceEntryControl Grid.Column="1" Margin="12,0,0,0" Width="80" Value="{Binding stop_price}" ContractSpec="{Binding spec}"/>
<usp:PriceEntryControl Grid.Column="1" Margin="12,0,0,0" Width="80" Value="{Binding stop_price}" Security="{Binding security}"/>
</Grid>
</DataTemplate>
</usp:OrderModificationTemplateSelector.StopLimitOrderTemplate>
@@ -82,7 +82,7 @@
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<TextBlock VerticalAlignment="Center">Stop Price</TextBlock>
<usp:PriceEntryControl Grid.Column="1" Margin="12,0,0,0" Width="80" Value="{Binding stop_price}" ContractSpec="{Binding spec}"/>
<usp:PriceEntryControl Grid.Column="1" Margin="12,0,0,0" Width="80" Value="{Binding stop_price}" Security="{Binding security}"/>
</Grid>
</DataTemplate>
</usp:OrderModificationTemplateSelector.StopMarketOrderTemplate>
@@ -1,12 +1,10 @@
using bts.api;
using mbts.spark;
using mbts.ui.extensions;
using mbts.ui.spark.converters;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using static mbts.ui.utility.text.TextUtils;
namespace mbts.ui.spark {
/// <summary>
@@ -18,7 +16,7 @@ namespace mbts.ui.spark {
#region Value
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(PriceEntryControl),new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceValue));
private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((ContractSpecificationImmutable)d.GetValue(ContractSpecProperty)).round((double)baseValue); }
private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((SecurityImmutable)d.GetValue(SecurityProperty)).round((double)baseValue); }
public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
#endregion
@@ -39,11 +37,11 @@ namespace mbts.ui.spark {
public ICommand TickDownCommand { get => GetValue(TickDownCommandProperty) as ICommand; private set => SetValue(TickDownCommandPropertyKey, value); }
#endregion
#region ContractSpec
public static readonly DependencyProperty ContractSpecProperty = DependencyProperty.Register("ContractSpec", typeof(ContractSpecificationImmutable), typeof(PriceEntryControl),
new PropertyMetadata(SecurityDataHelper.Defaults.ContractSpecificationImmutable, OnContractSpecChanged));
static void OnContractSpecChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PriceEntryControl)d)._update_text_binding();
public ContractSpecificationImmutable? ContractSpec { get => GetValue(ContractSpecProperty) as ContractSpecificationImmutable?; set => SetValue(ContractSpecProperty, value); }
#region Security
public static readonly DependencyProperty SecurityProperty = DependencyProperty.Register(
nameof(Security), typeof(SecurityImmutable), typeof(PriceEntryControl), new PropertyMetadata(SecurityDataHelper.Defaults.SecurityImmutable, OnSecurityChanged));
static void OnSecurityChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) => ((PriceEntryControl)d)._update_text_binding();
public SecurityImmutable? Security { get => GetValue(SecurityProperty) as SecurityImmutable?; set => SetValue(SecurityProperty, value); }
#endregion
TextBox _text;
@@ -71,8 +69,8 @@ namespace mbts.ui.spark {
if (double.IsNaN(v)) {
SetCurrentValue(ValueProperty, TickDefaultValue);
} else {
var spec = ContractSpec;
if (spec.HasValue) SetCurrentValue(ValueProperty, spec.Value.tickup(v));
var sec = Security;
if (sec.HasValue) SetCurrentValue(ValueProperty, sec.Value.tickup(v));
else SetCurrentValue(ValueProperty, TickDefaultValue);
}
}
@@ -85,21 +83,21 @@ namespace mbts.ui.spark {
if (double.IsNaN(v)) {
SetCurrentValue(ValueProperty, TickDefaultValue);
} else {
var spec = ContractSpec;
if (spec.HasValue) SetCurrentValue(ValueProperty, spec.Value.tickdown(v));
var sec = Security;
if (sec.HasValue) SetCurrentValue(ValueProperty, sec.Value.tickdown(v));
else SetCurrentValue(ValueProperty, TickDefaultValue);
}
}
void _update_text_binding() {
if (_text != null) {
var spec = ContractSpec;
if (spec != null) {
var sec = Security;
if (sec != null) {
var be = _text.GetBindingExpression(TextBox.TextProperty);
if (be != null) {
var converter = be.ParentBinding.Converter as TickDisplayTwoWayConverter;
if (converter != null) {
converter.ContractSpec = spec;
converter.Security = sec;
be.UpdateTarget();
}
}
@@ -16,9 +16,9 @@ namespace mbts.ui.spark.converters {
}
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
var price = get_val<double>(values, 0);
var spec = get_val<ContractSpecificationImmutable?>(values, 1);
if (spec == null) return price.ToString();
return spec.Value.format(price);
var security = get_val<SecurityImmutable?>(values, 1);
if (security == null) return price.ToString();
return security.Value.format(price);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>
@@ -26,23 +26,17 @@ namespace mbts.ui.spark.converters {
}
class TickDisplayTwoWayConverter : IValueConverter {
public ContractSpecificationImmutable? ContractSpec { get; set; } =
new ContractSpecification {
CashPerPoint = 1.0,
LowTick = 0.01,
HighTick = 0.01,
PriceBreak = double.MaxValue,
PriceMultiplier = 1.0
};
public SecurityImmutable? Security { get; set; } =
SecurityDataHelper.Defaults.SecurityImmutable;
public double DisplayMultiplier { get; set; } = double.NaN;
public bool ShowCommas { get; set; } = false;
public string NaNText { get; set; } = string.Empty;
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
ContractSpec.Value.format((double)value, DisplayMultiplier, ShowCommas, NaNText);
Security.format((double)value, DisplayMultiplier, ShowCommas, NaNText);
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
ContractSpec.Value.parse(value as string, DisplayMultiplier, NaNText);
Security.parse(value as string, DisplayMultiplier, NaNText);
}
}
@@ -7,7 +7,7 @@ namespace mbts.ui.converters {
class TickFactorsTextConverter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
if (value is TickFactors tf) {
int n_digits = TickExtensions.n_display_digits(tf.tick_base);
int n_digits = tf.display_digits();
if (n_digits > 1) {
string n_digits_format = new string('0', n_digits);
string format = "{0:" + n_digits_format + "}/{1}";
+6 -20
View File
@@ -1,8 +1,6 @@
using bts.api;
using bts.api.orderman;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using static mbts.ui.utilities.DisplayNameHelper;
@@ -75,7 +73,7 @@ namespace mbts.spark {
if (order.HasDef) {
sec_key_text = $"Security: {order.Def.SecurityKey}";
if (order.HasState) {
sb.AppendLine($"{order.Def.Side}: {TickUtils.format(security.ContractSpec, order.State.Price)}");
sb.AppendLine($"{order.Def.Side}: {security.format(order.State.Price)}");
sb.AppendLine($"Filled: {filled(order)} / {order.State.Quantity}");
} else {
sb.AppendLine($"{order.Def.Side}: (price-unknown)");
@@ -97,8 +95,8 @@ namespace mbts.spark {
return sb.ToString();
}
public static string short_description(this OrderRecordImmutable order, ContractSpecificationImmutable? spec) =>
$"{(order.HasDef ? order.Def.Side.ToString() : "(unknown-side)")} {(order.HasState ? ($@"{spec.format(order.State.Price)} @ {order.State.Quantity}") : "(unknown-price) @ (unknown-quantity)")}";
public static string short_description(this OrderRecordImmutable order, SecurityImmutable? security) =>
$"{(order.HasDef ? order.Def.Side.ToString() : "(unknown-side)")} {(order.HasState ? ($@"{security.format(order.State.Price)} @ {order.State.Quantity}") : "(unknown-price) @ (unknown-quantity)")}";
public static bool has_parent(this OrderRecordImmutable order) =>
order.ParentKey != 0;
@@ -121,24 +119,12 @@ namespace mbts.spark {
public static string order_type_display_name(CustomOrderDefinition.CustomOneofCase order_type) =>
camel_to_title_case(Regex.Replace(order_type.ToString(), "Order", string.Empty, RegexOptions.IgnoreCase));
public static string order_collection_summary(ICollection<OrderRecordImmutable> orders, Comparison<double> compare_price, ContractSpecificationImmutable spec) {
if (orders.Count == 0) return string.Empty;
var price_lookup = orders.ToLookup(o => o.State.Price);
var best_price = price_lookup.MaxElement(g => g.Key, compare_price);
var best_price_volume = best_price.Sum(o => o.working_quantity());
return order_collection_summary(
best_price.Key,
best_price_volume,
best_price_volume + price_lookup.Where(g => g.Key != best_price.Key).SelectMany(g => g).Sum(o => o.working_quantity()),
spec);
}
public static string order_collection_summary(double best_price, int best_price_volume, int total_volume, ContractSpecificationImmutable spec) {
public static string order_collection_summary(double best_price, int best_price_volume, int total_volume, SecurityImmutable security) {
if (total_volume == 0)
return string.Empty;
return total_volume == best_price_volume ?
$"{best_price_volume} @ {spec.format(best_price)}" :
$"{best_price_volume} ({total_volume}) @ {spec.format(best_price)}";
$"{best_price_volume} @ {security.format(best_price)}" :
$"{best_price_volume} ({total_volume}) @ {security.format(best_price)}";
}
public static string past_tense(this Side side) {
+262 -145
View File
@@ -6,105 +6,31 @@ using mbts.utils;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
namespace mbts.spark {
static class TickUtils {
#region TickFactors Cache
static readonly TickFactors _default_tick = new TickFactors(100, 1);
static readonly ConcurrentDictionary<double, bool> _resolved_unknown_ticks = new ConcurrentDictionary<double, bool>();
static readonly ConcurrentDictionary<(double low_tick, double high_tick, double price_break), RegionalTickFactors> _regional_ticks_cache =
new ConcurrentDictionary<(double low_tick, double high_tick, double price_break), RegionalTickFactors>();
static readonly double[] _descending_tick_fractional_units;
static readonly IReadOnlyDictionary<double, TickFactors> _ticks_cache = new[] {
// 100 based
new { tick_unit = 0.01, tick_factors = new TickFactors(100, 1) }, // 1/100
new { tick_unit = 0.05, tick_factors = new TickFactors(100, 5) }, // 1/20
new { tick_unit = 0.10, tick_factors = new TickFactors(100, 10) }, // 1/10
new { tick_unit = 0.25, tick_factors = new TickFactors(100, 25) }, // 1/4
new { tick_unit = 0.50, tick_factors = new TickFactors(100, 50) }, // 1/2
// 1,000 based
new { tick_unit = 0.001, tick_factors = new TickFactors(1000, 1) }, // 1/1,000
new { tick_unit = 0.005, tick_factors = new TickFactors(1000, 5) }, // 1/200
new { tick_unit = 0.025, tick_factors = new TickFactors(1000, 25) }, // 1/40
// 10,000 based
new { tick_unit = 0.0001, tick_factors = new TickFactors(10000, 1) }, // 1/10,000
new { tick_unit = 0.0005, tick_factors = new TickFactors(10000, 5) }, // 1/2,000
new { tick_unit = 0.0025, tick_factors = new TickFactors(10000, 25) }, // 1/400
// 64 based
new { tick_unit = 0.015625, tick_factors = new TickFactors(64, 1) }, // 1/64
new { tick_unit = 0.03125, tick_factors = new TickFactors(64, 2) }, // 1/32
new { tick_unit = 0.0625, tick_factors = new TickFactors(64, 4) }, // 1/16
new { tick_unit = 0.125, tick_factors = new TickFactors(64, 8) }, // 1/8
// 640 based
new { tick_unit = 0.0015625, tick_factors = new TickFactors(640, 1) }, // 1/640
new { tick_unit = 0.003125, tick_factors = new TickFactors(640, 2) }, // 1/320
new { tick_unit = 0.00625, tick_factors = new TickFactors(640, 4) }, // 1/160
new { tick_unit = 0.0078125, tick_factors = new TickFactors(640, 5) }, // 1/128
new { tick_unit = 0.0125, tick_factors = new TickFactors(640, 8) }, // 1/80
new { tick_unit = 0.0390625, tick_factors = new TickFactors(640, 25) }, // 5/128
new { tick_unit = 0.078125, tick_factors = new TickFactors(640, 50) }, // 5/64
// 6,400 based
new { tick_unit = 0.00015625, tick_factors = new TickFactors(6400, 1) }, // 1/6,400
new { tick_unit = 0.0003125, tick_factors = new TickFactors(6400, 2) }, // 1/3,200
new { tick_unit = 0.000625, tick_factors = new TickFactors(6400, 4) }, // 1/1,600
new { tick_unit = 0.00078125, tick_factors = new TickFactors(6400, 5) }, // 1/1,280
new { tick_unit = 0.00125, tick_factors = new TickFactors(6400, 8) }, // 1/800
new { tick_unit = 0.00390625, tick_factors = new TickFactors(6400, 25) }, // 1/256
// 64,000 based
new { tick_unit = 0.000015625, tick_factors = new TickFactors(64000, 1) }, // 1/6,400
new { tick_unit = 0.00003125, tick_factors = new TickFactors(64000, 2) }, // 1/3,200
new { tick_unit = 0.0000625, tick_factors = new TickFactors(64000, 4) }, // 1/1,600
new { tick_unit = 0.000078125, tick_factors = new TickFactors(64000, 5) }, // 1/12,800
new { tick_unit = 0.000125, tick_factors = new TickFactors(64000, 8) }, // 1/8,000
new { tick_unit = 0.000390625, tick_factors = new TickFactors(64000, 25) }, // 1/2,560
new { tick_unit = 0.001953125, tick_factors = new TickFactors(64000, 125) },// 1/512
}.ToReadOnlyDictionary(obj => obj.tick_unit, obj => obj.tick_factors, EqualityComparer.Create<double>(MathUtils.epsilon_equals));
#endregion
static TickUtils() {
// overkill? Maybe, but ticks are fundamental to the entire application.
// Any changes to the tick defaults must be deliberate, and scrutinized.
Logger.assert(_ticks_cache.Count == 35);
foreach(var kv in _ticks_cache) {
double result = kv.Value.tick_unit / kv.Value.tick_base;
Logger.assert(result == kv.Key, $"{kv.Value.tick_unit}/{kv.Value.tick_base} ({result} != {kv.Key})");
}
_descending_tick_fractional_units = _ticks_cache.Keys.Ordered(new ReverseComparer<double>(Comparer<double>.Default)).ToLArray();
}
public static double ticksize(this ContractSpecificationImmutable spec, double price) =>
Math.Abs(price) > spec.PriceBreak ? spec.HighTick : spec.LowTick;
public static string format(this ContractSpecificationImmutable spec, double price) {
var tick_factors = _get_tick_factors(spec.ticksize(price));
return tick_factors.format(price, false);
}
public static string format(this ContractSpecificationImmutable? spec, double price) {
if (spec.HasValue) {
return spec.Value.format(price);
}
return price.ToString("0.00000");
}
public static string format(this SecurityImmutable security, double price) =>
TickStore.get(security).format(price);
public static string format(this ContractSpecificationImmutable spec, double price, double display_multiplier, bool show_commas, string nan_text) {
var tick_factors = _get_tick_factors(spec.ticksize(price));
return tick_factors.format(price, display_multiplier, show_commas, nan_text);
}
public static string format(this SecurityImmutable? security, double price) =>
security.HasValue ? security.Value.format(price) : price.ToString("0.00000");
public static double parse(this ContractSpecificationImmutable spec, string text) {
var regional_tfs = get_regional_ticks(spec);
return regional_tfs.parse(text);
}
public static string format(this SecurityImmutable security, double price, double display_multiplier, bool show_commas, string nan_text) =>
TickStore.get(security).format(price, display_multiplier, show_commas, nan_text);
public static double parse(this ContractSpecificationImmutable spec, string text, double display_multiplier, string nan_text) {
var regional_tfs = get_regional_ticks(spec);
return regional_tfs.parse(text, display_multiplier, nan_text);
}
public static string format(this SecurityImmutable? security, double price, double display_multiplier, bool show_commas, string nan_text) =>
TickStore.get(security).format(price, display_multiplier, show_commas, nan_text);
public static double parse(this SecurityImmutable security, string text, double display_multiplier, string nan_text) =>
TickStore.get(security).parse(text, display_multiplier, nan_text);
public static double parse(this SecurityImmutable? security, string text, double display_multiplier, string nan_text) =>
TickStore.get(security).parse(text, display_multiplier, nan_text);
public static double low_tick(NativePriceSize[] bids, NativePriceSize[] asks) {
double low = bids[bids.Length - 1].price;
@@ -124,11 +50,11 @@ namespace mbts.spark {
return high;
}
public static (int n_low, int n_high) tick_diff(ContractSpecificationImmutable spec, double x, double y) =>
get_regional_ticks(spec).tickdiff(x, y);
public static (int n_low, int n_high) tick_diff(SecurityImmutable security, double x, double y) =>
get_regional_ticks(security).tickdiff(x, y);
public static int normalized_tick_diff(ContractSpecificationImmutable spec, double x, double y) {
var (n_low, n_high) = tick_diff(spec, x, y);
public static int normalized_tick_diff(SecurityImmutable security, double x, double y) {
var (n_low, n_high) = tick_diff(security, x, y);
return n_low + n_high;
}
@@ -146,36 +72,38 @@ namespace mbts.spark {
return raw_mid - (raw_mid % tick_size);
}
public static IReadOnlyList<TickFactors> all_present_ticks() =>
_ticks_cache.Values.ToReadOnlyList();
public static IReadOnlyCollection<TickFactors> synthetic_presets =>
TickStore.synthetic_presets;
public static TickFactors deduce_ticks(IEnumerable<ContractSpecification> contract_specs) {
var gcd = MathUtils.GCD(contract_specs.Select(s => s.LowTick));
if (gcd == 0) return null;
return _try_get_tick_factors(gcd);
return TickStore.get_tick_factors(gcd);
}
public static double tickup(this ContractSpecificationImmutable contract, double value) =>
get_regional_ticks(contract).tickup(value);
public static double tickup(this SecurityImmutable security, double value) =>
TickStore.get(security).tickup(value);
public static double tickup(this ContractSpecificationImmutable contract, double value, int count) =>
get_regional_ticks(contract).tickup(value, (uint)count);
public static double tickup(this SecurityImmutable security, double value, int count) =>
TickStore.get(security).tickup(value, (uint)count);
public static double tickdown(this ContractSpecificationImmutable contract, double value) =>
get_regional_ticks(contract).tickdown(value);
public static double tickdown(this SecurityImmutable security, double value) =>
TickStore.get(security).tickdown(value);
public static double tickdown(this ContractSpecificationImmutable contract, double value, int count) =>
get_regional_ticks(contract).tickdown(value, (uint)count);
public static double tickdown(this SecurityImmutable security, double value, int count) =>
TickStore.get(security).tickdown(value, (uint)count);
public static bool tick_equals(this SecurityImmutable security, double x, double y) =>
tick_equals(security.ContractSpec, x, y);
public static bool tick_equals(this ContractSpecificationImmutable contract, double x, double y) =>
MathUtils.RoundFractionalUnits(x, contract.LowTick) == MathUtils.RoundFractionalUnits(y, contract.LowTick);
public static IEqualityComparer<double> tick_equality_comparer(this ContractSpecificationImmutable contract)
{
var eq = EqualityComparer.Create((double a, double b) => TickUtils.tick_equals(contract, a, b),
x => MathUtils.RoundFractionalUnits(x, contract.LowTick));
return eq;
}
public static IEqualityComparer<double> tick_equality_comparer(this SecurityImmutable security) =>
security.ContractSpec.tick_equality_comparer();
public static IEqualityComparer<double> tick_equality_comparer(this ContractSpecificationImmutable contract) =>
EqualityComparer.Create((double a, double b) => tick_equals(contract, a, b), x => MathUtils.RoundFractionalUnits(x, contract.LowTick));
public static double round_to_tick(this ContractSpecificationImmutable spec, double value) {
double intpart = (long)value;
@@ -185,47 +113,236 @@ namespace mbts.spark {
return intpart + floatpart;
}
public static RegionalTickFactors get_regional_ticks(ContractSpecificationImmutable spec) =>
_regional_ticks_cache.GetOrAdd((spec.LowTick, spec.HighTick, spec.PriceBreak), _create_regional_ticks);
public static RegionalTickFactors get_regional_ticks(SecurityImmutable security) =>
TickStore.get(security);
public static RegionalTickFactors get_regional_ticks(ContractSpecification spec) =>
_regional_ticks_cache.GetOrAdd((spec.LowTick, spec.HighTick, spec.PriceBreak), _create_regional_ticks);
public static class CompareUtils {
public static IComparer<TickFactors> base_unit_comparer =>
Comparer<TickFactors>.Create(utils.CompareUtils.safe_comparison<TickFactors>(compare_base_unit));
static RegionalTickFactors _create_regional_ticks((double low_tick, double high_tick, double price_break) def) =>
new RegionalTickFactors(_get_tick_factors(def.low_tick), _get_tick_factors(def.high_tick), def.price_break);
static TickFactors _get_tick_factors(double tick) {
if (_ticks_cache.TryGetValue(tick, out TickFactors result))
return result;
// try to return the largest known tick that is divisible by this tick
foreach (var tfu in _descending_tick_fractional_units) {
double mod = tick % tfu;
if (MathUtils.epsilon_equals(mod, 0)) {
if (_resolved_unknown_ticks.TryAdd(tick, true))
Logger.warn(bts.log.Subsystem.Ui, $"Resolved unknown tick {tick} to {tfu}, if this tick is expected, talk to John about adding it to the hard-coded defaults ASAP.");
return _ticks_cache[tfu];
}
public static int compare_base_unit(TickFactors a, TickFactors b) {
int comp = a.reduced_base().CompareTo(b.reduced_base());
if (comp != 0)
return comp;
comp = a.tick_base.CompareTo(b.tick_base);
if (comp != 0)
return comp;
return a.tick_unit.CompareTo(b.tick_unit);
}
Logger.assert(false, $"Unable to resolve tick ({tick}): going down because the application cannot run properly with unresolved ticks. " +
$"FOR DEVS: If this tick was not caused by a bug, please talk to John about adding it to the hard-coded defaults. " +
$"If you believe this tick belongs to a synthetic security, and should not be in the defaults, please delete said synthetic from the db " +
$"(note: the synthetic creation dialog has changed to only allow known ticks from now on, so if you get the latest code and delete old synthetics from the db, this will not happen again). " +
$"Direct any further questions to John.");
return null;
}
// Almost the same function as _get_tick_factors, only difference being no assert/log.
// This seemed more practical than trying to factor this behavior out, it's only a few lines of code.
static TickFactors _try_get_tick_factors(double tick) {
if (_ticks_cache.TryGetValue(tick, out TickFactors result))
return result;
// try to return the largest known tick that is divisible by this tick
foreach (var tfu in _descending_tick_fractional_units) {
double mod = tick % tfu;
if (MathUtils.epsilon_equals(mod, 0))
return _ticks_cache[tfu];
static class TickStore {
static readonly RegionalTickFactors _default_rtf = new RegionalTickFactors(new TickFactors(1000, 1), new TickFactors(1000, 1), double.MaxValue);
static readonly ConcurrentDictionary<SpecKey, RegionalTickFactors> _exchange_ticks = new ConcurrentDictionary<SpecKey, RegionalTickFactors>();
static readonly ReadOnlyDictionary<double, TickFactors> _synthetic_presets_cache = new[] {
// 100 based
new { tick_unit = 0.01, tick_factors = new TickFactors(100, 1) }, // 1/100
new { tick_unit = 0.05, tick_factors = new TickFactors(100, 5) }, // 1/20
new { tick_unit = 0.10, tick_factors = new TickFactors(100, 10) }, // 1/10
new { tick_unit = 0.25, tick_factors = new TickFactors(100, 25) }, // 1/4
new { tick_unit = 0.50, tick_factors = new TickFactors(100, 50) }, // 1/2
// 1,000 based
new { tick_unit = 0.001, tick_factors = new TickFactors(1000, 1) }, // 1/1,000
new { tick_unit = 0.005, tick_factors = new TickFactors(1000, 5) }, // 1/200
new { tick_unit = 0.025, tick_factors = new TickFactors(1000, 25) }, // 1/40
// 10,000 based
new { tick_unit = 0.0001, tick_factors = new TickFactors(10000, 1) }, // 1/10,000
new { tick_unit = 0.0005, tick_factors = new TickFactors(10000, 5) }, // 1/2,000
new { tick_unit = 0.0025, tick_factors = new TickFactors(10000, 25) }, // 1/400
// 64 based
new { tick_unit = 0.015625, tick_factors = new TickFactors(64, 1) }, // 1/64
new { tick_unit = 0.03125, tick_factors = new TickFactors(64, 2) }, // 1/32
new { tick_unit = 0.0625, tick_factors = new TickFactors(64, 4) }, // 1/16
new { tick_unit = 0.125, tick_factors = new TickFactors(64, 8) }, // 1/8
// 640 based
new { tick_unit = 0.0015625, tick_factors = new TickFactors(640, 1) }, // 1/640
new { tick_unit = 0.003125, tick_factors = new TickFactors(640, 2) }, // 1/320
new { tick_unit = 0.00625, tick_factors = new TickFactors(640, 4) }, // 1/160
new { tick_unit = 0.0078125, tick_factors = new TickFactors(640, 5) }, // 1/128
new { tick_unit = 0.0125, tick_factors = new TickFactors(640, 8) }, // 1/80
new { tick_unit = 0.0390625, tick_factors = new TickFactors(640, 25) }, // 5/128
new { tick_unit = 0.078125, tick_factors = new TickFactors(640, 50) }, // 5/64
// 6,400 based
new { tick_unit = 0.00015625, tick_factors = new TickFactors(6400, 1) }, // 1/6,400
new { tick_unit = 0.0003125, tick_factors = new TickFactors(6400, 2) }, // 1/3,200
new { tick_unit = 0.000625, tick_factors = new TickFactors(6400, 4) }, // 1/1,600
new { tick_unit = 0.00078125, tick_factors = new TickFactors(6400, 5) }, // 1/1,280
new { tick_unit = 0.00125, tick_factors = new TickFactors(6400, 8) }, // 1/800
new { tick_unit = 0.00390625, tick_factors = new TickFactors(6400, 25) }, // 1/256
// 64,000 based
new { tick_unit = 0.000015625, tick_factors = new TickFactors(64000, 1) }, // 1/6,400
new { tick_unit = 0.00003125, tick_factors = new TickFactors(64000, 2) }, // 1/3,200
new { tick_unit = 0.0000625, tick_factors = new TickFactors(64000, 4) }, // 1/1,600
new { tick_unit = 0.000078125, tick_factors = new TickFactors(64000, 5) }, // 1/12,800
new { tick_unit = 0.000125, tick_factors = new TickFactors(64000, 8) }, // 1/8,000
new { tick_unit = 0.000390625, tick_factors = new TickFactors(64000, 25) }, // 1/2,560
new { tick_unit = 0.001953125, tick_factors = new TickFactors(64000, 125) },// 1/512
}.ToReadOnlyDictionary(obj => obj.tick_unit, obj => obj.tick_factors, EqualityComparer.Create<double>(MathUtils.epsilon_equals));
static readonly double[] _descending_synthetic_tick_sizes;
static TickStore() =>
_descending_synthetic_tick_sizes = _synthetic_presets_cache.Select(kv => kv.Key).Ordered(new ReverseComparer<double>(Comparer<double>.Default)).ToArray();
public static IReadOnlyCollection<TickFactors> synthetic_presets => _synthetic_presets_cache.Values;
public static RegionalTickFactors get(SecurityImmutable security) {
if (security.HasContractSpec) {
if (security.ContractCase == Security.ContractOneofCase.Synthetic) {
return get(security.ContractSpec.LowTick);
} else if (security.HasGlbx) {
return _exchange_ticks.GetOrAdd(new SpecKey(security.ContractSpec, security.Glbx), _create_rtf);
}
}
return _default_rtf;
}
public static RegionalTickFactors get(SecurityImmutable? security) =>
security.HasValue ? get(security.Value) : _default_rtf;
public static RegionalTickFactors get(double tick_size) {
var tf = get_tick_factors(tick_size);
return new RegionalTickFactors(tf, tf, double.MaxValue);
}
public static TickFactors get_tick_factors(double tick_size) {
if (_synthetic_presets_cache.TryGetValue(tick_size, out TickFactors result))
return result;
// try to return the largest known tick that is divisible by this tick
foreach (var tfu in _descending_synthetic_tick_sizes) {
double mod = tick_size % tfu;
if (MathUtils.epsilon_equals(mod, 0)) {
return _synthetic_presets_cache[tfu];
}
}
return new TickFactors(1 / tick_size, tick_size);
}
static RegionalTickFactors _create_rtf(SpecKey key) {
double tick_base = key.denominator;
if (tick_base == 0) {
// indicates tick is a decimal
tick_base = 100;
}
return _create_rtf(key.low_tick, key.high_tick, key.price_break, tick_base, key.display_digits);
}
static RegionalTickFactors _create_rtf(double low_tick, double high_tick, double price_break, double reduced_target_base, uint display_digits_override) {
var low_tf = _try_create_tf(low_tick, reduced_target_base, display_digits_override);
var high_tf = _try_create_tf(high_tick, reduced_target_base, display_digits_override);
if (low_tf == null) {
low_tf = high_tf ?? (high_tf = _default_rtf.low_tick);
} else if (high_tf == null)
high_tf = low_tf;
else {
// if low/high tick-bases do not match, inflate the smaller base so they do
// Note: this assumes the tick-bases are related by factors of 10 (i.e. they have all the same prime factors except for a different number of pairs of 5 and 2, e.g. 64 and 640)
if (low_tf.tick_base > high_tf.tick_base) {
high_tf = _inflate_to_base(high_tf, low_tf.tick_base);
} else if (low_tf.tick_base < high_tf.tick_base) {
low_tf = _inflate_to_base(low_tf, high_tf.tick_base);
}
}
return new RegionalTickFactors(low_tf, high_tf, price_break);
}
/// <summary>
/// Creates TickFactors with a base equal to &quot;<paramref name="tick_base"/> * 10^n,&quot; where 'n' is a natural number (including 0).
/// <para>Note: If <paramref name="display_digits_override"/> is non-zero, 'n' will be &quot;<paramref name="display_digits_override"/> - Math.Ceiling(Log10(<paramref name="tick_base"/>))&quot;</para>
/// </summary>
/// <param name="tick_size">The raw tick-size.</param>
/// <param name="tick_base">The raw tick-base.</param>
/// <returns>Well-defined TickFactors</returns>
static TickFactors _try_create_tf(double tick_size, double tick_base, uint display_digits_override) {
var tf = _try_create_tf(tick_size, tick_base);
if (tf != null && display_digits_override > 0) {
int display_digit_diff = (int)display_digits_override - tf.display_digits();
if (display_digit_diff != 0)
tf = _inflate_to_base(tf, tf.tick_base * Math.Pow(10, display_digit_diff));
}
return tf;
}
/// <summary>
/// Creates TickFactors with a base equal to &quot;reduced_target_base * 10^n,&quot; where 'n' is a natural number (including 0).
/// </summary>
/// <param name="tick_size">The raw tick-size.</param>
/// <param name="reduced_target_base">The smallest acceptable tick-base.</param>
/// <returns>Well-defined TickFactors</returns>
static TickFactors _try_create_tf(double tick_size, double reduced_target_base) {
if (!_check_tick_size(tick_size))
return null;
double raw_base = 1 / tick_size;
double raw_base_log10 = Math.Log10(raw_base);
double reduced_target_base_log10 = Math.Log10(reduced_target_base);
double log10_diff = raw_base_log10 - reduced_target_base_log10;
if (MathUtils.is_int(log10_diff))
return raw_base > reduced_target_base ? new TickFactors(raw_base, 1) : new TickFactors(reduced_target_base, Math.Pow(10, -log10_diff));
int count = 0;
double factored_base = log10_diff > 0 ? reduced_target_base * Math.Pow(10, Math.Ceiling(log10_diff)) : reduced_target_base;
do {
if (factored_base % raw_base == 0)
return new TickFactors(factored_base, factored_base / raw_base);
factored_base *= 10;
} while (++count < 10);
return null;
}
static TickFactors _create_tf(double tick_size) {
if (!_check_tick_size(tick_size))
return _default_rtf.low_tick;
double matched_unit = double.MinValue;
TickFactors matched_tf = null;
foreach (var kv in _exchange_ticks) {
if (kv.Key.high_tick == tick_size) {
return kv.Value.high_tick;
} else if (kv.Key.low_tick == tick_size) {
return kv.Value.low_tick;
} else if (is_better_match(kv.Key.high_tick)) {
matched_unit = kv.Key.high_tick;
matched_tf = kv.Value.high_tick;
} else if (is_better_match(kv.Key.low_tick)) {
matched_unit = kv.Key.low_tick;
matched_tf = kv.Value.low_tick;
}
}
return matched_tf ?? new TickFactors(1.0 / tick_size, 1);
bool is_better_match(double known_unit) =>
known_unit < tick_size && known_unit > matched_unit && tick_size % known_unit == 0;
}
static bool _check_tick_size(double tick_size) =>
tick_size > 0 && tick_size <= 0.5;
static TickFactors _inflate_to_base(TickFactors tick_factors, double new_base) =>
new TickFactors(new_base, tick_factors.tick_unit * new_base / tick_factors.tick_base);
struct SpecKey : IEquatable<SpecKey> {
public readonly uint denominator, display_digits;
public readonly double low_tick, high_tick, price_break;
public SpecKey(ContractSpecificationImmutable spec, GLBXExchangeDataImmutable glbx_data) {
denominator = glbx_data.MainFraction;
display_digits = glbx_data.PriceDisplayFormat;
low_tick = spec.LowTick;
high_tick = spec.HighTick;
price_break = spec.PriceBreak;
}
public bool Equals(SpecKey other) =>
denominator == other.denominator &&
display_digits == other.display_digits &&
low_tick == other.low_tick &&
high_tick == other.high_tick &&
price_break == other.price_break;
public override bool Equals(object obj) =>
obj is SpecKey sk && Equals(sk);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash((int)denominator, (int)display_digits, low_tick.GetHashCode(), high_tick.GetHashCode(), price_break.GetHashCode());
}
return null;
}
}
}
@@ -14,6 +14,6 @@ namespace mbts.spark {
static class SecurityRowExtensions {
public static string format_price(this ISecurityRow row, double price) =>
row.security.ContractSpec.format(price);
row.security.format(price);
}
}
@@ -306,13 +306,13 @@ namespace mbts.spark {
_settings.row_height,
_price_list,
column.settings,
security.ContractSpec);
security);
break;
case ColumnType.Ask: render_market_col(_asks); break;
}
void render_market_col(NativePriceSize[] depth) {
var mid = LadderRender.index_of(_price_list, _last_origin_price, _price_comparer);
LadderRender.render_sizes(column.visual_tup.visual, column.visual_tup.glyph_context, mid, _price_list, depth, _settings.row_height, security.ContractSpec, column.settings);
LadderRender.render_sizes(column.visual_tup.visual, column.visual_tup.glyph_context, mid, _price_list, depth, _settings.row_height, security, column.settings);
}
}
_apply_column_visual_offset();
@@ -390,8 +390,8 @@ namespace mbts.spark {
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 n_ticks_to_low = TickUtils.normalized_tick_diff(security, _mkt_break_lines.origin, low);
int n_ticks_to_high = TickUtils.normalized_tick_diff(security, 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) {
@@ -412,7 +412,7 @@ namespace mbts.spark {
}
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);
_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);
_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
@@ -447,8 +447,8 @@ namespace mbts.spark {
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);
LadderRender.render_sizes(_bid_vis_tup.visual, _bid_vis_tup.glyph_context, origin_index, _price_list, _bids, _settings.row_height, security, _settings.bid_column);
LadderRender.render_sizes(_ask_vis_tup.visual, _ask_vis_tup.glyph_context, origin_index, _price_list, _asks, _settings.row_height, security, _settings.ask_column);
}
_last_origin_price = _mkt_break_lines.origin;
_price_dirty = false;
@@ -472,7 +472,7 @@ namespace mbts.spark {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return double.IsNaN(best_bid) ?
double.IsNaN(best_ask) ? _vm.low : security.ContractSpec.tickdown(best_ask) :
double.IsNaN(best_ask) ? _vm.low : security.tickdown(best_ask) :
best_bid;
}
@@ -480,15 +480,15 @@ namespace mbts.spark {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return double.IsNaN(best_ask) ?
double.IsNaN(best_bid) ? security.ContractSpec.tickdown(_vm.high) : best_bid :
security.ContractSpec.tickdown(best_ask);
double.IsNaN(best_bid) ? security.tickdown(_vm.high) : best_bid :
security.tickdown(best_ask);
}
double _get_mid_market_break() {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return double.IsNaN(best_bid) ?
double.IsNaN(best_ask) ? 0.5 * (_vm.low + _vm.high) : security.ContractSpec.tickdown(best_ask) :
double.IsNaN(best_ask) ? 0.5 * (_vm.low + _vm.high) : security.tickdown(best_ask) :
double.IsNaN(best_ask) ? best_bid : TickUtils.mid_tick(security.ContractSpec, best_bid, best_ask);
}
@@ -1,6 +1,5 @@
using bts.api;
using bts.api.orderman;
using bts.spark;
using mbts.ui;
using mbts.ui.shell;
using System;
@@ -99,7 +98,7 @@ namespace mbts.spark {
if (_orders.Count > 0)
{
summary = _orders.Values.Select(order => order.short_description(_parent.security.ContractSpec)).Aggregate((s1, s2) => $"{s1}{Environment.NewLine}{Environment.NewLine}{s2}");
summary = _orders.Values.Select(order => order.short_description(_parent.security)).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();
@@ -197,4 +196,4 @@ namespace mbts.spark {
return $"Price: {this.price} Order Count: {this.orders.Count()}";
}
}
}
}
@@ -317,7 +317,7 @@
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="change"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
@@ -325,7 +325,7 @@
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="high"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
@@ -333,7 +333,7 @@
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="low"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
@@ -341,7 +341,7 @@
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="open"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
@@ -349,7 +349,7 @@
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="settlement"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
@@ -57,7 +57,7 @@ namespace mbts.spark {
public static GlyphRun format_text(string text, int row, double row_height, LadderColumnSettings settings, GlyphContext glyph_context) =>
glyph_context.get_glyph_run(text, settings.font_size, settings.width, row_height, HorizontalAlignment.Center, 0, VerticalAlignment.Center, row * row_height, true);
public static double[] gen_prices(double mid, int row_count, ContractSpecificationImmutable spec) {
public static double[] gen_prices(double mid, int row_count, SecurityImmutable security) {
// require odd number
Logger.assert(row_count % 2 == 1);
var result = new double[row_count];
@@ -67,32 +67,32 @@ namespace mbts.spark {
double up = mid, down = mid;
// Starting from the middle iterate out to the edges
for (int x = 1; x <= range; ++x) {
up = TickUtils.tickup(spec, up);
down = TickUtils.tickdown(spec, down);
up = security.tickup(up);
down = security.tickdown(down);
result[middle - x] = up;
result[middle + x] = down;
}
return result;
}
public static GlyphRun[] format_prices(double[] prices, double row_height, LadderColumnSettings settings, GlyphContext glyph_context, ContractSpecificationImmutable spec) {
public static GlyphRun[] format_prices(double[] prices, double row_height, LadderColumnSettings settings, GlyphContext glyph_context, SecurityImmutable security) {
var result = new GlyphRun[prices.Length];
Parallel.For(0, prices.Length, i =>
result[i] = format_text(spec.format(prices[i]), i, row_height, settings, glyph_context));
result[i] = format_text(security.format(prices[i]), i, row_height, settings, glyph_context));
return result;
}
public static double[] render_prices(DrawingVisual price, GlyphContext glyph_context, double mid, int row_count, double row_height,
LadderColumnSettings settings, ContractSpecificationImmutable spec) {
var dprices = gen_prices(mid, row_count, spec);
render_prices(price, glyph_context, row_count, row_height, dprices, settings, spec);
LadderColumnSettings settings, SecurityImmutable security) {
var dprices = gen_prices(mid, row_count, security);
render_prices(price, glyph_context, row_count, row_height, dprices, settings, security);
return dprices;
}
public static void render_prices(DrawingVisual price, GlyphContext glyph_context, int row_count, double row_height, double[] dprices, LadderColumnSettings settings, ContractSpecificationImmutable spec) {
public static void render_prices(DrawingVisual price, GlyphContext glyph_context, int row_count, double row_height, double[] dprices, LadderColumnSettings settings, SecurityImmutable security) {
var foreground = settings.foreground.rgb_brush();
//var background = new SolidColorBrush(settings.background.rgb_color());
var fprices = format_prices(dprices, row_height, settings, glyph_context, spec);
var fprices = format_prices(dprices, row_height, settings, glyph_context, security);
using (var dc = price.RenderOpen())
using (_draw_with_clip(dc, settings, row_height, row_count)) {
//dc.DrawRectangle(background, null, new Rect(0, 0, settings.width, row_count * row_height));
@@ -126,7 +126,7 @@ namespace mbts.spark {
double[] prices,
NativePriceSize[] rungs,
double row_height,
ContractSpecificationImmutable spec,
SecurityImmutable security,
LadderColumnSettings settings
) {
//var background = new SolidColorBrush(settings.background.rgb_color());
@@ -143,7 +143,7 @@ namespace mbts.spark {
double price = nps.price;
ushort size = nps.size;
// prices are in descending order, so get diff from curr_price - price
int tick_diff = TickUtils.normalized_tick_diff(spec, curr_price, price);
int tick_diff = TickUtils.normalized_tick_diff(security, curr_price, price);
curr_index += tick_diff;
curr_price = price;
if (curr_index >= 0 && curr_index < prices.Length) {
@@ -1,4 +1,4 @@
using bts.api;
using bts.api;
using mbts.co2;
using mbts.ui.controls;
using System;
+141 -65
View File
@@ -2,6 +2,7 @@
using mbts.spark.filters;
using mbts.ui;
using mbts.ui.shell;
using mbts.ui.utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -13,66 +14,105 @@ using static bts.shell.PAndLWindowFactory;
namespace mbts.spark {
class PAndLVM : DisposableViewModelBase {
public PAndLVM(IBus bus, PAndLModel model, PAndLStartupData state) {
public PAndLVM(IBus bus, PAndLModel model, PAndLStartupData startup_data) {
_bus = bus;
_model = model;
_selected_pnl_calc_type = backing<pnl_calc_type>(nameof(selected_pnl_calc_type));
// get initial value from settings
// else default to midpoint
// TODO:
// need to respond to settings change somehow as the
// combobox that selected_pnl_calc_type is bound to will be
// gone from this form.
// ditto start of day changes, but this will be a bit more involved
// since we'll need to create a new PnLCalculator when this changes. (infrequent, if ever)
_selected_pnl_calc_type.Value = (startup_data != null && startup_data.calc_type != pnl_calc_type.none) ? startup_data.calc_type : pnl_calc_type.midpoint;
_selected_pnl_calc_type.Changed += pnl_calc_type_changed;
_start_of_day_ts = (startup_data != null && startup_data.start_of_day_time.HasValue) ? startup_data.start_of_day_time.Value : new TimeSpan(16, 30, 0);
var pnl = model.on_pnl_data
.Sample(_POSITION_UPDATE_PERIOD)
.OnDispatcher()
.Subscribe(p => {
if (p != null) {
PnLCalculator calc = new PnLCalculator(p.state.Values);
PnLCalculator calc = new PnLCalculator(p.state.Values, _selected_pnl_calc_type.Value, _start_of_day_ts);
var summary_position_rows = calc.get_summary_position();
_pnl_data.sync_with(summary_position_rows);
_last_pnl_update_time = DateTime.Now;
}
});
pnl_view = CollectionViewSource.GetDefaultView(_pnl_data);
pnl_view.SetSortingCriteria(
new List<SortingCriteria>() {
new SortingCriteria("account", true)
, new SortingCriteria("exchange_string", true)
, new SortingCriteria("symbol", true)
, new SortingCriteria("security_text", true)
}
);
// restore filter state
var fs = startup_data?.filters;
if (startup_data != null) {
account_filter.load_state(fs.account_regex);
exchange_string_filter.load_state(fs.exchange_regex);
symbol_filter.load_state(fs.symbol_regex);
security_filter.load_state(fs.security_regex);
start_position_filter.load_state(fs.start_net_pos);
start_pnl_filter.load_state(fs.start_pnl);
day_long_quantity_filter.load_state(fs.day_long_pos);
day_short_quantity_filter.load_state(fs.day_short_pos);
day_pnl_filter.load_state(fs.day_pnl);
total_net_position_filter.load_state(fs.total_net_pos);
total_pnl_filter.load_state(fs.total_pnl);
pnl_price_filter.load_state(fs.pnl_price);
}
// restore sort state or supply default value
if (startup_data?.sort_criteria?.Any() == true) {
pnl_view.SetSortingCriteria(startup_data.sort_criteria);
} else {
pnl_view.SetSortingCriteria(new List<SortingCriteria>() {
new SortingCriteria(nameof(PnLSummaryRow.account), true)
, new SortingCriteria(nameof(PnLSummaryRow.exchange_string), true)
, new SortingCriteria(nameof(PnLSummaryRow.symbol), true)
, new SortingCriteria(nameof(PnLSummaryRow.security_text), true)
});
}
pnl_view.CollectionChanged += Pnl_view_CollectionChanged;
//Account[] accounts =
#region Create grid filters and load state
#endregion
// setup the main Disposable and
// hook up grid filters
_dispose = Disposable.Create(pnl,
DataGridFilterHelper.hook_filters(pnl_view,
security_filter, pnl_filter,
buy_quantity_filter, sell_quantity_filter,
net_position_filter, weighted_average_buy_filter,
weighted_average_sell_filter, pnl_price_filter,
sod_position_filter, account_filter,
exchange_string_filter, symbol_filter),
account_filter,
exchange_string_filter,
symbol_filter,
security_filter,
start_position_filter,
start_pnl_filter,
day_long_quantity_filter,
day_short_quantity_filter,
day_pnl_filter,
total_net_position_filter,
total_pnl_filter,
pnl_price_filter,
weighted_average_buy_filter,
weighted_average_sell_filter),
WorkLoop.Start("PAndL", _UPDATE_PERIOD, _calculate_pnl)
);
}
protected override void Dispose(bool disposing) {
pnl_view.CollectionChanged -= Pnl_view_CollectionChanged;
}
private void Pnl_view_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) {
_update_totals();
}
private void pnl_calc_type_changed(pnl_calc_type oldval, pnl_calc_type newval) {
_calculate_pnl();
}
protected override void Dispose(bool disposing) {
pnl_view.CollectionChanged -= Pnl_view_CollectionChanged;
_selected_pnl_calc_type.Changed -= pnl_calc_type_changed;
}
void _update_totals() {
if (pnl_view != null) {
total_pnl = pnl_view.Cast<PnLSummaryRow>().Where(r => !Double.IsNaN(r.pnl)).Sum(r => r.pnl);
total_net_pos = pnl_view.Cast<PnLSummaryRow>().Sum(r => r.net_position);
total_buy_qty = pnl_view.Cast<PnLSummaryRow>().Sum(r => r.buy_quantity);
total_sell_qty = pnl_view.Cast<PnLSummaryRow>().Sum(r => r.sell_quantity);
total_aggregate_pnl = pnl_view.Cast<PnLSummaryRow>().Where(r => !Double.IsNaN(r.total_pnl)).Sum(r => r.total_pnl);
total_aggregate_net_pos = pnl_view.Cast<PnLSummaryRow>().Sum(r => r.total_net_position);
total_aggregate_buy_qty = pnl_view.Cast<PnLSummaryRow>().Sum(r => r.day_long_quantity);
total_aggregate_sell_qty = pnl_view.Cast<PnLSummaryRow>().Sum(r => r.day_short_quantity);
}
}
@@ -81,75 +121,111 @@ namespace mbts.spark {
// position update in a while
if (DateTime.Now.Subtract(_last_pnl_update_time) > _UPDATE_PERIOD) {
foreach (var r in _pnl_data) {
r.update_pnl(pnl_calc_type.waterfall);
if (_selected_pnl_calc_type.Value != pnl_calc_type.none) {
r.update_pnl(_selected_pnl_calc_type.Value);
}
}
_update_totals();
}
}
private DateTime _last_pnl_update_time = DateTime.MinValue;
private ObservableCollection<PnLSummaryRow> _pnl_data = new ObservableCollection<PnLSummaryRow>();
#region Properties
public ICollectionView pnl_view { get; }
private double _total_pnl;
public double total_pnl {
public List<pnl_calc_type> pnl_calc_types { get; } = EnumHelper.get_values_except(pnl_calc_type.none, pnl_calc_type.waterfall, pnl_calc_type.bid_or_ask, pnl_calc_type.open, pnl_calc_type.close).ToList();
public pnl_calc_type selected_pnl_calc_type {
get => _selected_pnl_calc_type.Value;
set => _selected_pnl_calc_type.Value = value;
}
public double total_aggregate_pnl {
get {
return _total_pnl;
return _total_aggregate_pnl;
}
set {
_total_pnl = value;
RaisePropertyChanged(nameof(total_pnl));
_total_aggregate_pnl = value;
RaisePropertyChanged();
}
}
private double _total_net_pos;
public double total_net_pos {
get { return _total_net_pos; }
public double total_aggregate_net_pos {
get { return _total_aggregate_net_pos; }
set {
_total_net_pos = value;
RaisePropertyChanged(nameof(total_net_pos));
_total_aggregate_net_pos = value;
RaisePropertyChanged();
}
}
private double _total_buy_qty;
public double total_buy_qty {
get { return _total_buy_qty; }
public double total_aggregate_buy_qty {
get { return _total_aggregate_buy_qty; }
set {
_total_buy_qty = value;
RaisePropertyChanged(nameof(total_buy_qty));
_total_aggregate_buy_qty = value;
RaisePropertyChanged();
}
}
private double _total_sell_qty;
public double total_sell_qty {
get { return _total_sell_qty; }
public double total_aggregate_sell_qty {
get { return _total_aggregate_sell_qty; }
set {
_total_sell_qty = value;
RaisePropertyChanged(nameof(total_sell_qty));
_total_aggregate_sell_qty = value;
RaisePropertyChanged();
}
}
public TimeSpan start_of_day {
get { return _start_of_day_ts; }
}
#region Filters
public IDataGridColumnPersistentFilter<PnLSummaryRow, string> security_filter { get; } = new RegexFilterVM<PnLSummaryRow>(r => r.security_text, nameof(PnLSummaryRow.security_text));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> pnl_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.pnl, nameof(PnLSummaryRow.pnl));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> buy_quantity_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.buy_quantity, nameof(PnLSummaryRow.buy_quantity));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> sell_quantity_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.sell_quantity, nameof(PnLSummaryRow.sell_quantity));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> net_position_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.net_position, nameof(PnLSummaryRow.net_position));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> weighted_average_buy_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.weighted_average_buy, nameof(PnLSummaryRow.weighted_average_buy));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> weighted_average_sell_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.weighted_average_sell, nameof(PnLSummaryRow.weighted_average_sell));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> pnl_price_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.pnl_price, nameof(PnLSummaryRow.pnl_price));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> sod_position_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.sod_position, nameof(PnLSummaryRow.sod_position));
public IDataGridColumnPersistentFilter<PnLSummaryRow, string> account_filter { get; } = new RegexFilterVM<PnLSummaryRow>(r => r.account, nameof(PnLSummaryRow.account));
public IDataGridColumnPersistentFilter<PnLSummaryRow, string> exchange_string_filter { get; } = new RegexFilterVM<PnLSummaryRow>(r => r.exchange_string, nameof(PnLSummaryRow.exchange_string));
public IDataGridColumnPersistentFilter<PnLSummaryRow, string> symbol_filter { get; } = new RegexFilterVM<PnLSummaryRow>(r => r.symbol, nameof(PnLSummaryRow.symbol));
public IDataGridColumnPersistentFilter<PnLSummaryRow, string> security_filter { get; } = new RegexFilterVM<PnLSummaryRow>(r => r.security_text, nameof(PnLSummaryRow.security_text));
public IDataGridColumnPersistentFilter<PnLSummaryRow, IntMinMaxState> start_position_filter { get; } = new IntMinMax<PnLSummaryRow>(r => r.start_net_position, nameof(PnLSummaryRow.start_net_position));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> start_pnl_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.start_pnl, nameof(PnLSummaryRow.start_pnl));
public IDataGridColumnPersistentFilter<PnLSummaryRow, UIntMinMaxState> day_long_quantity_filter { get; } = new UIntMinMax<PnLSummaryRow>(r => r.day_long_quantity, nameof(PnLSummaryRow.day_long_quantity));
public IDataGridColumnPersistentFilter<PnLSummaryRow, UIntMinMaxState> day_short_quantity_filter { get; } = new UIntMinMax<PnLSummaryRow>(r => r.day_short_quantity, nameof(PnLSummaryRow.day_short_quantity));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> day_pnl_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.day_pnl, nameof(PnLSummaryRow.day_pnl));
public IDataGridColumnPersistentFilter<PnLSummaryRow, IntMinMaxState> total_net_position_filter { get; } = new IntMinMax<PnLSummaryRow>(r => r.total_net_position, nameof(PnLSummaryRow.total_net_position));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> total_pnl_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.total_pnl, nameof(PnLSummaryRow.total_pnl));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> pnl_price_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.pnl_price, nameof(PnLSummaryRow.pnl_price));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> weighted_average_buy_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.weighted_average_buy, nameof(PnLSummaryRow.weighted_average_buy));
public IDataGridColumnPersistentFilter<PnLSummaryRow, DoubleMinMaxState> weighted_average_sell_filter { get; } = new DoubleMinMax<PnLSummaryRow>(r => r.weighted_average_sell, nameof(PnLSummaryRow.weighted_average_sell));
public FilterStates get_filters_states() => new FilterStates {
account_regex = account_filter.get_state(),
exchange_regex = exchange_string_filter.get_state(),
symbol_regex = exchange_string_filter.get_state(),
security_regex = security_filter.get_state(),
start_net_pos = start_position_filter.get_state(),
start_pnl = start_pnl_filter.get_state(),
day_long_pos = day_long_quantity_filter.get_state(),
day_short_pos = day_short_quantity_filter.get_state(),
day_pnl = day_pnl_filter.get_state(),
total_net_pos = total_net_position_filter.get_state(),
total_pnl = total_pnl_filter.get_state(),
pnl_price = pnl_price_filter.get_state()
};
#endregion
public List<SortingCriteria> get_sorting_states() => pnl_view.GetSortingCriteria();
#endregion
readonly IBus _bus;
readonly PAndLModel _model;
static readonly TimeSpan _UPDATE_PERIOD = TimeSpan.FromSeconds(1);
static readonly TimeSpan _POSITION_UPDATE_PERIOD = TimeSpan.FromMilliseconds(333);
readonly Property<pnl_calc_type> _selected_pnl_calc_type;
double _total_aggregate_pnl, _total_aggregate_net_pos, _total_aggregate_buy_qty, _total_aggregate_sell_qty;
TimeSpan _start_of_day_ts;
DateTime _last_pnl_update_time = DateTime.MinValue;
ObservableCollection<PnLSummaryRow> _pnl_data = new ObservableCollection<PnLSummaryRow>();
}
@@ -25,13 +25,19 @@
<Grid>
<Grid.RowDefinitions>
<!-- Table -->
<RowDefinition Height="Auto"/>
<RowDefinition />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<c:DataGridEx Grid.Row="0" Grid.Column="0" x:Name="_grid" IsReadOnly="True" BorderThickness="0" GridLinesVisibility="None" CanUserSortColumns="True" SelectionUnit="FullRow"
<ComboBox Grid.Row="0"
ItemsSource="{Binding pnl_calc_types}"
SelectedItem="{Binding selected_pnl_calc_type}"
ItemTemplate="{StaticResource EnumDescriptionTemplate}">
</ComboBox>
<c:DataGridEx Grid.Row="1" Grid.Column="0" x:Name="_grid" IsReadOnly="True" BorderThickness="0" GridLinesVisibility="None" CanUserSortColumns="True" SelectionUnit="FullRow"
ItemsSource="{Binding pnl_view}" uc:DataGridBehavior.NotifyColumnsOfSorting="True">
<DataGrid.Columns>
<DataGridTextColumn x:Name="account" Header="Account" Binding="{Binding account}" IsReadOnly="true"
@@ -58,49 +64,85 @@
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.security_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource RegexTemplate}"
/>
<DataGridTextColumn x:Name="sod" Header="SOD" Binding="{Binding sod_position}" IsReadOnly="true"
<DataGridTextColumn x:Name="start_net_pos" Header="Start Net Pos" Binding="{Binding start_net_position}" IsReadOnly="true"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.sod_position_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.sod_position_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.sod_position_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.Filter="{Binding DataContext.start_position_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.start_position_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.start_position_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="buy_qty" Header="Buy Qty" Binding="{Binding buy_quantity}" IsReadOnly="true"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.buy_quantity_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.buy_quantity_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.buy_quantity_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="sell_qty" Header="Sell Qty" Binding="{Binding sell_quantity}" IsReadOnly="true"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.sell_quantity_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.sell_quantity_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.sell_quantity_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="net_pos" Header="Net Pos" Binding="{Binding net_position}" IsReadOnly="true"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.net_position_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.net_position_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.net_position_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="pnl" Header="PnL" IsReadOnly="true" SortMemberPath="pnl"
c:DataGridFilterProperties.Filter="{Binding DataContext.pnl_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.pnl_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.pnl_filter.open, Source={uc:DirectReference _grid}}"
<DataGridTextColumn x:Name="start_pnl" Header="Start PnL" IsReadOnly="true" SortMemberPath="start_pnl"
c:DataGridFilterProperties.Filter="{Binding DataContext.start_pnl_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.start_pnl_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.start_pnl_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="pnl"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="start_pnl"/>
<Binding Path="security"/>
</MultiBinding>
</DataGridTextColumn.Binding>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextAlignment" Value="Right" />
<Setter Property="Background" Value="{Binding pnl, Converter={StaticResource PnLBackgroundColorConverter}}" />
<Setter Property="Background" Value="{Binding start_pnl, Converter={StaticResource PnLBackgroundColorConverter}}" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn x:Name="day_long" Header="Day Long" Binding="{Binding day_long_quantity}" IsReadOnly="true"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.day_long_quantity_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.day_long_quantity_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.day_long_quantity_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="day_short" Header="Day Short" Binding="{Binding day_short_quantity}" IsReadOnly="true"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.day_short_quantity_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.day_short_quantity_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.day_short_quantity_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="day_pnl" Header="Day PnL" IsReadOnly="true" SortMemberPath="day_pnl"
c:DataGridFilterProperties.Filter="{Binding DataContext.day_pnl_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.day_pnl_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.day_pnl_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="day_pnl"/>
<Binding Path="security"/>
</MultiBinding>
</DataGridTextColumn.Binding>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextAlignment" Value="Right" />
<Setter Property="Background" Value="{Binding day_pnl, Converter={StaticResource PnLBackgroundColorConverter}}" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn x:Name="total_net_pos" Header="Total Net Pos" Binding="{Binding total_net_position}" IsReadOnly="true"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.total_net_position_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.total_net_position_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.total_net_position_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}"
/>
<DataGridTextColumn x:Name="total_pnl" Header="Total PnL" IsReadOnly="true" SortMemberPath="total_pnl"
c:DataGridFilterProperties.Filter="{Binding DataContext.total_pnl_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.total_pnl_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.total_pnl_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="total_pnl"/>
<Binding Path="security"/>
</MultiBinding>
</DataGridTextColumn.Binding>
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="TextAlignment" Value="Right" />
<Setter Property="Background" Value="{Binding total_pnl, Converter={StaticResource PnLBackgroundColorConverter}}" />
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
@@ -113,24 +155,17 @@
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="pnl_price"/>
<Binding Path="security.ContractSpec"/>
<Binding Path="security"/>
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
<!-- we are hiding these until we have toggle on/off via settings
<DataGridTextColumn x:Name="avg_buy" Header="AvgBuy" Binding="{Binding weighted_average_buy, Converter={StaticResource DoubleWithNaNHiddenConverter}}" IsReadOnly="true" SortMemberPath="weighted_average_buy"
ElementStyle="{StaticResource RightAlignedColumn}"
c:DataGridFilterProperties.Filter="{Binding DataContext.weighted_average_buy_filter, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterActive="{Binding DataContext.weighted_average_buy_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.weighted_average_buy_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<!--
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="weighted_average_buy"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</DataGridTextColumn.Binding>
-->
</DataGridTextColumn>
<DataGridTextColumn x:Name="avg_sell" Header="AvgSell" Binding="{Binding weighted_average_sell, Converter={StaticResource DoubleWithNaNHiddenConverter}}" IsReadOnly="true" SortMemberPath="weighted_average_sell"
ElementStyle="{StaticResource RightAlignedColumn}"
@@ -138,26 +173,19 @@
c:DataGridFilterProperties.FilterActive="{Binding DataContext.weighted_average_sell_filter.active, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterOpen="{Binding DataContext.weighted_average_sell_filter.open, Source={uc:DirectReference _grid}}"
c:DataGridFilterProperties.FilterTemplate="{StaticResource DoubleMinMaxTemplate}">
<!--
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="weighted_average_sell"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</DataGridTextColumn.Binding>
-->
</DataGridTextColumn>
-->
</DataGrid.Columns>
</c:DataGridEx>
<StatusBar Grid.Row="1" Grid.Column="0" DockPanel.Dock="Bottom">
<StatusBar Grid.Row="2" Grid.Column="0" DockPanel.Dock="Bottom">
<StatusBarItem DockPanel.Dock="Right">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Total PnL: "/>
<TextBlock Grid.Column="1" Text="{Binding total_pnl, Converter={StaticResource DoubleWithNaNHiddenConverter}}" />
<TextBlock Grid.Column="0" Text="Aggregate PnL: "/>
<TextBlock Grid.Column="1" Text="{Binding total_aggregate_pnl, Converter={StaticResource DoubleWithNaNHiddenConverter}}" />
</Grid>
</StatusBarItem>
<StatusBarItem DockPanel.Dock="Right">
@@ -169,8 +197,8 @@
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Total Net Pos: "/>
<TextBlock Grid.Column="1" Text="{Binding total_net_pos}"/>
<TextBlock Grid.Column="0" Text="Aggregate Net Pos: "/>
<TextBlock Grid.Column="1" Text="{Binding total_aggregate_net_pos}"/>
</Grid>
</StatusBarItem>
<StatusBarItem DockPanel.Dock="Right">
@@ -182,8 +210,8 @@
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Total Sell Qty: "/>
<TextBlock Grid.Column="1" Text="{Binding total_sell_qty}"/>
<TextBlock Grid.Column="0" Text="Aggregate Sell Qty: "/>
<TextBlock Grid.Column="1" Text="{Binding total_aggregate_sell_qty}"/>
</Grid>
</StatusBarItem>
<StatusBarItem DockPanel.Dock="Right">
@@ -195,8 +223,8 @@
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="Total Buy Qty: "/>
<TextBlock Grid.Column="1" Text="{Binding total_buy_qty}"/>
<TextBlock Grid.Column="0" Text="Aggregate Buy Qty: "/>
<TextBlock Grid.Column="1" Text="{Binding total_aggregate_buy_qty}"/>
</Grid>
</StatusBarItem>
<StatusBarItem />
@@ -14,26 +14,31 @@ namespace mbts.spark {
internal class PAndLWindow : SparkWindow<PAndLWindowFactory.PAndLStartupData>, ISharedWindow {
const string _window_type = "PAndL", PNL_THREAD_ID = "PnL";
PAndLWindowFactory.PAndLStartupData _state;
PAndLWindowFactory.PAndLStartupData _startup_data;
PAndLModel _model;
PAndLView _view;
PAndLVM _vm;
PAndLWindowFactory _factory;
public PAndLWindow(PAndLModel model, PAndLWindowFactory factory, IBus bus, PAndLWindowFactory.PAndLStartupData state, ImageSource Icon ) : base("P&L", bus, factory, SparkCommands.ShowPAndL.icon) {
public PAndLWindow(PAndLModel model, PAndLWindowFactory factory, IBus bus, PAndLWindowFactory.PAndLStartupData startup_data, ImageSource Icon ) : base("P&L", bus, factory, SparkCommands.ShowPAndL.icon) {
_model = model;
_factory = factory;
_state = state;
_startup_data = startup_data;
}
public override string window_type => _window_type;
public override PAndLWindowFactory.PAndLStartupData SaveState => _state =
new PAndLWindowFactory.PAndLStartupData();
public override PAndLWindowFactory.PAndLStartupData SaveState => _startup_data =
new PAndLWindowFactory.PAndLStartupData(
_vm.get_sorting_states(),
_vm.get_filters_states(),
_vm.selected_pnl_calc_type,
_vm.start_of_day
);
public override UIElement Content => _view;
public override double MinWidth => 894;
public string thread_id => PNL_THREAD_ID;
public void thread_init() {
_vm = new PAndLVM(_bus, _model, _state);
_vm = new PAndLVM(_bus, _model, _startup_data);
_view = new PAndLView(_vm);
_view.DataContext = _vm;
}
@@ -77,20 +77,27 @@ namespace mbts.spark {
class PnLCalculator {
readonly IEnumerable<PnLData> _data;
readonly pnl_calc_type _calc_type;
readonly DateTime _start_of_trading_day_utc;
public PnLCalculator(IEnumerable<PnLData> data) {
public PnLCalculator(IEnumerable<PnLData> data, pnl_calc_type calc_type, TimeSpan start_of_day_ts) {
_data = data;
_calc_type = calc_type;
// Note that this isn't the acutal start of the trading day
// but it's close enough for pnl purposes.
// In reality, instruments have different schedules
_start_of_trading_day_utc = DateTime.Now.Date.Add(start_of_day_ts).AddDays(-1).ToUniversalTime();
}
public IEnumerable<PnLSummaryRow> get_summary_position() {
return (from pnl_item in _data
group pnl_item by (pnl_item.account, pnl_item.exchange, pnl_item.symbol, pnl_item.security, pnl_item.sec_md) into grouping
let start_of_day = _get_start_of_day(grouping.Key.symbol)
select new PnLSummaryRow(grouping.Key,
grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => y.buy_quantity),
grouping.Where(y => y.fill.Timestamp.ToDateTime() >= start_of_day).Sum(y => y.sell_quantity),
grouping.Sum(y => y.buy_quantity - y.sell_quantity),
grouping.Where(y => y.fill.Timestamp.ToDateTime() < start_of_day).Sum(y => y.buy_quantity - y.sell_quantity),
/* let start_of_day = _get_start_of_day(grouping.Key.symbol) */
select new PnLSummaryRow(_calc_type, _start_of_trading_day_utc, grouping.Key,
grouping.Where(y => y.fill.Timestamp.ToDateTime() >= _start_of_trading_day_utc).Sum(y => (uint)y.buy_quantity),
grouping.Where(y => y.fill.Timestamp.ToDateTime() >= _start_of_trading_day_utc).Sum(y => (uint)y.sell_quantity),
grouping.Sum(y => (int)(y.buy_quantity - y.sell_quantity)),
grouping.Where(y => y.fill.Timestamp.ToDateTime() < _start_of_trading_day_utc).Sum(y => (int)(y.buy_quantity - y.sell_quantity)),
grouping.weighted_average(y => y.fill.LastPrice, y => y.buy_quantity),
grouping.weighted_average(y => y.fill.LastPrice, y => y.sell_quantity),
grouping.Select(i => i.fill)
@@ -98,21 +105,23 @@ namespace mbts.spark {
);
}
public static double get_driver(SecurityMD sec_md, pnl_calc_type pnl_request) {
ulong unused = 0;
sec_md.md.get_bbo(ref unused, out NativePriceSize bid, out NativePriceSize ask);
sec_md.md.get_last_trade(ref unused, out NativePriceSize last, out DateTime unused1, out ulong unused2);
public static bool get_driver(ref ulong bbo_time, ref ulong last_trade_time, SecurityMD sec_md, pnl_calc_type pnl_request, ref double driver_price) {
// check with eric as I'm not sure if i was every querying md correctly
if (!sec_md.md.get_bbo(ref bbo_time, out NativePriceSize bid, out NativePriceSize ask)) return false;
if (!sec_md.md.get_last_trade(ref last_trade_time, out NativePriceSize last, out DateTime unused1, out ulong unused2)) return false;
if (pnl_request.HasFlag(pnl_calc_type.waterfall)) {
// last price is available and withing range of available bid and ask
if (!Double.IsNaN(last.price) && last.price >= bid.price && last.price <= ask.price) {
return last.price;
driver_price = last.price;
return true;
}
double mid = TickUtils.mid_tick(sec_md.security.ContractSpec, bid.price, ask.price);
// last price is not valid, so try the mid
if (!Double.IsNaN(mid)) {
return mid;
driver_price = mid;
return true;
}
// last bid
@@ -120,9 +129,11 @@ namespace mbts.spark {
if (!Double.IsNaN(last.price) && !Double.IsNaN(bid.price) && Double.IsNaN(ask.price)) {
// if last >= bid then last else bid
if (last.price >= bid.price) {
return last.price;
driver_price = last.price;
return true;
} else {
return bid.price;
driver_price = bid.price;
return true;
}
}
@@ -131,15 +142,18 @@ namespace mbts.spark {
if (!Double.IsNaN(last.price) && !Double.IsNaN(ask.price) && Double.IsNaN(bid.price)) {
// if last <= ask then last else ask
if (last.price <= ask.price) {
return last.price;
driver_price = last.price;
return true;
} else {
return ask.price;
driver_price = ask.price;
return true;
}
}
// last only
if (!Double.IsNaN(last.price)) {
return last.price;
driver_price = last.price;
return true;
}
// indicative, no support yet
@@ -148,36 +162,43 @@ namespace mbts.spark {
if ((!Double.IsNaN(bid.price) || !Double.IsNaN(ask.price)) && !Double.IsNaN(sec_md.md.settlement_price)) {
// if bid and no ask and settle and bid > Settle
if (!Double.IsNaN(bid.price) && Double.IsNaN(ask.price) && !Double.IsNaN(sec_md.md.settlement_price) && bid.price > sec_md.md.settlement_price) {
return bid.price;
driver_price = bid.price;
return true;
}
// if ask and no bid and settle and ask < Settle
if (!Double.IsNaN(ask.price) && Double.IsNaN(bid.price) && !Double.IsNaN(sec_md.md.settlement_price) && ask.price < sec_md.md.settlement_price) {
return ask.price;
driver_price = ask.price;
return true;
}
}
// Settlement
// neither bid or ask are available
if (!Double.IsNaN(sec_md.md.settlement_price)) {
return sec_md.md.settlement_price;
driver_price = sec_md.md.settlement_price;
return true;
}
// Close
return sec_md.md.close_price;
driver_price = sec_md.md.close_price;
return true;
} // end waterfall
if (pnl_request.HasFlag(pnl_calc_type.last)) return last.price;
if (pnl_request.HasFlag(pnl_calc_type.mid)) return TickUtils.mid_tick(sec_md.security.ContractSpec, bid.price, ask.price);
if (pnl_request.HasFlag(pnl_calc_type.open)) return sec_md.md.open_price;
if (pnl_request.HasFlag(pnl_calc_type.close)) return sec_md.md.close_price;
if (pnl_request.HasFlag(pnl_calc_type.settle)) return sec_md.md.settlement_price;
return Double.NaN;
if (pnl_request.HasFlag(pnl_calc_type.last)) { driver_price = last.price; return true; }
// note that bid_or_ask is not considered here since this method only
// supports returning a single driver price; see update_pnl
if (pnl_request.HasFlag(pnl_calc_type.midpoint)) { driver_price = TickUtils.mid_tick(sec_md.security.ContractSpec, bid.price, ask.price); return true; }
if (pnl_request.HasFlag(pnl_calc_type.open)) { driver_price = sec_md.md.open_price; return true; }
if (pnl_request.HasFlag(pnl_calc_type.close)) { driver_price = sec_md.md.close_price; return true; }
if (pnl_request.HasFlag(pnl_calc_type.settle)) { driver_price = sec_md.md.settlement_price; return true; }
driver_price = Double.NaN;
return false;
}
public static double get_pnl(double bid_for_long, double ask_for_short, FillImmutable fill, double cpp) {
if (fill.Side == Side.Buy) { return _get_long_pnl(bid_for_long, fill.LastPrice, fill.LastShares, cpp); }
if (fill.Side == Side.Sell) { return _get_short_pnl(ask_for_short, fill.LastPrice, fill.LastShares, cpp); }
if (fill.Side == Side.Buy && !Double.IsNaN(bid_for_long)) { return _get_long_pnl(bid_for_long, fill.LastPrice, fill.LastShares, cpp); }
if (fill.Side == Side.Sell && !Double.IsNaN(ask_for_short)) { return _get_short_pnl(ask_for_short, fill.LastPrice, fill.LastShares, cpp); }
return Double.NaN;
}
@@ -197,10 +218,6 @@ namespace mbts.spark {
return (price - driver) * quantity * cpp;
}
private static DateTime _get_start_of_day(string symbool) {
// I rekcon this will change according to the symbol's session
return DateTime.Today;
}
}
}
+10 -2
View File
@@ -1,18 +1,26 @@
using bts.api;
using bts.api.orderman;
using System;
using System.ComponentModel;
namespace mbts.spark {
[Flags]
public enum pnl_calc_type {
none = 0,
[Description("Last Tradeable Price Avalanche")]
waterfall = 1,
[Description("Last")]
last = 2,
bid_and_ask = 4,
mid = 8,
[Description("Bid/Ask")]
bid_or_ask = 4,
[Description("Midpoint")]
midpoint = 8,
[Description("Open")]
open = 16,
[Description("Close")]
close = 32,
[Description("Settle")]
settle = 64
}
@@ -12,70 +12,106 @@ namespace mbts.spark {
internal class PnLSummaryRow : ViewModelBase, IEquatable<PnLSummaryRow> {
DateTime _start_of_day;
(string account, Venue? exchange, string symbol, SecurityImmutable? security, SecurityMD? sec_md) key;
double _buy_quantity, _sell_quantity, _net_position, _sod_position, _pnl, _pnl_price, _weighted_average_buy, _weighted_average_sell;
int _start_net_position, _total_net_position;
uint _day_long_quantity, _day_short_quantity;
double _total_pnl, _sod_pnl, _start_pnl, _pnl_price, _weighted_average_buy, _weighted_average_sell;
IEnumerable<FillImmutable> _fills;
//List<MarketSchedule> _schedules = new List<MarketSchedule>() { MarketSchedule.es_schedule };
ulong _bbo_ref, _last_ref;
double _driver;
static readonly Dictionary<string, double> cpp_dict = config.Configuration.get<bts.config.CppConfig>().cpp_entry;
public PnLSummaryRow((string, Venue?, string, SecurityImmutable?, SecurityMD?) key,
double buy_quant, double sell_quant, double net_pos, double sod_pos, double wavg_buy, double wavg_sell, IEnumerable<FillImmutable> fills) {
public PnLSummaryRow(pnl_calc_type calc_type,
DateTime start_of_day,
(string, Venue?, string, SecurityImmutable?, SecurityMD?) key,
uint day_buy_quant, uint day_sell_quant, int net_pos, int sod_pos, double wavg_buy, double wavg_sell, IEnumerable<FillImmutable> fills) {
this._start_of_day = start_of_day;
this.key = key;
buy_quantity = buy_quant;
sell_quantity = sell_quant;
net_position = net_pos;
sod_position = sod_pos;
day_long_quantity = day_buy_quant;
day_short_quantity = day_sell_quant;
total_net_position = net_pos;
start_net_position = sod_pos;
weighted_average_buy = wavg_buy;
weighted_average_sell = wavg_sell;
_fills = fills;
// set the initial pnl and pnl_price when there has been a
// position update i.e. this constructor
update_pnl(pnl_calc_type.waterfall);
update_pnl(calc_type);
}
private double _get_cpp_for_security(SecurityImmutable s) {
if (s.security_type() == SecurityType.Spread) {
var distinct_cpps = s.Spread.Legs
.Select(l => l.Security.ContractSpec.CashPerPoint)
.Select(l => get_cpp_for_symbol(l.Security))
.Distinct();
bool all_legs_have_same_cpp = distinct_cpps.Count() < 2;
if (all_legs_have_same_cpp) {
return s.Spread.Legs.First().Security.ContractSpec.CashPerPoint;
return distinct_cpps.First();
} else {
Logger.error(bts.log.Subsystem.Ui,
Logger.error(bts.log.Subsystem.Ui,
$"Security {s} contains legs with the following cash multipliers: { string.Join(",", distinct_cpps.Select(d => d.ToString())) } ");
return Double.NaN;
}
} else {
return get_cpp_for_symbol(s);
}
// local function for looking up cpp for a single SecurityImmutable
double get_cpp_for_symbol(SecurityImmutable si) {
if (cpp_dict.TryGetValue(si.Symbol, out double cpp_out)) {
return cpp_out;
} else {
Logger.error(bts.log.Subsystem.Ui, $"No cash multiplier found for Security {si}, Symbol {si.Symbol}");
}
return double.NaN;
}
return s.ContractSpec.CashPerPoint;
}
public void update_pnl(pnl_calc_type pnl_request) {
if (key.sec_md.HasValue) {
double cpp = _get_cpp_for_security(key.security.Value);
if (pnl_request.HasFlag(pnl_calc_type.bid_and_ask)) {
ulong unused = 0;
key.sec_md.Value.md.get_bbo(ref unused, out NativePriceSize bid, out NativePriceSize ask);
if (pnl_request.HasFlag(pnl_calc_type.bid_or_ask)) {
key.sec_md.Value.md.get_bbo(ref _bbo_ref, out NativePriceSize bid, out NativePriceSize ask);
double summary_pnl = 0.0;
double start_pnl_total = 0.0;
double day_pnl_total = 0.0;
foreach (var fill in _fills) {
double _tick_pnl = PnLCalculator.get_pnl(bid.price, ask.price, fill, cpp);
summary_pnl += _tick_pnl;
if (fill.Timestamp.ToDateTime() >= _start_of_day) {
day_pnl_total += _tick_pnl;
} else {
start_pnl_total += _tick_pnl;
}
}
pnl = summary_pnl;
total_pnl = summary_pnl;
day_pnl = day_pnl_total;
start_pnl = start_pnl_total;
pnl_price = Double.NaN;
} else {
double driver = PnLCalculator.get_driver(key.sec_md.Value, pnl_request);
double summary_pnl = 0.0;
foreach (var fill in _fills) {
double _tick_pnl = PnLCalculator.get_pnl(driver, fill, cpp);
summary_pnl += _tick_pnl;
if (PnLCalculator.get_driver(ref _bbo_ref, ref _last_ref, key.sec_md.Value, pnl_request, ref _driver)) {
double summary_pnl = 0.0;
double start_pnl_total = 0.0;
double day_pnl_total = 0.0;
foreach (var fill in _fills) {
double _tick_pnl = PnLCalculator.get_pnl(_driver, fill, cpp);
summary_pnl += _tick_pnl;
if (fill.Timestamp.ToDateTime() >= _start_of_day) {
day_pnl_total += _tick_pnl;
} else {
start_pnl_total += _tick_pnl;
}
}
total_pnl = summary_pnl;
day_pnl = day_pnl_total;
start_pnl = start_pnl_total;
pnl_price = _driver;
}
pnl = summary_pnl;
pnl_price = driver;
}
}
}
@@ -89,9 +125,9 @@ namespace mbts.spark {
key.exchange == other.exchange &&
key.security == other.security &&
key.symbol == other.symbol &&
buy_quantity == other.buy_quantity &&
sell_quantity == other.sell_quantity &&
pnl == other.pnl;
day_long_quantity == other.day_long_quantity &&
day_short_quantity == other.day_short_quantity &&
total_pnl == other.total_pnl;
}
public override int GetHashCode() {
@@ -104,7 +140,7 @@ namespace mbts.spark {
}
public override string ToString() {
return $"account: {account} exchange: {exchange_string} symbol: {symbol} security: {security_text} buy_quantity: {buy_quantity} sell_quantity: {sell_quantity} pnl: {pnl}";
return $"account: {account} exchange: {exchange_string} symbol: {symbol} security: {security_text} buy_quantity: {day_long_quantity} sell_quantity: {day_short_quantity} pnl: {total_pnl}";
}
public string account {
@@ -140,56 +176,77 @@ namespace mbts.spark {
set => ignore();
}
public double buy_quantity {
get => _buy_quantity;
public int start_net_position {
get => _start_net_position;
set {
if (_buy_quantity != value) {
_buy_quantity = value;
RaisePropertyChanged(nameof(buy_quantity));
if (_start_net_position != value) {
_start_net_position = value;
RaisePropertyChanged(nameof(start_net_position));
}
}
}
public double start_pnl {
get => _start_pnl;
set {
if (_start_pnl != value) {
_start_pnl = value;
RaisePropertyChanged();
}
}
}
public uint day_long_quantity {
get => _day_long_quantity;
set {
if (_day_long_quantity != value) {
_day_long_quantity = value;
RaisePropertyChanged(nameof(day_long_quantity));
}
}
}
public uint day_short_quantity {
get => _day_short_quantity;
set {
if (_day_short_quantity != value) {
_day_short_quantity = value;
RaisePropertyChanged(nameof(day_short_quantity));
}
}
}
public double day_pnl {
get => _sod_pnl;
set {
if (_sod_pnl != value) {
_sod_pnl = value;
RaisePropertyChanged();
}
}
}
public double sell_quantity {
get => _sell_quantity;
public int total_net_position {
get => _total_net_position;
set {
if (_sell_quantity != value) {
_sell_quantity = value;
RaisePropertyChanged(nameof(sell_quantity));
if (_total_net_position != value) {
_total_net_position = value;
RaisePropertyChanged(nameof(total_net_position));
}
}
}
public double sod_position {
get => _sod_position;
public double total_pnl {
get => _total_pnl;
set {
if (_sod_position != value) {
_sod_position = value;
RaisePropertyChanged(nameof(sod_position));
if (_total_pnl != value) {
_total_pnl = value;
RaisePropertyChanged(nameof(total_pnl));
}
}
}
public double net_position {
get => _net_position;
set {
if (_net_position != value) {
_net_position = value;
RaisePropertyChanged(nameof(net_position));
}
}
}
public double pnl {
get => _pnl;
set {
if (_pnl != value) {
_pnl = value;
RaisePropertyChanged(nameof(pnl));
}
}
}
public double pnl_price {
get => _pnl_price;
@@ -221,6 +278,9 @@ namespace mbts.spark {
}
}
//public IEnumerable<FillImmutable> sod_fills => _fills.Where(f => f.Timestamp.ToDateTime() >= _start_of_day);
//public IEnumerable<FillImmutable> pos_fills => _fills.Where(f => f.Timestamp.ToDateTime() < _start_of_day);
}
@@ -76,7 +76,7 @@ namespace mbts.spark {
_status_store = CellFactory.create(this, _book_vm.columns.status_column, nameof(status), r => _order.status(), r => r._status_store);
_last_msg_store = CellFactory.create(this, _book_vm.columns.last_message_column, nameof(last_msg), r => _order.last_msg(), r => r._last_msg_store);
//
string format_price(double v) => _security.HasValue ? _security.Value.ContractSpec.format(v) :
string format_price(double v) => _security.HasValue ? _security.Value.format(v) :
Math.Round(v, _unknown_security_price_num_fractional_digits, MidpointRounding.AwayFromZero).ToString(_unknown_security_price_format_string);
string format_date(DateTime v) => $"{v:M/d} {v:h:mm:ss.fff tt}";
string format_sub_type(OrderSubType v) {
@@ -41,7 +41,7 @@ namespace mbts.spark {
public static GlyphContext get_glyph_context(OrderBookRowVM r) => r.is_child ? _child_glyph_context : TextUtils.StandardGlyphContext;
public static Brush get_side_brush(OrderBookRowVM r) => r.side == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask;
public static BindingBase get_font_weight_binding() => new Binding(nameof(OrderBookRowVM.is_child)) { Converter = _font_weight_converter };
public static string format_price(OrderBookRowVM row, double price) => row.security.HasValue ? row.security.Value.ContractSpec.format(price) : row.price.ToString();
public static string format_price(OrderBookRowVM row, double price) => row.security.HasValue ? row.security.Value.format(price) : row.price.ToString();
}
abstract class OrderbookColumnBase : ColumnBase<Columns>, IKeyedColumn<Columns>, IFilterableColumn {
@@ -61,7 +61,27 @@ namespace mbts.spark.utilities {
if (value > max) return max;
return value;
}
public static bool is_within_range(double min, double max, double value) =>
value >= min && value <= max;
public static int RoundFractionalUnits(double value, double fractional_unit) =>
(int)Math.Round(value / fractional_unit);
public static bool is_int(double d) =>
epsilon_equals(d, (int)d);
public static double factor_out(double value, double factor) =>
factor_out(value, factor, out int _);
public static double factor_out(double value, double factor, out int n_factors_removed) {
n_factors_removed = 0;
double quotient = value / factor;
while (is_int(quotient)) {
value = quotient;
++n_factors_removed;
quotient /= factor;
}
return value;
}
}
}
@@ -15,11 +15,13 @@ namespace mbts.spark
public static class Defaults {
public static ContractSpecification ContractSpecification => new ContractSpecification { CashPerPoint = 1.0, LowTick = 0.01, HighTick = 0.01, PriceBreak = double.MaxValue, PriceMultiplier = 1.0 };
public static GLBXExchangeData GlbxExchangeData => new GLBXExchangeData { MainFraction = 1000, PriceDisplayFormat = 3 };
public static readonly ContractSpecificationImmutable ContractSpecificationImmutable = new ContractSpecificationImmutable(ContractSpecification);
public static Security Security => new Security {
Symbol = string.Empty,
Exchange = Venue.Bts,
ContractSpec = ContractSpecification,
Glbx = GlbxExchangeData
};
public static readonly SecurityImmutable SecurityImmutable = new SecurityImmutable(Security);
}
+1 -1
View File
@@ -1 +1 @@
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cpp_config.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cpp_config.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;metrics/metrics.cpp;metrics/system_metrics.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp)
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/services/AdminService.proto;api/services/ApiUnitTestService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cpp_config.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cpp_config.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;md/test/synthetic_book_merge_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/catch_test_runner.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SecureLogon.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp)