diff --git a/.vscode/launch.json b/.vscode/launch.json index 34727391a..36fdd03c8 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -16,7 +16,7 @@ "name": "Client Attach", "type": "clr", "request": "attach", - "processName": "${command:pickProcess}" + "processId":"${command:pickProcess}" }, { "name": "Docker Launch", diff --git a/.vscode/settings.json b/.vscode/settings.json index 5a578c9d3..9b216393c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,5 @@ { - "files.associations": { +"files.associations": { "utility": "cpp", "initializer_list": "cpp", "list": "cpp", @@ -7,7 +7,10 @@ "vector": "cpp", "xhash": "cpp", "xstring": "cpp", + "system_error": "cpp", + "array": "cpp", + "string_view": "cpp" "xutility": "cpp", "*.ipp": "cpp" - } +} } \ No newline at end of file diff --git a/src/client/spark/App.xaml.cs b/src/client/spark/App.xaml.cs index 59972bc28..a44a6eaaf 100644 --- a/src/client/spark/App.xaml.cs +++ b/src/client/spark/App.xaml.cs @@ -90,13 +90,13 @@ namespace mbts.ui.shell else { // Second instance. Activate the main window and return NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, (WM)NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero); - Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Starting a second shell is not allowed. Attempting to bring the original shell to the foreground."); + Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Starting a second shell is not allowed. Attempting to bring the original shell to the foreground."); } return 0; } } catch (AbandonedMutexException ame) { - Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Shell mutex was abandoned. Releasing the mutex and trying again. \n" + ame.ToString()); + Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "Shell mutex was abandoned. Releasing the mutex and trying again. \n" + ame.ToString()); _mutex.ReleaseMutex(); // Try agai until stack overflow return Run(); diff --git a/src/client/spark/Spark.csproj b/src/client/spark/Spark.csproj index b9f5cc22a..2258a5cfe 100644 --- a/src/client/spark/Spark.csproj +++ b/src/client/spark/Spark.csproj @@ -22,7 +22,6 @@ - diff --git a/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs b/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs index 6a6c22bda..9cdf875da 100644 --- a/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs @@ -208,7 +208,7 @@ namespace mbts // Some defenses against crashing when the source collection is if (!src.is_distinct(comp)) { Logger.assert_d(false); - Logger.error(bts.log.Subsystem.ui, "sync_with requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name)); + Logger.error(bts.log.Subsystem.Ui, "sync_with requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name)); } // First remove anything not in the destination @@ -235,7 +235,7 @@ namespace mbts ++d; } } catch (Exception ex) { - Logger.error(bts.log.Subsystem.ui, "sync_with error (Element T is {0}): {1}".fmt(typeof(T), ex)); + Logger.error(bts.log.Subsystem.Ui, "sync_with error (Element T is {0}): {1}".fmt(typeof(T), ex)); throw ex; } } @@ -244,7 +244,7 @@ namespace mbts public static bool sync_with_setwise(this ObservableCollection dest, IEnumerable src, IEqualityComparer comp) { if (!src.is_distinct(comp)) { Logger.assert_d(false); - Logger.error(bts.log.Subsystem.ui, "sync_with_setwise requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name)); + Logger.error(bts.log.Subsystem.Ui, "sync_with_setwise requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name)); } IEnumerable added, removed; dest.difference(src, out added, out removed, comp); diff --git a/src/client/spark/core/GlobalExtensions/TickExtensions.cs b/src/client/spark/core/GlobalExtensions/TickExtensions.cs index 775de1783..bf2ca2fc5 100644 --- a/src/client/spark/core/GlobalExtensions/TickExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/TickExtensions.cs @@ -44,11 +44,13 @@ namespace mbts public static double tickup(this RegionalTickFactors regional_tick, double input) { return regional_tick.tickup(input, 1); } public static double tickup(this RegionalTickFactors regional_tick, double input, uint count) { - if (DoubleHelper.IsNaNOrInfinity(input)) return input; + if (DoubleHelper.IsNaNOrInfinity(input) || count == 0) return input; double val, tuf; if (input < regional_tick.low_tick_inclusive_end) { tuf = regional_tick.low_tick.tick_unit_frac(); - input -= input % tuf; + double ieeer = Math.IEEERemainder(input, tuf); + input -= ieeer; + if (ieeer < -_precision_const) count--; val = input + tuf * count; if (val > regional_tick.low_tick_inclusive_end) { count -= (uint)Math.Ceiling((regional_tick.low_tick_inclusive_end - input) / tuf); @@ -57,12 +59,15 @@ namespace mbts } } else { tuf = regional_tick.high_tick.tick_unit_frac(); - input -= input % tuf; + double ieeer = Math.IEEERemainder(input, tuf); + if (Math.Abs(ieeer) <= _precision_const) input -= ieeer; val = input + tuf * count; } return _round_tick(tuf, val); } + private const double _precision_const = 0.000000001; + public static double tickdown(this TickFactors tick, double input) { return tick.tickdown(input, 1); } public static double tickdown(this TickFactors tick, double input, uint count) { if (DoubleHelper.IsNaNOrInfinity(input)) return input; @@ -75,24 +80,33 @@ namespace mbts public static double tickdown(this RegionalTickFactors regional_tick, double input) { return regional_tick.tickdown(input, 1); } public static double tickdown(this RegionalTickFactors regional_tick, double input, uint count) { - if (DoubleHelper.IsNaNOrInfinity(input)) return input; + if (DoubleHelper.IsNaNOrInfinity(input) || count == 0) return input; double val, tuf; if (input > regional_tick.low_tick_inclusive_end) { tuf = regional_tick.high_tick.tick_unit_frac(); - double remainder = input % tuf; - if (remainder > 0) input += tuf - remainder; + double ieeer = Math.IEEERemainder(input, tuf); + input -= ieeer; + if (ieeer > _precision_const) count--; val = input - count * tuf; if (val < regional_tick.low_tick_inclusive_end) { count -= (uint)Math.Ceiling((input - regional_tick.low_tick_inclusive_end) / tuf); tuf = regional_tick.low_tick.tick_unit_frac(); - return regional_tick.low_tick_inclusive_end - tuf * count; + val = regional_tick.low_tick_inclusive_end - tuf * count; } } else { tuf = regional_tick.low_tick.tick_unit_frac(); + double ieeer = Math.IEEERemainder(input, tuf); + if (Math.Abs(ieeer) <= _precision_const) input -= ieeer; val = input - tuf * count; } return _round_tick(tuf, val); } + + public static double round(this TickFactors tick, double input) { return _round_tick(tick.tick_unit_frac(), input); } + public static double round(this RegionalTickFactors regional_tick, double input) { + 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); + } #endregion #region Private Members @@ -175,7 +189,7 @@ namespace mbts } private static double _round_tick(double tick_unit_frac, double input) { - return input + Math.IEEERemainder(input, tick_unit_frac); + return input - Math.IEEERemainder(input, tick_unit_frac); } private static int _n_display_digits(double tick_base) { diff --git a/src/client/spark/mspark/Algo/ActorFabric.cs b/src/client/spark/mspark/Algo/ActorFabric.cs index 1524d5e30..6cb3b1273 100644 --- a/src/client/spark/mspark/Algo/ActorFabric.cs +++ b/src/client/spark/mspark/Algo/ActorFabric.cs @@ -9,7 +9,12 @@ using bts.spark; namespace mbts.spark { - class ActorFabric : IActorFabric + + interface IParentSearch + { + OrderID find_parent_id(OrderID oid); + } + class ActorFabric : IActorFabric, IParentSearch { readonly static Lazy _instance = new Lazy(() => new ActorFabric(), true); public static ActorFabric instance { get { return _instance.Value; } } @@ -38,6 +43,20 @@ namespace mbts.spark }); } + public OrderID find_parent_id(OrderID oid) + { + foreach(var actor in _actors.Values) + { + if(actor is IParentSearch) + { + var res = (actor as IParentSearch).find_parent_id(oid); + if(res != null) + return res; + } + } + return null; + } + public void install_pollster(IPollable poll) { _polls[Guid.NewGuid()] = poll; diff --git a/src/client/spark/mspark/Algo/ClientAPI/AlgoClient.cs b/src/client/spark/mspark/Algo/ClientAPI/AlgoClient.cs index 49a3b4d7a..590bcf59d 100644 --- a/src/client/spark/mspark/Algo/ClientAPI/AlgoClient.cs +++ b/src/client/spark/mspark/Algo/ClientAPI/AlgoClient.cs @@ -30,6 +30,8 @@ namespace mbts.spark } } + + Dictionary _unique_fills = new Dictionary(); Task IAlgoClient.send(Order order) { return Task.Run(() => @@ -38,7 +40,15 @@ namespace mbts.spark if(ActorMapping.order_actor_mapping.TryGetValue(order.AlgoOrderTypeCase, out t)) { IOrderHandle actor = _fabric.create(t, order); - actor.fills.Subscribe(x => _fills.OnNext(x)); + actor.fills.Subscribe(x => + { + string dum; + if(!_unique_fills.TryGetValue(x.Id.Id, out dum)) + { + _unique_fills[x.Id.Id] = string.Empty; + _fills.OnNext(x); + } + }); actor.order_status.Subscribe(x => _order_status.OnNext(x)); _orders[order.Id] = actor; actor.spawn(); diff --git a/src/client/spark/mspark/Algo/Orders/ComplexSpreader/CrossingHedgeOrderActor.cs b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/CrossingHedgeOrderActor.cs index 512bf72d5..618e902a6 100644 --- a/src/client/spark/mspark/Algo/Orders/ComplexSpreader/CrossingHedgeOrderActor.cs +++ b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/CrossingHedgeOrderActor.cs @@ -14,17 +14,15 @@ namespace mbts.spark.orders class CrossingHedgeOrderActor : OrderActorBase, ICancelable, IModifiable { readonly IMarketDataSource _md; - readonly IExchangeGateway _exchange; - readonly IDropCopy _dc; OrderStatus _status; + IOrderHandle _handle; public CrossingHedgeOrderActor(IActorFabric fabric, Order order) : base(fabric, order) { //TODO Multi exchange fabric.find_wellknown_service(order.Security.Exchange, out _md); - fabric.find_wellknown_service(order.Security.Exchange, out _exchange); - fabric.find_wellknown_service(order.Security.Exchange, out _dc); } + public override void on_spawn() { _disposables.Add(_md.subscribe_bbo(_order.Security).Subscribe(x => @@ -32,29 +30,27 @@ namespace mbts.spark.orders if(x != null) watch_hedges(x); })); - _disposables.Add(_dc.subscribe_fills(new Predicate(x => _order.Id.Equals(x.Order.Id))).Subscribe(x => - { - _fills_sink.OnNext(x); - })); - _disposables.Add(_dc.subscribe_status(new Predicate(x => _order.Id.Equals(x.Order.Id))).Subscribe(x => - { - _status = x; - _status_sink.OnNext(x); - if(is_done_state(x.Status)) - exit(); - })); - var clone = _order.Clone(); - clone.LimitOrder = new LimitOrder(); - _exchange.send_order(clone); + //_handle = spawn_limit_order(_order.Security, _order.Size, _order.Price, _order.Side, _order.TimeInForce); + _handle = create_order(_order.Security, _order.Size, _order.Price, _order.Side, + _order.TimeInForce, new LimitOrder(), _order.CrossingHedgeOrder.PreAssignedId); + track_child(_handle); + _handle.spawn(); } + + override protected void on_child_status(OrderStatus child_status, ref OrderStatus merged_status) + { + base.on_child_status(child_status, ref merged_status); + _status = child_status; + } + void watch_hedges(BBOType bbo) { - if(_status != null) + if(_status != null && !is_final_state(_status.Status)) { PriceSize bid_or_ask; - if(_status.Order.Side == Side.Buy) + if(_order.Side == Side.Buy) bid_or_ask = bbo.Item2; else bid_or_ask = bbo.Item1; @@ -62,25 +58,25 @@ namespace mbts.spark.orders uint distance = Convert.ToUInt32(Math.Abs(bid_or_ask.price - _status.Order.Price) / compute_tick(_order.Security)); double tick = (_order.Side == Side.Buy ? 1.0 : -1.0) * compute_tick(_order.Security); if(distance > _order.CrossingHedgeOrder.TicksThreshold) - _exchange.modify_price(_order.Id, _status.Order.Price + _order.CrossingHedgeOrder.MarketCrossTicks * tick); + _handle.modify_price(_status.Order.Price + _order.CrossingHedgeOrder.MarketCrossTicks * tick); } } bool ICancelable.on_cancel() { - _exchange.cancel_order(_order.Id); + _handle.cancel(); return true; } bool IModifiable.on_modify_price(double new_price) { - _exchange.modify_price(_order.Id, new_price); + _handle.modify_price( new_price); return true; } bool IModifiable.on_modify_size(uint new_size) { - _exchange.modify_size(_order.Id, new_size); + _handle.modify_size(new_size); return true; } } diff --git a/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticLimitOrder.cs b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticLimitOrder.cs index 5ddd9aab6..e3c8a9e62 100644 --- a/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticLimitOrder.cs +++ b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticLimitOrder.cs @@ -50,10 +50,7 @@ namespace mbts.spark.orders else { if(current_order == null) //no current order, send one - { - var ord = spawn_limit_order(sec, size, price, side, _order.TimeInForce); - track_child(ord); - } + spawn_limit_order(sec, size, price, side, _order.TimeInForce); else update_existing_order(current_order, price, size, side, this_leg_book, param, bypass_quote_rules); } @@ -194,6 +191,11 @@ namespace mbts.spark.orders return true; } + protected override void on_child_status(OrderStatus child_status, ref OrderStatus merged_status) + { + merged_status.Order.Price = _order_price; + merged_status.Order.Size = _order_size;; + } bool IModifiable.on_modify_price(double new_price) { _order_price = new_price; @@ -231,11 +233,24 @@ namespace mbts.spark.orders void IPollable.on_poll() { } + public override void on_spawn() + { + base.on_spawn(); + OrderStatus merged = new OrderStatus(); + merged.Order = _order.Clone(); + merged.Status = OrderStatus.Types.Status.New; + _status_sink.OnNext(merged); + } + public override void on_destroy() { _paused = true; lock(_destroy_lock) { + OrderStatus merged = new OrderStatus(); + merged.Order = _order.Clone(); + merged.Status = OrderStatus.Types.Status.Done; + _status_sink.OnNext(merged); base.on_destroy(); } } diff --git a/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticOrderBase.cs b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticOrderBase.cs index fc9bcec5a..8502c9726 100644 --- a/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticOrderBase.cs +++ b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticOrderBase.cs @@ -12,7 +12,7 @@ using BookType = System.Tuple; namespace mbts.spark.orders { - abstract class SyntheticOrderBase : OrderActorBase + abstract class SyntheticOrderBase : OrderActorBase, IParentSearch { readonly protected object _destroy_lock = new object(); readonly protected IMarketDataSource _md; @@ -27,6 +27,14 @@ namespace mbts.spark.orders foreach(var ven in _leg_ratios.Keys) //TODO: Multi exchange fabric.find_wellknown_service(ven.Exchange, out _md); } + + public OrderID find_parent_id(OrderID oid) + { + if(_children.ContainsKey(oid)) + return this._order.Id; + else + return null; + } protected class HedgeInfo { @@ -79,12 +87,9 @@ namespace mbts.spark.orders async Task reduce_and_hedge(Fill fill) { - //if this fill was not because of a hedge, fire a hedge if(!_hedges.Contains(fill.Order.Id)) { - //send a hedge await hedge_working_order(fill); - //await reduce_working(fill.Order.Security, fill.Size, fill.Side, fill.Order.Id); } } @@ -93,6 +98,7 @@ namespace mbts.spark.orders bool gotone = false; var existing = _child_status.Where(x => x.Value.Order.Security.Equals(sec) && x.Value.Order.Side == side && + !is_final_state(x.Value.Status) && !_hedges.Contains(x.Key) ); foreach(var x in existing) { @@ -100,8 +106,7 @@ namespace mbts.spark.orders { IOrderHandle existing_working; if(_children.TryGetValue(x.Key, out existing_working)) - { - gotone = true; + { if(all || size >= x.Value.Order.Size) await existing_working.cancel(); else @@ -109,6 +114,8 @@ namespace mbts.spark.orders UInt32 new_size = x.Value.Order.Size - size; await existing_working.modify_size(new_size); } + gotone = true; + break; } } } @@ -116,6 +123,7 @@ namespace mbts.spark.orders } + readonly ConcurrentBag _hedge_disposables = new ConcurrentBag(); async Task hedge_working_order(Fill fill) { if(_order.Security.Equals(fill.Order.Security)) @@ -131,41 +139,41 @@ namespace mbts.spark.orders double hedge_price = kv.Value.price; hedge_price = compute_hedge_price(kv.Value.leg, hedge_side, hedge_size, kv.Value.leg_params, hedge_price); - //look for existing - //var existing = _child_status.Where(x => x.Value.Order.Security.Equals(kv.Key) && - // x.Value.Order.Side == hedge_side && - // x.Value.Order.Price == hedge_price); - - //if(existing.Any()) - //{ - // var existing_status = existing.First(); - // IOrderHandle existing_order; - // if(_children.TryGetValue(existing_status.Key, out existing_order)) - // { - // var res = await existing_order.modify_size(existing_status.Value.Order.Size + hedge_size); - // if(res.result) - // continue; - // } - //} - double tick = compute_tick(kv.Key); - PostHedgePriceBasedForcedCross post = null; - if(post.Priority.IsActive) - post = kv.Value.leg_params.PostHedgeParams.PriceBasedCross; + PostHedgePriceBasedForcedCross post = kv.Value?.leg_params?.PostHedgeParams?.PriceBasedCross; + var active = post?.Priority?.IsActive; var cross = new CrossingHedgeOrder { - TicksThreshold = (post == null) ? 1000 : post.TicksThreshold, - MarketCrossTicks = (post == null) ? 0 : post.MarketCrossTicks, + TicksThreshold = (active.HasValue && active.Value) ? post.TicksThreshold : 1000, + MarketCrossTicks = (active.HasValue && active.Value) ? post.MarketCrossTicks : 0 }; + cross.PreAssignedId = generate_order_id(); + _hedges.Add(cross.PreAssignedId); var hedge = create_order(kv.Value.leg, hedge_size, hedge_price, hedge_side, Order.Types.TimeInForce.Day, cross); _hedges.Add(hedge.order_id); - track_child(hedge); - await hedge.spawn(); + //there is a race here. the working leg comes back as filled, and the other working leg was cancelled before the hedge was sent + //this puts the parent order in a terminal state, no longer listening to fills, etc. This has the unintended side effect of + //'eating' the hedge leg fills + //track_child(hedge); + _children[hedge.order_id] = hedge; + _hedge_disposables.Add(hedge.order_status.Subscribe(x => + { + _child_status[x.Order.Id] = x; + compute_status_internal(x); + })); + _hedge_disposables.Add(hedge.fills.Subscribe(x => + { + _child_fills.Add(x); + compute_fill_internal(x); + })); + //reduce any working quantity by the amount of the hedge //initially I meant to reduce working on hedge fills, but now that I see it in action, there's too many orders out if we do it that way await reduce_working(kv.Value.leg, hedge_size, hedge_side); + + await hedge.spawn(); } } diff --git a/src/client/spark/mspark/Algo/Orders/OrderActorBase.cs b/src/client/spark/mspark/Algo/Orders/OrderActorBase.cs index cf59bb78c..baf37668e 100644 --- a/src/client/spark/mspark/Algo/Orders/OrderActorBase.cs +++ b/src/client/spark/mspark/Algo/Orders/OrderActorBase.cs @@ -25,7 +25,7 @@ namespace mbts.spark.orders if(order.ExecutionStrategy != null && order.ExecutionStrategy.LegParamsMap != null) order.ExecutionStrategy.LegParamsMap.ForEach(x => _execution_strategy.TryAdd(x.Key, x.Value)); } - + protected IOrderHandle spawn_limit_order(Security sec, uint size, double price, Side side, Order.Types.TimeInForce tif = Order.Types.TimeInForce.Day) { @@ -123,8 +123,6 @@ namespace mbts.spark.orders if(_children.TryRemove(child_status.Order.Id, out handle)) _ex_children.TryAdd(child_status.Order.Id, handle); } - merged_status.Children.AddRange(_children.Select(x => x.Key)); - merged_status.Children.AddRange(_ex_children.Select(x => x.Key)); } override protected void track_child(IOrderHandle algo) diff --git a/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleOrderBase.cs b/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleOrderBase.cs index bdfadb195..715ff8d4f 100644 --- a/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleOrderBase.cs +++ b/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleOrderBase.cs @@ -82,10 +82,10 @@ namespace mbts.spark.orders protected IOrderHandle create_order(Security sec, uint size, double price, Side side, Order.Types.TimeInForce tif = Order.Types.TimeInForce.Day, - T algo_order_params = default(T)) where T : new() + T algo_order_params = default(T), OrderID id = null) where T : new() { Order ord = ActorMapping.create_order_of_type(algo_order_params); - ord.Id = generate_order_id(); + ord.Id = id ?? generate_order_id(); ord.Security = sec; ord.Price = price; ord.Size = size; diff --git a/src/client/spark/mspark/Core/MDSource.cs b/src/client/spark/mspark/Core/MDSource.cs index 8593c139c..2fe22f22f 100644 --- a/src/client/spark/mspark/Core/MDSource.cs +++ b/src/client/spark/mspark/Core/MDSource.cs @@ -7,21 +7,23 @@ using System.ComponentModel.Composition; using mbts.ui.shell; using bts.api; using mbts; +using System.Reactive.Linq; using security_key = System.UInt32; +using System.Threading.Tasks; namespace mbts.spark { [Export(typeof(IInitializable))] class MDSource : IObserver>, IInitializable { - private readonly bts.api.IBus _bus; + private readonly IBus _bus; private readonly MDConsumer _consumer; private List _disp_list = new List (); private IDictionary _exchange_sec_map = new Dictionary (), _synthetic_sec_map = new Dictionary (); [ImportingConstructor] - public MDSource(bts.api.IBus bus, [Import("username")] string username) + public MDSource(IBus bus, [Import("username")] string username) { _bus = bus; _consumer = Co2RelayControl.instance.consumer; @@ -37,12 +39,14 @@ namespace mbts.spark public void OnNext(List values) { - foreach (var v in values) { - _exchange_sec_map.Add(v.security.Id, new SecurityMD(new bts.api.Security(v.security), v.handle)); + if (values.Count > 0) { + var temp = new Dictionary(_exchange_sec_map); + foreach (var v in values) { + temp.Add(v.security.Id, new SecurityMD(v.security, v.handle)); + } + _exchange_sec_map = temp; + //_publish_securities(); } - //Logger.info(bts.log.Subsystem.MarketData, $"Publishing {_security_state.Count} securities."); - _publish_securities(); - //_bus.post(SparkTags.SecuritiesTag, new Dictionary(_exchange_sec_map)); } public int priority { get { return 0; } } @@ -52,6 +56,26 @@ namespace mbts.spark _disp_list.Add (_consumer.on_security.Subscribe(this)); _disp_list.Add (_bus.subscribe (SparkTags.SyntheticSecuritiesTag).Subscribe (i => _on_synthetic_securities (i))); new DataPersistor(_bus); + Task.Run(run); + } + + async Task run() { + int count = 0; + while (true) { + var exch = _exchange_sec_map; + var synth = _synthetic_sec_map; + var newcount = exch.Count + synth.Count; + if (newcount > count) { + count = newcount; + try { + _publish_securities(); + } + catch (Exception e) { + Logger.error(bts.log.Subsystem.MarketData, $"Error in publish_securities: {e}"); + } + } + await Task.Delay(TimeSpan.FromSeconds(1)); + } } private void _on_synthetic_securities(SparkBusData.SyntheticSecuritiesMessage synth_secs) @@ -59,7 +83,7 @@ namespace mbts.spark if (synth_secs != null && synth_secs.data != null) { _synthetic_sec_map = synth_secs.data.ToDictionaryDupes(s => s.Key, s => new SecurityMD(s.Value.Security, new SyntheticSecurityMDHandle(s.Value.Security, _exchange_sec_map))); - _publish_securities(); + //_publish_securities(); } } @@ -71,7 +95,7 @@ namespace mbts.spark Security sec = kv.Value.security; rv.Add(sec.Id, new SecurityMD(sec, new SyntheticSecurityMDHandle(sec, _exchange_sec_map))); } - mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, String.Format("MDSource publishing {0} securities", rv.Count)); + Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, String.Format("MDSource publishing {0} securities", rv.Count)); _bus.post(SparkTags.SecuritiesTag, rv); } } diff --git a/src/client/spark/mspark/Core/TickUtils.cs b/src/client/spark/mspark/Core/TickUtils.cs index 7f679bd42..ce0acbe32 100644 --- a/src/client/spark/mspark/Core/TickUtils.cs +++ b/src/client/spark/mspark/Core/TickUtils.cs @@ -35,10 +35,10 @@ namespace mbts.spark { } - public static double tickup(this ContractSpecification contract, double value) { return _get_regional_ticks(contract).tickup(value); } - public static double tickup(this ContractSpecification contract, double value, int count) { return _get_regional_ticks(contract).tickup(value, (uint)count); } - public static double tickdown(this ContractSpecification contract, double value) { return _get_regional_ticks(contract).tickdown(value); } - public static double tickdown(this ContractSpecification contract, double value, int count) { return _get_regional_ticks(contract).tickdown(value, (uint)count); } + public static double tickup(this ContractSpecification contract, double value) { return get_regional_ticks(contract).tickup(value); } + public static double tickup(this ContractSpecification contract, double value, int count) { return get_regional_ticks(contract).tickup(value, (uint)count); } + public static double tickdown(this ContractSpecification contract, double value) { return get_regional_ticks(contract).tickdown(value); } + public static double tickdown(this ContractSpecification contract, double value, int count) { return get_regional_ticks(contract).tickdown(value, (uint)count); } public static double round_to_tick(this ContractSpecification spec, double value) { double intpart = (long)value; @@ -52,7 +52,7 @@ namespace mbts.spark { double low = Math.Min(a, b); double high = Math.Max(a, b); int count = 0; - while (a < b) { + while (a < b && count < 1000000) { ++count; a = tickup(spec, a); } @@ -62,7 +62,7 @@ namespace mbts.spark { public static int[] get_tick_jump_quantities(ContractSpecification spec) { return _ticks_cache.TryGetValue(spec.LowTick, out (TickFactors tf, int[] jumps) result) ? result.jumps : new[] { 1, 5, 10, 25, 50, 100 }; } - public static RegionalTickFactors _get_regional_ticks(ContractSpecification spec) { + public static RegionalTickFactors get_regional_ticks(ContractSpecification spec) { return _regional_ticks_cache.GetOrAdd((spec.LowTick, spec.HighTick, spec.PriceBreak), _create_regional_ticks); } private static RegionalTickFactors _create_regional_ticks((double low_tick, double high_tick, double price_break) def) { diff --git a/src/client/spark/mspark/Ladder/LadderModel.cs b/src/client/spark/mspark/Ladder/LadderModel.cs index eaebf7479..3ff7b1cc8 100644 --- a/src/client/spark/mspark/Ladder/LadderModel.cs +++ b/src/client/spark/mspark/Ladder/LadderModel.cs @@ -29,7 +29,7 @@ namespace mbts.spark { public void cancel_orders(CancelType ct) { order_gateway.cancel_security_orders (new uint[] {security.Id}, ct == CancelType.Bids || ct == CancelType.All, ct == CancelType.Asks || ct == CancelType.All); - Logger.info(bts.log.Subsystem.ui, $"Cancel {ct}"); + Logger.info(bts.log.Subsystem.Ui, $"Cancel {ct}"); } public OrdersModel order_gateway => _order_gateway; diff --git a/src/client/spark/mspark/Ladder/LadderOrdersHost.cs b/src/client/spark/mspark/Ladder/LadderOrdersHost.cs index 23ee6d34d..a50731689 100644 --- a/src/client/spark/mspark/Ladder/LadderOrdersHost.cs +++ b/src/client/spark/mspark/Ladder/LadderOrdersHost.cs @@ -51,14 +51,15 @@ namespace mbts.spark { panel.Children.Add(mkbadge(order)); } } - public void remove_order(OrderVM order) { - _orders.Remove(order); + public bool remove_order(OrderVM order) { + bool result = _orders.Remove(order); foreach (var panel in _stacks.Values) { var todelete = panel.Children.OfType().Where(b => b.DataContext == order).ToList(); foreach (var item in todelete) { panel.Children.Remove(item); } } + return result; } public void clear_orders() { @@ -109,11 +110,12 @@ namespace mbts.spark { if (e.Data.GetDataPresent(typeof(OrderVM))) { OrderVM vm = e.Data.GetData(typeof(OrderVM)) as OrderVM; if (vm != null && vm.security_key == security_key) { - Logger.info(bts.log.Subsystem.ui, "Drop - " + vm.summary); + Logger.info(bts.log.Subsystem.Ui, "Drop - " + vm.summary); double price = _parent.price_for_point(e.GetPosition(_parent)); if (vm.try_change_price(price)) { - remove_order(vm); - add_order(vm); + if (remove_order(vm)) { + add_order(vm); + } } } } diff --git a/src/client/spark/mspark/Ladder/LadderSettings.cs b/src/client/spark/mspark/Ladder/LadderSettings.cs index bce82e729..299048b1a 100644 --- a/src/client/spark/mspark/Ladder/LadderSettings.cs +++ b/src/client/spark/mspark/Ladder/LadderSettings.cs @@ -60,7 +60,7 @@ namespace mbts.spark { public bool scroll_bar_visible { get; set; } public int ticks_to_recenter { get; set; } = 3; - public int seconds_to_recenter { get; set; } = 300; + public int seconds_to_recenter { get; set; } = 30; public string SelectedAlgo { get; set; } = "LimitOrder"; public string DefaultTimeInForce { get; set; } = "Day"; diff --git a/src/client/spark/mspark/Ladder/LadderVM.cs b/src/client/spark/mspark/Ladder/LadderVM.cs index bbdf3f060..8defb25a0 100644 --- a/src/client/spark/mspark/Ladder/LadderVM.cs +++ b/src/client/spark/mspark/Ladder/LadderVM.cs @@ -71,6 +71,8 @@ namespace mbts.spark { public Security security => _model.security; public IMDHandle md => _model.md; + public bool is_synthetic => _model.security.ContractCase == Security.ContractOneofCase.Synthetic; + private void tick(object sender, EventArgs e) { update_header(); on_tick?.Invoke(); @@ -99,7 +101,15 @@ namespace mbts.spark { _open.set(spec.format(md.open_price)); ulong unused = 0; md.get_last_trade(ref unused, out NativePriceSize last, out DateTime time, out ulong volume); - _change.set(spec.format(last.price - md.settlement_price)); + if (!double.IsNaN(last.price)) { + _change.set(spec.format(last.price - md.settlement_price)); + } + else { + unused = 0; + _model.md.get_bbo(ref unused, out NativePriceSize bid, out NativePriceSize ask); + double mid = TickUtils.mid_tick(spec, bid.price, ask.price); + _change.set(spec.format(mid - md.settlement_price)); + } _volume.set(volume); } } @@ -205,7 +215,7 @@ namespace mbts.spark { //Logger.notnull(i); if (i == null) { var msg = String.Join(" ",my_orders.Select(m => m.ID().Id)); - Logger.error(bts.log.Subsystem.ui, $"Equality problem in order {o.id} should be in {msg}."); + Logger.error(bts.log.Subsystem.Ui, $"Equality problem in order {o.id} should be in {msg}."); } if (i != null) { o.update(i); diff --git a/src/client/spark/mspark/Ladder/LadderView.xaml b/src/client/spark/mspark/Ladder/LadderView.xaml index cdd1ad3c2..fa483fc58 100644 --- a/src/client/spark/mspark/Ladder/LadderView.xaml +++ b/src/client/spark/mspark/Ladder/LadderView.xaml @@ -7,6 +7,7 @@ xmlns:usp="clr-namespace:mbts.ui.spark" xmlns:uag="clr-namespace:mbts.ui.spark.algo" xmlns:sys="clr-namespace:System;assembly=mscorlib" + xmlns:converters="clr-namespace:mbts.ui.converters" Height="600" Width="400" TextElement.FontSize="11"> @@ -15,6 +16,15 @@ + + + + + + + + + @@ -32,15 +42,10 @@ - - - - - Revert - + @@ -54,10 +59,16 @@ + + + + + - + @@ -81,23 +92,27 @@ - - +