diff --git a/src/client/spark/Themes/generic.xaml b/src/client/spark/Themes/generic.xaml index a1d40f230..7b1aa034e 100644 --- a/src/client/spark/Themes/generic.xaml +++ b/src/client/spark/Themes/generic.xaml @@ -1,492 +1,492 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs b/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs index cf5fcf4a8..e7f975921 100644 --- a/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/GenericCollectionExtensions.cs @@ -16,6 +16,10 @@ namespace System.Collections.Generic public static IEnumerable DistinctOn(this IEnumerable enumerable, Func key_selector) { return enumerable.Distinct(new AnonymousEqualityComparer((x, y) => key_selector(x).Equals(key_selector(y)), x => key_selector(x).GetHashCode())); } + + public static IEnumerable Intersect(this IEnumerable enumerable, IEnumerable intersection, Func key_selector) { + return enumerable.Where(t => intersection.Contains(key_selector(t))); + } } public static class DictionaryExtensions @@ -49,6 +53,25 @@ namespace System.Collections.Generic public static class ListExtensions { + public static bool Pop(this IList list, TKey key, Func key_selector, out T result) { + for(int i = 0; i < list.Count; i++) { + if (key_selector(list[i]).Equals(key)) { + result = list[i]; + return true; + } + } + result = default(T); + return false; + } + + public static bool PopDispose(this IList list, TKey key, Func key_selector) where T : IDisposable { + if (list.Pop(key, key_selector, out T result)) { + result.Dispose(); + return true; + } + return false; + } + public static T Pop(this IList list, int index) { T rv = list.ElementAt(index); list.RemoveAt(index); @@ -149,9 +172,13 @@ namespace mbts.collections.extensions public static class DictionaryExtensions { - //public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key) { - // return dictionary.TryGetValue(key, out TValue result) ? result : default(TValue); - //} + public static TValue GetValueOrDefault(this Dictionary dictionary, TKey key) { + return dictionary.TryGetValue(key, out TValue result) ? result : default(TValue); + } + + public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key) { + return dictionary.TryGetValue(key, out TValue result) ? result : default(TValue); + } public static TValue GetValue(this IDictionary dictionary, TKey key, TValue error_val) { return dictionary.TryGetValue(key, out TValue result) ? result : error_val; @@ -162,11 +189,4 @@ namespace mbts.collections.extensions else dictionary.Add(key, create_new()); } } - - public static class ReadOnlyDictionaryExtensions - { - public static TValue GetValueOrDefault(this IReadOnlyDictionary dictionary, TKey key) { - return dictionary.TryGetValue(key, out TValue result) ? result : default(TValue); - } - } -} +} \ No newline at end of file diff --git a/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs b/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs index ca137783a..7d635f101 100644 --- a/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs +++ b/src/client/spark/core/GlobalExtensions/GlobalExtensions.cs @@ -426,6 +426,10 @@ namespace System.Reactive.Linq IObservable alive = source.Select(_ => true); return dead.Merge(alive).DistinctUntilChanged(); } + + public static IObservable<(TSource prev, TSource curr)> PairWithPrevious(this IObservable source) { + return source.Scan((default(TSource), default(TSource)), (last, next) => (last.curr, next)); + } } } diff --git a/src/client/spark/core/bus/SingletonBus.cs b/src/client/spark/core/bus/SingletonBus.cs index 47c3a22a2..4c37ab31f 100644 --- a/src/client/spark/core/bus/SingletonBus.cs +++ b/src/client/spark/core/bus/SingletonBus.cs @@ -1,11 +1,9 @@ using bts.api; +using mbts.utils; using System; using System.Collections.Generic; using System.ComponentModel.Composition; -using System.Linq; using System.Reactive.Subjects; -using System.Text; -using System.Threading.Tasks; namespace bts.core { @@ -22,7 +20,7 @@ namespace bts.core if (inst.TryGetValue(tag, out ISubject result)) { return result; } - result = new Subject(); + result = new StateSubject(); inst[tag] = result; return result; } @@ -36,4 +34,4 @@ namespace bts.core return subject(tag); } } -} +} \ No newline at end of file diff --git a/src/client/spark/core/utils/CompareUtils.cs b/src/client/spark/core/utils/CompareUtils.cs index bac77bfc0..0a268ce9f 100644 --- a/src/client/spark/core/utils/CompareUtils.cs +++ b/src/client/spark/core/utils/CompareUtils.cs @@ -5,6 +5,22 @@ namespace mbts.utils { public static class CompareUtils { + #region Equality + public static IEqualityComparer NullCheckEqualityComparer(Func never_null_equals, Func get_hash_code) { + return EqualityComparer.Create(NullCheckEquality(never_null_equals), get_hash_code); + } + public static Func NullCheckEquality(Func never_null_equals) { + return (x, y) => NullCheckEquals(x, y, never_null_equals); + } + public static bool NullCheckEquals(T x, T y) { + return NullCheckEquals(x, y, (_x, _y) => _x.Equals(_y)); + } + public static bool NullCheckEquals(T x, T y, Func never_null_equals) { + return x == null ? y == null : y == null ? false : never_null_equals(x, y); + } + #endregion + + #region Comparison public static Comparison NullCheckComparison(Comparison never_null_comparison) where T : class { return new Comparison((x, y) => NullCheckCompare(x, y, never_null_comparison)); } @@ -14,5 +30,6 @@ namespace mbts.utils public static int NullCheckCompare(T x, T y, Comparison never_null_comparison) where T : class { return x == null ? y == null ? 0 : -1 : y == null ? 1 : never_null_comparison(x, y); } + #endregion } } \ No newline at end of file diff --git a/src/client/spark/core/utils/StatePublisher.cs b/src/client/spark/core/utils/StatePublisher.cs new file mode 100644 index 000000000..d47538e06 --- /dev/null +++ b/src/client/spark/core/utils/StatePublisher.cs @@ -0,0 +1,37 @@ +using System; +using System.Reactive.Linq; +using System.Reactive.Subjects; + +namespace mbts.utils +{ + /// + /// Subscribes to the source and stores the latest valule internally. All subscription sequences begin with the latest value. + /// + /// + public class StatePublisher : IObservable, IDisposable + { + public StatePublisher(IObservable source) { + _publisher = source.Select(val => { + lock (_lock) { + _value_initialized = true; + return _last_value = val; + } + }).Publish(); + _connection = _publisher.Connect(); + } + + private readonly IConnectableObservable _publisher; + private readonly IDisposable _connection; + private readonly object _lock = new object(); + private bool _value_initialized; + private T _last_value; + + public IDisposable Subscribe(IObserver observer) { + lock(_lock) return (_value_initialized ? _publisher.StartWith(_last_value) : _publisher).Subscribe(observer); + } + + public void Dispose() { + _connection.Dispose(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/core/utils/StateSubject.cs b/src/client/spark/core/utils/StateSubject.cs new file mode 100644 index 000000000..5ab4ce783 --- /dev/null +++ b/src/client/spark/core/utils/StateSubject.cs @@ -0,0 +1,27 @@ +using System; +using System.Reactive.Subjects; + +namespace mbts.utils +{ + public class StateSubject : ISubject, IDisposable + { + public StateSubject() { + _publisher = new StatePublisher(_subject); + } + + private readonly Subject _subject = new Subject(); + private readonly StatePublisher _publisher; + + #region ISubject + public void OnNext(T value) { _subject.OnNext(value); } + public void OnError(Exception error) { _subject.OnError(error); } + public void OnCompleted() { _subject.OnCompleted(); } + public IDisposable Subscribe(IObserver observer) { return _publisher.Subscribe(observer); } + #endregion + + public void Dispose() { + _subject.OnCompleted(); + _publisher.Dispose(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Algo/ActorMapping.cs b/src/client/spark/mspark/Algo/ActorMapping.cs index f6f24edea..4409ea121 100644 --- a/src/client/spark/mspark/Algo/ActorMapping.cs +++ b/src/client/spark/mspark/Algo/ActorMapping.cs @@ -18,6 +18,7 @@ namespace mbts.spark { Order.AlgoOrderTypeOneofCase.StopLimitOrder, typeof(orders.StopLimitOrderActor) }, { Order.AlgoOrderTypeOneofCase.StopMarketOrder, typeof(orders.StopMarketOrderActor) }, { Order.AlgoOrderTypeOneofCase.CrossingHedgeOrder, typeof(orders.CrossingHedgeOrderActor) }, + { Order.AlgoOrderTypeOneofCase.SimpleHedgeOrder, typeof(orders.SimpleHedgeOrderActor) }, }; } diff --git a/src/client/spark/mspark/Algo/Orders/Hedge/CrossingHedgeOrderActor.cs b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/CrossingHedgeOrderActor.cs similarity index 85% rename from src/client/spark/mspark/Algo/Orders/Hedge/CrossingHedgeOrderActor.cs rename to src/client/spark/mspark/Algo/Orders/ComplexSpreader/CrossingHedgeOrderActor.cs index 3ee5c687a..8ccae4f74 100644 --- a/src/client/spark/mspark/Algo/Orders/Hedge/CrossingHedgeOrderActor.cs +++ b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/CrossingHedgeOrderActor.cs @@ -53,9 +53,9 @@ namespace mbts.spark.orders { if(_status != null) { - PriceSize bid_or_ask; + PriceSize bid_or_ask; if(_status.Order.Side == BuySell.Buy) - bid_or_ask = bbo.Item2; + bid_or_ask = bbo.Item2; else bid_or_ask = bbo.Item1; @@ -64,6 +64,10 @@ namespace mbts.spark.orders { _exchange.modify_price(_order.Id, bid_or_ask.price); } + + uint distance = Convert.ToUInt32(Math.Abs(bid_or_ask.price - _status.Order.Price) / compute_tick(_order.Security)); + if(distance > _order.CrossingHedgeOrder.TicksBetterThreshold) + _exchange.modify_price(_order.Id, bid_or_ask.price); } } diff --git a/src/client/spark/mspark/Algo/Orders/Limit/SyntheticLimitOrder.cs b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticLimitOrder.cs similarity index 88% rename from src/client/spark/mspark/Algo/Orders/Limit/SyntheticLimitOrder.cs rename to src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticLimitOrder.cs index cbf53256d..485715a0b 100644 --- a/src/client/spark/mspark/Algo/Orders/Limit/SyntheticLimitOrder.cs +++ b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticLimitOrder.cs @@ -13,9 +13,13 @@ namespace mbts.spark.orders { class SyntheticLimitOrder : SyntheticOrderBase, ICancelable, IModifiable, IPausable, ICrackable, IPollable { - bool _paused; + bool _paused; + double _order_price; + uint _order_size; public SyntheticLimitOrder(IActorFabric fabric, Order order) : base(fabric, order) - { + { + _order_price = order.Price; + _order_size = order.Size; } protected override void on_book_change(BookType book) @@ -28,7 +32,7 @@ namespace mbts.spark.orders { if(!_books.Values.Any(x => x == null)) { - foreach(Security sec in _leg_sizes.Keys) + foreach(Security sec in _leg_ratios.Keys) { SyntheticLegExecutionParams param; _execution_strategy.TryGetValue(sec.Id, out param); @@ -41,12 +45,15 @@ namespace mbts.spark.orders { if(size == 0) { - reduce_working(sec, 0, side, null, true); + clear_working(sec, side); } else { if(current_order == null) //no current order, send one - spawn_limit_order(sec, size, price, side, _order.TimeInForce); + { + var ord = spawn_limit_order(sec, size, price, side, _order.TimeInForce); + track_child(ord); + } else update_existing_order(current_order, price, size, side, this_leg_book, param, bypass_quote_rules); } @@ -67,7 +74,7 @@ namespace mbts.spark.orders if(is_done_state(status.Status) || is_problem_state(status.Status)) return; - if(new_size > status.Order.Size || bypass_quote_rules) + if(new_size != status.Order.Size && bypass_quote_rules) current_order.modify_size(new_size); double tick = compute_tick(current_order.security); @@ -100,17 +107,17 @@ namespace mbts.spark.orders out BuySell final_side, out IReadOnlyList this_leg_book) { //this is the price we want the spread, this algorithm works backwards from this price to get the price of the quote leg - final_price = _order.Price * -1.0; //-4 means a credit + final_price = _order_price * -1.0; //-X means credit final_size = 0; final_side = BuySell.Buy; this_leg_book = null; bool hit_myself = false; - foreach(Security sec in _leg_sizes.Keys) + foreach(Security sec in _leg_ratios.Keys) { SyntheticLegExecutionParams param; if(!_execution_strategy.TryGetValue(sec.Id, out param)) return false; - double quote_size = _leg_sizes[sec]; + double quote_size = _leg_ratios[sec] * _order_size; if(leg.Equals(sec)) //this leg -- do sizing { @@ -141,7 +148,7 @@ namespace mbts.spark.orders else bid_or_ask_book = _books[sec].Item1; double leg_price = 0.0; bool ok = false; - uint looking_for_size = Convert.ToUInt32(Math.Abs(quote_size) * param.QuoteParams.HedgeRatio); + uint looking_for_size = Convert.ToUInt32(Math.Abs(quote_size) * param.QuoteParams.LeanQuantityRatio); uint size_counter = looking_for_size; foreach(var level in bid_or_ask_book) { @@ -192,15 +199,14 @@ namespace mbts.spark.orders bool IModifiable.on_modify_price(double new_price) { - _order.Price = new_price; + _order_price = new_price; requote(true); return true; } bool IModifiable.on_modify_size(uint new_size) { - _order.Size = new_size; - flatten_synthetic(_order, out _leg_sizes, out _price_mults); + _order_size = new_size; requote(true); return true; } diff --git a/src/client/spark/mspark/Algo/Orders/Market/SyntheticMarketOrder.cs b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticMarketOrder.cs similarity index 92% rename from src/client/spark/mspark/Algo/Orders/Market/SyntheticMarketOrder.cs rename to src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticMarketOrder.cs index eeacb688c..f241b885d 100644 --- a/src/client/spark/mspark/Algo/Orders/Market/SyntheticMarketOrder.cs +++ b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticMarketOrder.cs @@ -20,7 +20,7 @@ namespace mbts.spark.orders override public void on_spawn() { base.on_spawn(); - foreach(var kv in _leg_sizes) + foreach(var kv in _leg_ratios) { SyntheticLegExecutionParams param; if(_execution_strategy.TryGetValue(kv.Key.Id, out param)) @@ -28,7 +28,7 @@ namespace mbts.spark.orders if(param.QuoteParams.IsWorking) { BuySell side = kv.Value > 0.0 ? BuySell.Buy : BuySell.Sell; - uint size = Convert.ToUInt32(Math.Abs(kv.Value)); + uint size = Convert.ToUInt32(Math.Abs(kv.Value * _order.Size)); spawn_market_order(kv.Key, size, side, _order.TimeInForce); //break; //only send market for one working leg, the rest should come out in the hedge } diff --git a/src/client/spark/mspark/Algo/Orders/Hedge/SyntheticOrderBase.cs b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticOrderBase.cs similarity index 65% rename from src/client/spark/mspark/Algo/Orders/Hedge/SyntheticOrderBase.cs rename to src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticOrderBase.cs index d55be5018..08cb2ac97 100644 --- a/src/client/spark/mspark/Algo/Orders/Hedge/SyntheticOrderBase.cs +++ b/src/client/spark/mspark/Algo/Orders/ComplexSpreader/SyntheticOrderBase.cs @@ -16,15 +16,15 @@ namespace mbts.spark.orders { readonly protected object _destroy_lock = new object(); readonly protected IMarketDataSource _md; - protected IDictionary _leg_sizes; + protected IDictionary _leg_ratios; protected IDictionary _price_mults; readonly protected IDictionary _books = new ConcurrentDictionary(); readonly protected IDictionary _hedge_info = new ConcurrentDictionary(); readonly protected ConcurrentBag _hedges = new ConcurrentBag(); public SyntheticOrderBase(IActorFabric fabric, Order order) : base(fabric, order) { - flatten_synthetic(order, out _leg_sizes, out _price_mults); - foreach(var ven in _leg_sizes.Keys) //TODO: Multi exchange + flatten_synthetic(order, out _leg_ratios, out _price_mults); + foreach(var ven in _leg_ratios.Keys) //TODO: Multi exchange fabric.find_wellknown_service(ven.Exchange, out _md); } @@ -38,7 +38,7 @@ namespace mbts.spark.orders override public void on_spawn() { - foreach(var sec in _leg_sizes.Keys) + foreach(var sec in _leg_ratios.Keys) { _books[sec] = null; _disposables.Add(_md.subscribe_depth(sec).Subscribe(x => @@ -69,43 +69,54 @@ namespace mbts.spark.orders protected override void on_child_fill(Fill fill, ref Fill merged_fill) { - lock(_destroy_lock) - { - if(!reduce_working(fill.Order.Security, fill.Size, fill.Side, fill.Order.Id) && - !_hedges.Contains(fill.Order.Id)) - { - hedge_working_order(fill); - } + reduce_and_hedge(fill).ContinueWith( _ => { }); + } + + protected void clear_working(Security sec, BuySell side) + { + reduce_working(sec, 0, side, null, true).ContinueWith(_ => { }); + } + + 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); } } - - protected bool reduce_working(Security sec, uint size, BuySell side, OrderID oid = null, bool all = false) + + protected async Task reduce_working(Security sec, uint size, BuySell side, OrderID oid = null, bool all = false) { bool gotone = false; - var existing = _child_status.Where(x => x.Value.Order.Security.Equals(sec) && x.Value.Order.Side == side); - existing.ForEach(x => - { - if(!x.Key.Equals(oid ?? new OrderID())) - { - IOrderHandle existing_working; - if(_children.TryGetValue(x.Key, out existing_working)) - { - gotone = true; - if(all || size >= x.Value.Order.Size) - existing_working.cancel(); - else - { - UInt32 new_size = x.Value.Order.Size - size; - existing_working.modify_size(new_size); - } - } - } - }); + var existing = _child_status.Where(x => x.Value.Order.Security.Equals(sec) && + x.Value.Order.Side == side && + !_hedges.Contains(x.Key) ); + foreach(var x in existing) + { + if(!x.Key.Equals(oid ?? new OrderID())) + { + 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 + { + UInt32 new_size = x.Value.Order.Size - size; + await existing_working.modify_size(new_size); + } + } + } + } return gotone; } - async void hedge_working_order(Fill fill) + async Task hedge_working_order(Fill fill) { if(_order.Security.Equals(fill.Order.Security)) return; //don't hedge yourself if you are a synthetic @@ -115,38 +126,45 @@ namespace mbts.spark.orders continue; //don't hedge yourself var hedge_side = (kv.Value.size > 0.0) ? BuySell.Buy : BuySell.Sell; - uint hedge_size = Convert.ToUInt32(Math.Abs(kv.Value.size) * fill.Size / fill.Order.Size); + double ratio = _leg_ratios[kv.Key]; + uint hedge_size = Convert.ToUInt32(Math.Abs(ratio) * fill.Size); 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; - } - } + //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); var post = kv.Value.leg_params.HedgeParams.PostHedgeRules; var cross = new CrossingHedgeOrder { CrossSizeThreshold = post == null ? 0 : post.CrossSizeThreshold, CrossRatioThreshold = post == null ? 1.0 : post.CrossRatioThreshold, + TicksBetterThreshold = Convert.ToUInt32(Math.Abs(hedge_price - kv.Value.price) / tick), }; 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.order_id, hedge); + track_child(hedge); await hedge.spawn(); + //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); } } diff --git a/src/client/spark/mspark/Algo/Orders/Limit/LimitOrderActor.cs b/src/client/spark/mspark/Algo/Orders/Limit/LimitOrderActor.cs index a76936fd9..2e64e34d9 100644 --- a/src/client/spark/mspark/Algo/Orders/Limit/LimitOrderActor.cs +++ b/src/client/spark/mspark/Algo/Orders/Limit/LimitOrderActor.cs @@ -10,7 +10,7 @@ namespace mbts.spark.orders class LimitOrderActor : IActor, ICancelable, IModifiable, IPausable, ICrackable, IPollable, IOrderStatusProducer, IFillProducer { - readonly OrderActorBase _impl; + readonly SimpleOrderBase _impl; readonly ICancelable _cancel; readonly IModifiable _modify; readonly IPausable _pause; @@ -22,8 +22,9 @@ namespace mbts.spark.orders throw new NotSupportedException("Limit order doesn't support SecurityType == None"); else if(order.Security.ContractCase == Security.ContractOneofCase.Synthetic) { - var algo = new SyntheticLimitOrder(fabric, order); - _impl = algo; _cancel = algo; _modify = algo; _pause = algo; _crack = algo; _poll = algo; + var algo = new SimpleSyntheticLimitOrder(fabric, order); + //var algo = new SyntheticLimitOrder(fabric, order); + _impl = algo; _cancel = algo; _modify = algo; _pause = null; _crack = null; _poll = null; } else { diff --git a/src/client/spark/mspark/Algo/Orders/OrderActorBase.cs b/src/client/spark/mspark/Algo/Orders/OrderActorBase.cs index 50cac9dda..c5da96b53 100644 --- a/src/client/spark/mspark/Algo/Orders/OrderActorBase.cs +++ b/src/client/spark/mspark/Algo/Orders/OrderActorBase.cs @@ -11,13 +11,8 @@ using bts.spark; namespace mbts.spark.orders { - abstract class OrderActorBase : IActor, IOrderStatusProducer, IFillProducer - { - readonly IOrderIDGenerator _generator; - protected readonly IActorFabric _fabric; - protected readonly Order _order; - - readonly protected List _disposables = new List(); + abstract class OrderActorBase : SimpleOrderBase + { readonly protected ConcurrentDictionary _children = new ConcurrentDictionary(); readonly protected ConcurrentDictionary _ex_children = new ConcurrentDictionary(); readonly protected ConcurrentDictionary _child_status = new ConcurrentDictionary(); @@ -25,54 +20,12 @@ namespace mbts.spark.orders readonly protected ConcurrentBag _child_fills = new ConcurrentBag(); readonly protected ConcurrentDictionary _execution_strategy = new ConcurrentDictionary(); - protected OrderActorBase(IActorFabric fabric, Order order) + protected OrderActorBase(IActorFabric fabric, Order order) : base(fabric, order) { - _order = order.Clone(); - _fabric = fabric; - _fabric.find_wellknown_service(out _generator); - guid = Guid.NewGuid(); if(order.ExecutionStrategy != null && order.ExecutionStrategy.SecurityIdToParams != null) order.ExecutionStrategy.SecurityIdToParams.ForEach(x => _execution_strategy.TryAdd(x.Key, x.Value)); } - - public Guid guid { get; private set; } - readonly ConcurrentQueue _orderids = new ConcurrentQueue(); - protected OrderID generate_order_id() - { - //TODO we need to rework this when things have to go fast.... - if(_orderids.Count == 0) - { - const int nids = 100; - OrderID[] oids; - _generator.generate_order_ids(nids, out oids); - oids.ForEach(x => _orderids.Enqueue(x)); - } - OrderID id; - var succ = _orderids.TryDequeue(out id); - if(!succ) - throw new NotSupportedException(); - //id.Id = this.GetType().Name + " " + id.Id; - return id; - } - - protected IOrderHandle create_order(Security sec, uint size, double price, BuySell side, - Order.Types.TimeInForce tif = Order.Types.TimeInForce.Day, - T algo_order_params = default(T)) where T : new() - { - Order ord = ActorMapping.create_order_of_type(algo_order_params); - ord.Id = generate_order_id(); - ord.Security = sec; - ord.Price = price; - ord.Size = size; - ord.Side = side; - ord.TimeInForce = tif; - - Type actor_type; - ActorMapping.order_actor_mapping.TryGetValue(ord.AlgoOrderTypeCase, out actor_type); - IOrderHandle algoorder = _fabric.create(actor_type, ord); - return algoorder; - } - + protected IOrderHandle spawn_limit_order(Security sec, uint size, double price, BuySell side, Order.Types.TimeInForce tif = Order.Types.TimeInForce.Day) { @@ -85,7 +38,7 @@ namespace mbts.spark.orders ord.Side = side; ord.TimeInForce = tif; IOrderHandle algoorder = _fabric.create(ord); - track_child(ord.Id, algoorder); + track_child(algoorder); algoorder.spawn(); return algoorder; } @@ -101,7 +54,7 @@ namespace mbts.spark.orders ord.Side = side; ord.TimeInForce = tif; IOrderHandle algoorder = _fabric.create(ord); - track_child(ord.Id, algoorder); + track_child(algoorder); algoorder.spawn(); return algoorder; } @@ -118,7 +71,7 @@ namespace mbts.spark.orders ord.Side = side; ord.TimeInForce = tif; IOrderHandle algoorder = _fabric.create(ord); - track_child(ord.Id, algoorder); + track_child(algoorder); algoorder.spawn(); return algoorder; } @@ -135,7 +88,7 @@ namespace mbts.spark.orders ord.Side = side; ord.TimeInForce = tif; IOrderHandle algoorder = _fabric.create(ord); - track_child(ord.Id, algoorder); + track_child(algoorder); algoorder.spawn(); return algoorder; } @@ -154,42 +107,29 @@ namespace mbts.spark.orders do_to_children(async x => await x.cancel() ); } - protected void flatten_synthetic(Order order, out IDictionary ratios, out IDictionary price_mults) + override protected List child_status_list() { - ratios = new Dictionary(); - price_mults = new Dictionary(); - crack_synthetic(order.Security, ratios, price_mults, order.Side, order.Size); + var statlist = new List(); + foreach(var stat in _child_status.Values) + statlist.Add(stat.Status); + return statlist; } - //break the synthetic into a dictionary of listed sub-securities and the proper signed quantity per leg - void crack_synthetic(Security security, IDictionary listed_vs_signed_size, - IDictionary listed_vs_price_mult, - BuySell side = BuySell.Buy, uint quantity = 1) + override protected void on_child_status(OrderStatus child_status, ref OrderStatus merged_status) { - if(security.ContractCase == Security.ContractOneofCase.Synthetic) + if(is_done_state(child_status.Status)) { - foreach(var leg in security.Synthetic.Legs) - { - if(leg.Security.ContractCase == Security.ContractOneofCase.Synthetic) - crack_synthetic(leg.Security, listed_vs_signed_size, listed_vs_price_mult, side, quantity); - else - { - listed_vs_signed_size.Add(leg.Security, leg.Quantity * (leg.Side == BuySell.Sell ? -1 : 1) * - quantity * (side == BuySell.Sell ? -1 : 1)); - listed_vs_price_mult.Add(leg.Security, leg.PriceMultiplier); - } - } - } - else - { - listed_vs_signed_size.Add(security, quantity * (side == BuySell.Sell ? -1 : 1)); - listed_vs_price_mult.Add(security, 1.0); + IOrderHandle handle; + 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)); } - protected void track_child(OrderID order_id, IOrderHandle algo) + override protected void track_child(IOrderHandle algo) { - _children[order_id] = algo; + _children[algo.order_id] = algo; _disposables.Add(algo.order_status.Subscribe(x => { _child_status[x.Order.Id] = x; @@ -201,163 +141,5 @@ namespace mbts.spark.orders compute_fill_internal(x); })); } - - protected OrderStatus.Types.Status merge_status(List statlist) - { - OrderStatus.Types.Status newstatus = OrderStatus.Types.Status.Undefined; - if(statlist.All(x => x == OrderStatus.Types.Status.PendingNew || x == OrderStatus.Types.Status.New)) - newstatus = OrderStatus.Types.Status.PendingNew; - if(statlist.All(x => x == OrderStatus.Types.Status.New)) - newstatus = OrderStatus.Types.Status.New; - - if(statlist.Any(x => x == OrderStatus.Types.Status.PartiallyFilled || x == OrderStatus.Types.Status.Filled)) - newstatus = OrderStatus.Types.Status.PartiallyFilled; - if(statlist.All(x => x == OrderStatus.Types.Status.Filled)) - newstatus = OrderStatus.Types.Status.Filled; - - if(statlist.Any(x => x == OrderStatus.Types.Status.PendingCancel || x == OrderStatus.Types.Status.Canceled)) - newstatus = OrderStatus.Types.Status.PendingCancel; - if(statlist.All(x => x == OrderStatus.Types.Status.Canceled)) - newstatus = OrderStatus.Types.Status.Canceled; - - if(statlist.Any(x => x == OrderStatus.Types.Status.PendingReplace|| x == OrderStatus.Types.Status.Replaced)) - newstatus = OrderStatus.Types.Status.PendingReplace; - if(statlist.All(x => x == OrderStatus.Types.Status.Replaced)) - newstatus = OrderStatus.Types.Status.Replaced; - - if(statlist.Any(x => x == OrderStatus.Types.Status.PendingReplace || x == OrderStatus.Types.Status.Replaced)) - newstatus = OrderStatus.Types.Status.PendingReplace; - if(statlist.All(x => x == OrderStatus.Types.Status.Replaced)) - newstatus = OrderStatus.Types.Status.Replaced; - - if(statlist.Any(x => x == OrderStatus.Types.Status.Stopped)) - { - newstatus = OrderStatus.Types.Status.Stopped; - return newstatus; - } - if(statlist.Any(x => x == OrderStatus.Types.Status.Rejected)) - { - newstatus = OrderStatus.Types.Status.Rejected; - return newstatus; - } - if(statlist.Any(x => x == OrderStatus.Types.Status.Suspended)) - { - newstatus = OrderStatus.Types.Status.Suspended; - return newstatus; - } - if(statlist.Any(x => x == OrderStatus.Types.Status.Calculated)) - { - newstatus = OrderStatus.Types.Status.Calculated; - return newstatus; - } - if(statlist.Any(x => x == OrderStatus.Types.Status.AcceptedForBidding)) - { - newstatus = OrderStatus.Types.Status.AcceptedForBidding; - return newstatus; - } - var dist = statlist.Distinct(); - if(dist.Count() == 1) - newstatus = dist.First(); - else if(statlist.All(x => is_done_state(x))) - newstatus = OrderStatus.Types.Status.Done; - - return newstatus; - } - virtual protected List child_status_list() - { - var statlist = new List(); - foreach(var stat in _child_status.Values) - statlist.Add(stat.Status); - return statlist; - } - - protected void compute_status_internal(OrderStatus child_status) - { - OrderStatus merged = new OrderStatus(); - merged.Order = _order == null ? new Order() : _order.Clone(); - - List statlist = child_status_list(); - merged.Status = merge_status(statlist); - - if(is_done_state(child_status.Status)) - { - IOrderHandle handle; - if(_children.TryRemove(child_status.Order.Id, out handle)) - _ex_children.TryAdd(child_status.Order.Id, handle); - } - merged.Children.AddRange(_children.Select(x => x.Key)); - merged.Children.AddRange(_ex_children.Select(x => x.Key)); - on_child_status(child_status, ref merged); - - _status_sink.OnNext(child_status); - if(merged != null) - { - _status_sink.OnNext(merged); - if(is_done_state(merged.Status)) - exit(); - if(is_problem_state(merged.Status)) - exit("parent order problem state"); - } - if(is_problem_state(child_status.Status)) - exit("child order problem state"); - } - protected virtual void on_child_status(OrderStatus child_status, ref OrderStatus merged_status) { } - - void compute_fill_internal(Fill child_fill) - { - Fill merged = null; - on_child_fill(child_fill, ref merged); - _fills_sink.OnNext(child_fill); - if(merged != null) - _fills_sink.OnNext(merged); - } - protected virtual void on_child_fill(Fill child_fill, ref Fill merged_fill) { } - - protected bool is_done_state(OrderStatus.Types.Status stat) - { - return stat == OrderStatus.Types.Status.Canceled || - stat == OrderStatus.Types.Status.Done || - stat == OrderStatus.Types.Status.Expired || - stat == OrderStatus.Types.Status.Filled; - } - - protected bool is_problem_state(OrderStatus.Types.Status stat) - { - return stat == OrderStatus.Types.Status.Undefined || - stat == OrderStatus.Types.Status.Stopped || - stat == OrderStatus.Types.Status.Rejected || - stat == OrderStatus.Types.Status.Suspended || - stat == OrderStatus.Types.Status.Calculated || - stat == OrderStatus.Types.Status.AcceptedForBidding - ; - } - - protected double compute_tick(Security sec) - { - return sec.ContractSpec.LowTick; - } - - readonly protected Subject _status_sink = new Subject(); - public IObservable order_status - { - get { return _status_sink; } - } - - readonly protected Subject _fills_sink = new Subject(); - public IObservable fills - { - get { return _fills_sink; } - } - - protected void exit(string error = null) - { - _fabric.destroy(this, error); - } - - public abstract void on_spawn(); - public virtual void on_destroy() - { - _disposables.ForEach(x => x.Dispose()); - } } } diff --git a/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleHedgeOrderActor.cs b/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleHedgeOrderActor.cs new file mode 100644 index 000000000..05179f548 --- /dev/null +++ b/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleHedgeOrderActor.cs @@ -0,0 +1,118 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using System.Linq; + +using bts.api; +using bts.spark; +using mbts.co2; + +using BBOType = System.Tuple; + +namespace mbts.spark.orders +{ + class SimpleHedgeOrderActor : SimpleOrderBase, ICancelable, IModifiable + { + readonly IMarketDataSource _md; + readonly IExchangeGateway _exchange; + readonly IDropCopy _dc; + OrderStatus _status; + readonly double _tick; + public SimpleHedgeOrderActor(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); + _tick = compute_tick(order.Security); + } + + override protected List child_status_list() + { + var stat = new List(); + if(_status != null) + stat.Add(_status.Status); + return stat; + } + + override protected void on_child_status(OrderStatus child_status, ref OrderStatus merged_status) + { + _status = child_status; + if(_status.Order?.Id != null) + merged_status.Children.Add(_status.Order.Id); + } + + public override void on_spawn() + { + _disposables.Add(_md.subscribe_bbo(_order.Security).Subscribe(x => + { + if(x != null) + watch_hedges(x); + })); + _disposables.Add(_dc.subscribe_fills(new Predicate(x => _order.Id.Equals(x.Order.Id))).Subscribe(x => + { + compute_fill_internal(x); + })); + _disposables.Add(_dc.subscribe_status(new Predicate(x => _order.Id.Equals(x.Order.Id))).Subscribe(x => + { + compute_status_internal(x); + })); + + var clone = _order.Clone(); + clone.LimitOrder = new LimitOrder(); + _exchange.send_order(clone); + } + + void watch_hedges(BBOType bbo) + { + if(_status != null) + { + PriceSize inside_market; + if(_status.Order.Side == BuySell.Buy) + inside_market = bbo.Item2; + else + inside_market = bbo.Item1; + + evaluate_post_hedge_rules(inside_market); + } + } + + void evaluate_post_hedge_rules(PriceSize inside_market) + { + PostHedgePriceBasedForcedCross post = _order.SimpleHedgeOrder.Post; + if(post == null || _status == null || post.TicksThreshold == 0 || post.MarketCrossTicks == 0) + return; + + if(_status.Order.Side == BuySell.Buy) + { + uint diff = Convert.ToUInt32((inside_market.price - _status.Order.Price) / _tick); + if(diff >= post.TicksThreshold) + _exchange.modify_price(_order.Id, _status.Order.Price + _tick * post.MarketCrossTicks); + } + else + { + uint diff = Convert.ToUInt32((_status.Order.Price - inside_market.price) / _tick); + if(diff >= post.TicksThreshold) + _exchange.modify_price(_order.Id, _status.Order.Price - _tick * post.MarketCrossTicks); + } + } + + bool ICancelable.on_cancel() + { + _exchange.cancel_order(_order.Id); + return true; + } + + bool IModifiable.on_modify_price(double new_price) + { + _exchange.modify_price(_order.Id, new_price); + return true; + } + + bool IModifiable.on_modify_size(uint new_size) + { + _exchange.modify_size(_order.Id, new_size); + return true; + } + } +} diff --git a/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleOrderBase.cs b/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleOrderBase.cs new file mode 100644 index 000000000..b6a56a54c --- /dev/null +++ b/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleOrderBase.cs @@ -0,0 +1,264 @@ +using System; +using System.Collections.Generic; +using System.Collections.Concurrent; +using System.Reactive.Subjects; +using System.Threading.Tasks; +using System.Linq; + +using bts.api; +using bts.spark; +using mbts.co2; + + +namespace mbts.spark.orders +{ + abstract class SimpleOrderBase : IActor, IOrderStatusProducer, IFillProducer + { + readonly protected List _disposables = new List(); + readonly IOrderIDGenerator _generator; + protected readonly IActorFabric _fabric; + protected readonly Order _order; + + public SimpleOrderBase(IActorFabric fabric, Order order) + { + _order = order.Clone(); + _fabric = fabric; + _fabric.find_wellknown_service(out _generator); + guid = Guid.NewGuid(); + } + public Guid guid { get; private set; } + + static protected void flatten_synthetic(Order order, out IDictionary ratios, out IDictionary price_mults) + { + ratios = new Dictionary(); + price_mults = new Dictionary(); + crack_synthetic(order.Security, ratios, price_mults, order.Side); + } + + //break the synthetic into a dictionary of listed sub-securities and the proper signed quantity per leg + static void crack_synthetic(Security security, IDictionary listed_vs_signed_ratio, + IDictionary listed_vs_price_mult, + BuySell side = BuySell.Buy, uint quantity = 1) + { + if(security.ContractCase == Security.ContractOneofCase.Synthetic) + { + foreach(var leg in security.Synthetic.Legs) + { + if(leg.Security.ContractCase == Security.ContractOneofCase.Synthetic) + crack_synthetic(leg.Security, listed_vs_signed_ratio, listed_vs_price_mult, side, quantity); + else + { + listed_vs_signed_ratio.Add(leg.Security, leg.Quantity * (leg.Side == BuySell.Sell ? -1 : 1) * + quantity * (side == BuySell.Sell ? -1 : 1)); + listed_vs_price_mult.Add(leg.Security, leg.PriceMultiplier == 0.0 ? 1.0 : leg.PriceMultiplier); + } + } + } + else + { + listed_vs_signed_ratio.Add(security, quantity * (side == BuySell.Sell ? -1 : 1)); + listed_vs_price_mult.Add(security, 1.0); + } + } + + static readonly ConcurrentQueue _orderids = new ConcurrentQueue(); + protected OrderID generate_order_id() + { + //TODO we need to rework this when things have to go fast.... + if(_orderids.Count == 0) + { + const int nids = 100; + OrderID[] oids; + _generator.generate_order_ids(nids, out oids); + oids.ForEach(x => _orderids.Enqueue(x)); + } + OrderID id; + var succ = _orderids.TryDequeue(out id); + if(!succ) + throw new NotSupportedException(); + //id.Id = this.GetType().Name + " " + id.Id; + return id; + } + + protected IOrderHandle create_order(Security sec, uint size, double price, BuySell side, + Order.Types.TimeInForce tif = Order.Types.TimeInForce.Day, + T algo_order_params = default(T)) where T : new() + { + Order ord = ActorMapping.create_order_of_type(algo_order_params); + ord.Id = generate_order_id(); + ord.Security = sec; + ord.Price = price; + ord.Size = size; + ord.Side = side; + ord.TimeInForce = tif; + + Type actor_type; + ActorMapping.order_actor_mapping.TryGetValue(ord.AlgoOrderTypeCase, out actor_type); + IOrderHandle algoorder = _fabric.create(actor_type, ord); + return algoorder; + } + + virtual protected void track_child(IOrderHandle algo) + { + _disposables.Add(algo.order_status.Subscribe(x => + { + compute_status_internal(x); + })); + _disposables.Add(algo.fills.Subscribe(x => + { + compute_fill_internal(x); + })); + } + + static protected OrderStatus.Types.Status merge_status(List statlist) + { + if(!statlist.Any()) + return OrderStatus.Types.Status.New; + OrderStatus.Types.Status newstatus = OrderStatus.Types.Status.Undefined; + if(statlist.All(x => x == OrderStatus.Types.Status.PendingNew || x == OrderStatus.Types.Status.New)) + newstatus = OrderStatus.Types.Status.PendingNew; + if(statlist.All(x => x == OrderStatus.Types.Status.New)) + newstatus = OrderStatus.Types.Status.New; + + if(statlist.Any(x => x == OrderStatus.Types.Status.PartiallyFilled || x == OrderStatus.Types.Status.Filled)) + newstatus = OrderStatus.Types.Status.PartiallyFilled; + if(statlist.All(x => x == OrderStatus.Types.Status.Filled)) + newstatus = OrderStatus.Types.Status.Filled; + + if(statlist.Any(x => x == OrderStatus.Types.Status.PendingCancel || x == OrderStatus.Types.Status.Canceled)) + newstatus = OrderStatus.Types.Status.PendingCancel; + if(statlist.All(x => x == OrderStatus.Types.Status.Canceled)) + newstatus = OrderStatus.Types.Status.Canceled; + + if(statlist.Any(x => x == OrderStatus.Types.Status.PendingReplace || x == OrderStatus.Types.Status.Replaced)) + newstatus = OrderStatus.Types.Status.PendingReplace; + if(statlist.All(x => x == OrderStatus.Types.Status.Replaced)) + newstatus = OrderStatus.Types.Status.Replaced; + + if(statlist.Any(x => x == OrderStatus.Types.Status.PendingReplace || x == OrderStatus.Types.Status.Replaced)) + newstatus = OrderStatus.Types.Status.PendingReplace; + if(statlist.All(x => x == OrderStatus.Types.Status.Replaced)) + newstatus = OrderStatus.Types.Status.Replaced; + + if(statlist.Any(x => x == OrderStatus.Types.Status.Stopped)) + { + newstatus = OrderStatus.Types.Status.Stopped; + return newstatus; + } + if(statlist.Any(x => x == OrderStatus.Types.Status.Rejected)) + { + newstatus = OrderStatus.Types.Status.Rejected; + return newstatus; + } + if(statlist.Any(x => x == OrderStatus.Types.Status.Suspended)) + { + newstatus = OrderStatus.Types.Status.Suspended; + return newstatus; + } + if(statlist.Any(x => x == OrderStatus.Types.Status.Calculated)) + { + newstatus = OrderStatus.Types.Status.Calculated; + return newstatus; + } + if(statlist.Any(x => x == OrderStatus.Types.Status.AcceptedForBidding)) + { + newstatus = OrderStatus.Types.Status.AcceptedForBidding; + return newstatus; + } + var dist = statlist.Distinct(); + if(dist.Count() == 1) + newstatus = dist.First(); + else if(statlist.All(x => is_done_state(x))) + newstatus = OrderStatus.Types.Status.Done; + + return newstatus; + } + + protected void compute_status_internal(OrderStatus child_status) + { + OrderStatus merged = new OrderStatus(); + merged.Order = _order == null ? new Order() : _order.Clone(); + + on_child_status(child_status, ref merged); + List statlist = child_status_list(); + merged.Status = merge_status(statlist); + + _status_sink.OnNext(child_status); + if(merged != null) + { + _status_sink.OnNext(merged); + if(is_done_state(merged.Status)) + exit(); + if(is_problem_state(merged.Status)) + exit("parent order problem state"); + } + if(is_problem_state(child_status.Status)) + exit("child order problem state"); + } + + abstract protected List child_status_list(); + protected virtual void on_child_status(OrderStatus child_status, ref OrderStatus merged_status) { } + + protected void compute_fill_internal(Fill child_fill) + { + Fill merged = null; + on_child_fill(child_fill, ref merged); + _fills_sink.OnNext(child_fill); + if(merged != null) + _fills_sink.OnNext(merged); + } + protected virtual void on_child_fill(Fill child_fill, ref Fill merged_fill) { } + + static protected bool is_done_state(OrderStatus.Types.Status stat) + { + return stat == OrderStatus.Types.Status.Canceled || + stat == OrderStatus.Types.Status.Done || + stat == OrderStatus.Types.Status.Expired || + stat == OrderStatus.Types.Status.Filled; + } + + static protected bool is_problem_state(OrderStatus.Types.Status stat) + { + return stat == OrderStatus.Types.Status.Undefined || + stat == OrderStatus.Types.Status.Stopped || + stat == OrderStatus.Types.Status.Rejected || + stat == OrderStatus.Types.Status.Suspended || + stat == OrderStatus.Types.Status.Calculated || + stat == OrderStatus.Types.Status.AcceptedForBidding + ; + } + static protected bool is_final_state(OrderStatus.Types.Status status) + { + return is_done_state(status) || is_problem_state(status); + } + + protected double compute_tick(Security sec) + { + return sec.ContractSpec.LowTick; + } + + readonly protected Subject _status_sink = new Subject(); + public IObservable order_status + { + get { return _status_sink; } + } + + readonly protected Subject _fills_sink = new Subject(); + public IObservable fills + { + get { return _fills_sink; } + } + + + protected virtual void exit(string error = null) + { + _fabric.destroy(this, error); + } + + public abstract void on_spawn(); + public virtual void on_destroy() + { + _disposables.ForEach(x => x.Dispose()); + } + } +} diff --git a/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleSyntheticLimitOrder.cs b/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleSyntheticLimitOrder.cs new file mode 100644 index 000000000..1f2107d14 --- /dev/null +++ b/src/client/spark/mspark/Algo/Orders/SimpleSpreader/SimpleSyntheticLimitOrder.cs @@ -0,0 +1,358 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; + +using bts.api; +using bts.spark; +using mbts.co2; + +using BookType = System.Tuple; + +namespace mbts.spark.orders +{ + + class SpreaderLegOrderInfo + { + public IOrderHandle handle; + public double last_hedge_price; + } + + struct SpreaderLeg + { + public readonly Security security; + public readonly SimpleExecutionParams param; + public readonly double ratio; + public readonly double mult; + public readonly double tick; + + public BookType book; + public OrderStatus status; + public SpreaderLegOrderInfo order_info; + public SpreaderLeg(Security sec, SimpleExecutionParams para, double ratio, double mult, double tick) + { + this.security = sec; + this.param = para; + this.ratio = ratio; + this.mult = mult; + this.tick = tick; + + this.book = null; + this.status = null; + this.order_info = new SpreaderLegOrderInfo(); + } + } + + class SimpleSyntheticLimitOrder : SimpleOrderBase, IActor, ICancelable, IModifiable + { + readonly IMarketDataSource _md; + + SpreaderLeg _leg1, _leg2; + readonly ConcurrentDictionary _hedges = new ConcurrentDictionary(); + readonly ConcurrentDictionary _status = new ConcurrentDictionary(); + public SimpleSyntheticLimitOrder(IActorFabric fabric, Order order) : base(fabric, order) + { + IDictionary leg_ratios; + IDictionary price_mults; + flatten_synthetic(order, out leg_ratios, out price_mults); + foreach(var sec in leg_ratios.Keys) + { + if(sec.ContractCase == Security.ContractOneofCase.Synthetic) + throw new NotSupportedException("Nested Synthetics not supported"); + fabric.find_wellknown_service(sec.Exchange, out _md); + } + if(leg_ratios.Keys.Count != 2) + throw new NotSupportedException("Simple Synthetic Only Supports 2 Legs"); + + SimpleExecutionStrategy simple = order.SimpleExecutionStrategy; + //map the current UI to this new simple mode + if(simple == null && order.ExecutionStrategy != null) + { + var map = order.ExecutionStrategy.SecurityIdToParams; + Security sec1 = leg_ratios.Keys.First(); + Security sec2 = leg_ratios.Keys.Last(); + + SyntheticLegExecutionParams old1 = map[sec1.Id], old2 = map[sec2.Id]; + SimpleExecutionParams s1 = convert_exec_params(sec1, old1), s2 = convert_exec_params(sec2, old2); + _leg1 = new SpreaderLeg(sec1, s1, leg_ratios[sec1], price_mults[sec1], compute_tick(sec1)); + _leg2 = new SpreaderLeg(sec2, s2, leg_ratios[sec2], price_mults[sec2], compute_tick(sec2)); + } + else + { + Security sec1 = order.SimpleExecutionStrategy.Leg1.Security; + Security sec2 = order.SimpleExecutionStrategy.Leg2.Security; + _leg1 = new SpreaderLeg(sec1, order.SimpleExecutionStrategy.Leg1, leg_ratios[sec1], price_mults[sec1], compute_tick(sec1)); + _leg2 = new SpreaderLeg(sec2, order.SimpleExecutionStrategy.Leg2, leg_ratios[sec2], price_mults[sec2], compute_tick(sec2)); + } + } + + SimpleExecutionParams convert_exec_params(Security sec, SyntheticLegExecutionParams old) + { + uint slop = 0; + var ss = old.QuoteParams?.TickRangeRequoteRules?.TicksAwayToSensitivity?.FirstOrDefault(); + if(ss.HasValue) + slop = ss.Value.Value; + int payup = 0; + var pu = old.HedgeParams?.PayupHedgeRules; + if(pu != null && pu.EnablePayup) + payup = Convert.ToInt32(pu.PayupTicks); + var pl = old.HedgeParams?.PaylessHedgeRules; + if(pl != null && pl.EnablePayless) + payup = -Convert.ToInt32(pu.PayupTicks); + var post = old.HedgeParams?.PostHedgeRules; + + var s = new SimpleExecutionParams() + { + IsHedging = true, + IsWorking = old.QuoteParams.IsWorking, + Security = sec, + Slop = new QuoteMuteZone { InsideTicks = slop, OutsideTicks = slop }, + PreHedgePayupTicks = payup, + Post = new PostHedgePriceBasedForcedCross + { + MarketCrossTicks = post == null ? 0 : post.CrossSizeThreshold, + TicksThreshold = post == null ? 0 : Convert.ToUInt32(post.CrossRatioThreshold), + }, + }; + return s; + } + + override protected List child_status_list() + { + return _status.Values.Select(x => x.Status).ToList(); + } + override protected void on_child_status(OrderStatus child_status, ref OrderStatus merged_status) + { + if(child_status.Order.Security.Equals(_leg1.security)) + _leg1.status = child_status; + if(child_status.Order.Security.Equals(_leg2.security)) + _leg2.status = child_status; + + if(_leg1.order_info.handle != null) + merged_status.Children.Add(_leg1.order_info.handle.order_id); + if(_leg2.order_info.handle != null) + merged_status.Children.Add(_leg2.order_info.handle.order_id); + _status[child_status.Order.Id] = child_status; + } + + + override public void on_spawn() + { + _disposables.Add(_md.subscribe_depth(_leg1.security).Subscribe(x => + { + BookType transformed = Tuple.Create(x.Item1.Select(xx => new PriceSize(xx.price * _leg1.mult, xx.size)).ToArray(), + x.Item2.Select(xx => new PriceSize(xx.price * _leg1.mult, xx.size)).ToArray()); + _leg1.book = transformed; + requote(_leg2, _leg1); + })); + + _disposables.Add(_md.subscribe_depth(_leg2.security).Subscribe(x => + { + BookType transformed = Tuple.Create(x.Item1.Select(xx => new PriceSize(xx.price * _leg2.mult, xx.size)).ToArray(), + x.Item2.Select(xx => new PriceSize(xx.price * _leg2.mult, xx.size)).ToArray()); + _leg2.book = transformed; + requote(_leg1, _leg2); + })); + } + + public override void on_destroy() + { + base.on_destroy(); + } + + #region Quoting + + //always pessimistic + bool walk_book(PriceSize[] book, uint size, out double leg_price) + { + bool ok = false; leg_price = double.NaN; + uint agg = 0; + foreach(var level in book) + { + agg += level.size; + if(agg >= size) + { + leg_price = level.price; + ok = true; + break; + } + } + if(leg_price == 0.0) + leg_price = double.NaN; + return ok; + } + + void new_quote_order(Security security, uint quote_size, double quote_price, BuySell quote_side, double hedge_price, + SpreaderLegOrderInfo order_info) + { + order_info.handle = create_order(security, quote_size, quote_price, quote_side, _order.TimeInForce, new LimitOrder()); + order_info.last_hedge_price = hedge_price; //cache this for later + track_child(order_info.handle); + order_info.handle.spawn(); + } + + void replace_quote_order(SpreaderLeg quote_leg, double hedge_price, ref double quote_price) + { + if(evaluate_prequote_rules(quote_leg, ref quote_price)) + { + if(double.IsNaN(quote_price)) + quote_leg.order_info.handle.cancel(); + else + { + quote_leg.order_info.handle.modify_price(quote_price); + quote_leg.order_info.last_hedge_price = hedge_price; //cache this for later + } + } + } + + void requote_all() + { + requote(_leg1, _leg2); + requote(_leg2, _leg1); + } + + //reprice the quote leg in terms of the hedge leg + void requote(SpreaderLeg quote_leg, SpreaderLeg hedge_leg) + { + if(quote_leg.status != null && is_final_state(quote_leg.status.Status)) + return; + if(!quote_leg.param.IsWorking) + return; + + double quote_price = _order.Price * -1.0; + + int hedge_size_signed = Convert.ToInt32(_order.Size * hedge_leg.ratio); + int hedge_side = (hedge_size_signed < 0 ? -1 : 1); + uint hedge_size = Convert.ToUInt32(Math.Abs(hedge_size_signed)); + + double hedge_price_at_size = double.NaN; + if(hedge_side < 0) + walk_book(hedge_leg.book.Item1, hedge_size, out hedge_price_at_size); + else + walk_book(hedge_leg.book.Item2, hedge_size, out hedge_price_at_size); + + quote_price += hedge_side * hedge_price_at_size * (_order.Side == BuySell.Sell ? -1 : 1); + quote_price = Math.Round(Math.Abs(quote_price) / quote_leg.tick, MidpointRounding.AwayFromZero) * quote_leg.tick; + + if(quote_leg.order_info.handle == null && !double.IsNaN(quote_price)) //new order + { + int quote_size_signed = Convert.ToInt32(_order.Size * quote_leg.ratio); + BuySell quote_side = (quote_size_signed < 0 ? BuySell.Sell : BuySell.Buy); + uint quote_size = Convert.ToUInt32(Math.Abs(quote_size_signed)); + new_quote_order(quote_leg.security, quote_size, quote_price, quote_side, hedge_price_at_size, quote_leg.order_info); + } + else + replace_quote_order(quote_leg, hedge_price_at_size, ref quote_price); + } + + //one day this could modify size, do a fancy rule chain, etc + bool evaluate_prequote_rules(SpreaderLeg quote_leg, ref double quote_price) + { + SimpleExecutionParams param = quote_leg.param; + if(param.Slop != null) + { + double? orig_price = quote_leg.status?.Order.Price; + if(orig_price.HasValue) + { + int diff = Convert.ToInt32((quote_price - orig_price) / quote_leg.tick); + if(diff != 0) + { + if(quote_leg.status.Order.Side == BuySell.Buy) + { + if(diff >= param.Slop.InsideTicks || diff <= -param.Slop.OutsideTicks) + return true; + } + else + { + if(diff <= -param.Slop.InsideTicks || diff >= param.Slop.OutsideTicks) + return true; + } + } + } + return false; + } + return true; + } + + #endregion + + #region Hedging + + protected override void on_child_fill(Fill child_fill, ref Fill merged_fill) + { + if(!_hedges.ContainsKey(child_fill.Order.Id)) + hedge_fill(child_fill); + } + + void reduce_working_order(OrderStatus quote_leg_status, SpreaderLegOrderInfo order_info, uint hedge_size) + { + if(order_info.handle != null && quote_leg_status != null && !is_final_state(quote_leg_status.Status)) + { + if(hedge_size < quote_leg_status.Order.Size) + order_info.handle.modify_size(quote_leg_status.Order.Size - hedge_size); + else + order_info.handle.cancel(); + } + } + + void hedge_fill(Fill fill) + { + SpreaderLeg quote_leg, hedge_leg; + if(fill.Order.Security.Equals(_leg1.security)) + { + quote_leg = _leg1; + hedge_leg = _leg2; + } + else + { + quote_leg = _leg2; + hedge_leg = _leg1; + } + if(!hedge_leg.param.IsHedging) + return; + + double hedge_size_signed = hedge_leg.ratio * fill.Size * (fill.Side == BuySell.Buy ? 1.0 : -1.0); + var hedge_side = (hedge_size_signed > 0.0) ? BuySell.Buy : BuySell.Sell; + uint hedge_size = Convert.ToUInt32(Math.Abs(hedge_size_signed)); + reduce_working_order(hedge_leg.status, hedge_leg.order_info, hedge_size); + double hedge_price = quote_leg.order_info.last_hedge_price + hedge_leg.param.PreHedgePayupTicks * hedge_leg.tick; + + var rules = new SimpleHedgeOrder { Post = hedge_leg.param.Post }; + var hedge = create_order(hedge_leg.security, hedge_size, hedge_price, + hedge_side, Order.Types.TimeInForce.Day, rules); + _hedges[hedge.order_id] = null; + track_child(hedge); + hedge.spawn(); + } + + #endregion + + + bool ICancelable.on_cancel() + { + if(_leg1.order_info.handle != null) + _leg1.order_info.handle.cancel(); + if(_leg2.order_info.handle != null) + _leg2.order_info.handle.cancel(); + return true; + } + + bool IModifiable.on_modify_price(double new_price) + { + _order.Price = new_price; + requote_all(); + return true; + } + + bool IModifiable.on_modify_size(uint new_size) + { + _order.Size = new_size; + _leg1.order_info.handle?.cancel(); + _leg1.order_info = null; + _leg2.order_info.handle?.cancel(); + _leg2.order_info = null; + requote_all(); + return true; + } + } +} diff --git a/src/client/spark/mspark/Algo/Orders/StopLimitOrderActor.cs b/src/client/spark/mspark/Algo/Orders/Stop/StopLimitOrderActor.cs similarity index 100% rename from src/client/spark/mspark/Algo/Orders/StopLimitOrderActor.cs rename to src/client/spark/mspark/Algo/Orders/Stop/StopLimitOrderActor.cs diff --git a/src/client/spark/mspark/Algo/Orders/StopMarketOrderActor.cs b/src/client/spark/mspark/Algo/Orders/Stop/StopMarketOrderActor.cs similarity index 100% rename from src/client/spark/mspark/Algo/Orders/StopMarketOrderActor.cs rename to src/client/spark/mspark/Algo/Orders/Stop/StopMarketOrderActor.cs diff --git a/src/client/spark/mspark/Algo/Scratch/QuoteLegQuantityState.cs b/src/client/spark/mspark/Algo/Scratch/QuoteLegQuantityState.cs new file mode 100644 index 000000000..483ce793e --- /dev/null +++ b/src/client/spark/mspark/Algo/Scratch/QuoteLegQuantityState.cs @@ -0,0 +1,123 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + + +namespace mbts.spark +{ + public class QuoteLegPriceQuantityState + { + /// These are set by the users + private double _target_spread_price; + private Nullable _leg_price_override; + private uint _target_leg_qty; + + /// As fills come in _aggregated_filled_qty is updated. + private uint _aggregated_hedged_qty, + /// As other legs are filled, this is updated + _aggregated_filled_qty; + + private double _computed_price; + private uint _computed_qty; + + public double out_price = Double.NaN; + public uint out_qty = 0; + + private readonly Func> _price_qty_evaluator; + + public QuoteLegPriceQuantityState(double target_spread_price, + uint target_leg_qty, + uint aggregated_hedged_qty, + uint aggregated_filled_qty, + Func> price_qty_evaluator) + { + _target_spread_price = target_spread_price; + _target_leg_qty = target_leg_qty; + _aggregated_hedged_qty = aggregated_hedged_qty; + _aggregated_filled_qty = aggregated_filled_qty; + _price_qty_evaluator = price_qty_evaluator; + _update_output(); + } + + private void _update_output() + { + /// ignore leg price override for now + if (_aggregated_filled_qty >= _target_leg_qty) + { + _computed_qty = 0; + _computed_price = Double.NaN; + } + else + { + uint hedge_adjusted_qty = _target_leg_qty - _aggregated_filled_qty; + if (_aggregated_filled_qty >= hedge_adjusted_qty) + { + _computed_qty = 0; + _computed_price = Double.NaN; + } + else + { + uint remainder_to_get_qty = hedge_adjusted_qty - _aggregated_filled_qty; + Tuple price_qty = _price_qty_evaluator(remainder_to_get_qty); + if (price_qty.Item2 == 0) + { + _computed_qty = 0; + _computed_price = Double.NaN; + } + else + { + _computed_qty = price_qty.Item2 + _aggregated_filled_qty; + _computed_price = price_qty.Item1; + } + } + } + } + + public void update_hedges(uint normalized_qty) + { + _aggregated_hedged_qty += normalized_qty; + _update_output(); + } + + public void update_fills(uint filled_qty) + { + _aggregated_filled_qty += filled_qty; + _update_output(); + } + + public void update_target_leg_qty(uint target_leg_qty) + { + _target_leg_qty = target_leg_qty; + _update_output(); + } + + public void update_target_spread_price(double target_spread_price) + { + _target_spread_price = target_spread_price; + _update_output(); + } + + public void update_target_leg_price(double target_leg_price) + { + _leg_price_override = target_leg_price; + _update_output(); + } + + public void update_md() + { + _update_output(); + } + + public uint target_leg_qty { get { return _target_leg_qty; } } + + public uint aggregated_filled_qty { get { return _aggregated_filled_qty; } } + + public uint aggegated_hedged_qty { get { return _aggregated_hedged_qty; } } + + public uint computed_qty { get { return _computed_qty; } } + + public double computed_price { get { return _computed_price; } } + } +} diff --git a/src/client/spark/mspark/Algo/Scratch/ScratchPad.cs b/src/client/spark/mspark/Algo/Scratch/ScratchPad.cs index 401a9f9fc..69cdd5442 100644 --- a/src/client/spark/mspark/Algo/Scratch/ScratchPad.cs +++ b/src/client/spark/mspark/Algo/Scratch/ScratchPad.cs @@ -6,7 +6,7 @@ using System.Threading.Tasks; namespace mbts.spark { - public class OrderOperationResult + internal class OrderOperationResult { public readonly bool success; public readonly string details; @@ -18,13 +18,13 @@ namespace mbts.spark } } - public interface IOrderStateWatcher + internal interface IOrderStateWatcher { void on_order_status(bts.spark.OrderID order_id, bts.spark.OrderStatus.Types.Status status); void on_fills(bts.spark.OrderID order_id, bts.api.BuySell side, uint qty, double price); } - interface IOrderManager : IOrderStateWatcher + internal interface IOrderManager : IOrderStateWatcher { OrderOperationResult initialize(IAlgoHyperLoop algo_hyper_loop, bts.spark.Order order); OrderOperationResult modify_order(bts.spark.Order order); @@ -36,7 +36,7 @@ namespace mbts.spark void time_quantam(); } - interface IAlgoHyperLoop + internal interface IAlgoHyperLoop { /// Internal calls from within the application OrderOperationResult send_order(IOrderManager order_manager, bts.spark.Order order); @@ -51,4 +51,53 @@ namespace mbts.spark void send_fill_status(bts.spark.OrderID order_id, bts.api.BuySell side, uint qty, double price); mbts.co2.IMDHandle get_md_handle(); } + + internal class BTSOrders + { + /// Price can be enterred in an offset from + /// Bid, Ask or LTP + public class PriceOffset + { + public enum PriceType { Bid, Ask, LastTradePrice }; + public int offset_ticks; + } + + public class QuantityThreshold + { + public enum QuantityType { Absolute, Ratio }; + public uint absolute_qty; + public double ratio; + } + + public class BTSRetryParamaters + { + /// + /// 1. Can this be fundamental data associated + /// with any order ? + /// 2. How is the parent child relation mantained + /// a. There will be multiple orders, only one + /// active though associated with the synthetic parent + /// b. After the child is accepted, TT makes the synthetic go away + /// + public uint max_number_of_retries; + public TimeSpan time_between_retries; + /// Only of these will be true + public TimeSpan offset_from_now; + public DateTime start_time; + } + + public class BTSRetryOrder + { + /// only market and limit order types are supported + } + + /// This is fundamental data associated with an order. + /// Any order can have a WithATick parameters associated + /// with it + /// There will be a BTSWithATickOrder too + public class BTSWithATickParameters + { + public QuantityThreshold threshold; + } + } } diff --git a/src/client/spark/mspark/Algo/Scratch/SingleFillHedger.cs b/src/client/spark/mspark/Algo/Scratch/SingleFillHedger.cs new file mode 100644 index 000000000..7855affd0 --- /dev/null +++ b/src/client/spark/mspark/Algo/Scratch/SingleFillHedger.cs @@ -0,0 +1,26 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.spark; + +namespace mbts.spark +{ + /// This class is reponsible for mantaining the hedge for quoting fill + internal class SingleFillHedger + { + private readonly ISingleSecurityExchangeGateway _order_gateway; + public Action on_fill = f => { }; + + public SingleFillHedger(Order hedge_order, + ContractLeg leg, + LegSpreaderParams leg_spreader_param, + mbts.co2.IMDHandle md_handle, + ISingleSecurityExchangeGateway order_gateway) + { + _order_gateway = order_gateway; + } + } +} diff --git a/src/client/spark/mspark/Algo/Scratch/SingleLegQuoter.cs b/src/client/spark/mspark/Algo/Scratch/SingleLegQuoter.cs new file mode 100644 index 000000000..388c81e56 --- /dev/null +++ b/src/client/spark/mspark/Algo/Scratch/SingleLegQuoter.cs @@ -0,0 +1,374 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.spark; + +namespace mbts.spark +{ + internal enum QuoterState + { + START = 0, + WAITING_FOR_MARKET, + WAITING_FOR_FIRST_ACK, + WORKING, + WAITING_FOR_CANCEL_ACK, + END + } + + internal enum ExternalEvents + { + /// Normal status event from the exchange + OrderStatusNormal = 0, + /// Error status event from the exchage (this could be a temporary error, however the state machine will cxl the order) + OrderStatusError, + /// When the order is completely filled (end event, should not expect anything else after that) + OrderStatusFilled, + /// When the order is cancelled (end event, should not expect anything else after that) + OrderStatusCancelled, + /// Fills reported by the exchange + OrderFills, + /// Market data update from the exchange + MDUpdate, + /// One of the other quoting legs in the spread got filled (not a hedge fill) + OtherLegQuotingFill, + /// User changes the price of the spread order + UserSpreadPriceChange, + /// User changes the quantity of the spread order + UserSpreadQuantityChange, + /// User changes the price of this leg + UserLegPriceChange, + /// User cancels this leg + UserLegCancel, + /// Either the user or the spreader cancels the order + CancelOrder + } + + internal class SingleLegQuoter + { + private readonly double _tick_size; + private readonly Order _order; + private readonly ContractLeg _leg; + private readonly bts.spark.LegSpreaderParams _leg_params; + private readonly double _leg_price_ratio, _leg_qty_ratio; + private readonly mbts.co2.IMDHandle _md_handle; + private readonly ISingleSecurityExchangeGateway _order_gateway; + private readonly IDictionary> _handler_map; + private readonly IDictionary _leg_map; + public Action on_fill = f => { }; + public Action on_send_hedge_order = o => { }; + public Action on_end = (f, b) => { }; + + /// This is the actual state + private QuoteLegPriceQuantityState _price_qty_state; + private QuoterState _state = QuoterState.START; + private TempFlatOrderState _order_state; + + public SingleLegQuoter(Order order, + ContractLeg leg, + LegSpreaderParams leg_spreader_param, + mbts.co2.IMDHandle md_handle, + ISingleSecurityExchangeGateway order_gateway) + { + mbts.Logger.assert(leg.Security.ContractSpec.LowTick == leg.Security.ContractSpec.HighTick); + _tick_size = leg.Security.ContractSpec.LowTick; + _order = order; + _leg = leg; + _leg_params = leg_spreader_param; + _leg_qty_ratio = leg.Quantity; /// TODO, can be a double + _leg_price_ratio = leg_spreader_param.PriceMultiplier; + _md_handle = md_handle; + _order_gateway = order_gateway; + _handler_map = new Dictionary>() + { + {QuoterState.WAITING_FOR_MARKET, _handle_events_in_WAITING_FOR_MARKET}, + {QuoterState.WAITING_FOR_FIRST_ACK, _handle_events_in_WAITING_FOR_FIRST_ACK}, + {QuoterState.WORKING, _handle_events_in_WORKING}, + {QuoterState.WAITING_FOR_CANCEL_ACK, _handle_events_in_WAITING_FOR_CANCEL_ACK} + }; + _leg_map = order.Security.Synthetic.Legs.ToDictionary(l => l.Security.Id, l => l); + _price_qty_state = new QuoteLegPriceQuantityState(_order.Price, Convert.ToUInt32(order.Size * _leg_qty_ratio), 0, 0, _compute_market_adjusted_price_qty); + _change_state(QuoterState.START); + } + + private uint _get_target_leg_qty() { return Convert.ToUInt32(_order.Size * _leg_qty_ratio); } + + /// Based on the desired leg qty it looks at all the other legs + /// and see how much it can get and at what price + private Tuple _compute_market_adjusted_price_qty(uint desired_leg_qty) + { + /// TODO + return null; + } + + private Order _get_new_order() + { + /// TODO + return null; + } + + private uint _get_equivelant_qty(uint other_leg_key, uint other_leg_fill_qty) + { + /// TODO + mbts.Logger.assert (_leg_map.ContainsKey (other_leg_key)); + return Convert.ToUInt32(other_leg_fill_qty * _leg_qty_ratio / _leg_map[other_leg_key].Quantity); + } + + private void _change_state(QuoterState new_state) + { + QuoterState current_state = _state; + _state = new_state; + if (new_state == QuoterState.WAITING_FOR_MARKET) + { + mbts.Logger.assert(current_state == QuoterState.START, String.Format("Only {0}->{1} possible", QuoterState.START.ToString(), new_state.ToString())); + /// TODO: sub to the market here + _handle_events_in_WAITING_FOR_MARKET(ExternalEvents.MDUpdate); + } + else if (new_state == QuoterState.WAITING_FOR_FIRST_ACK) + { + /// change to this state means send the order + mbts.Logger.assert(current_state == QuoterState.WAITING_FOR_MARKET, String.Format("Only {0}->{1} possible", QuoterState.WAITING_FOR_MARKET.ToString(), new_state.ToString())); + mbts.Logger.assert(_price_qty_state.aggregated_filled_qty == 0); + mbts.Logger.assert(_price_qty_state.out_qty == 0); + /// All changes to price (for spread, there is no active leg order till now) and qty + /// have been subsumed into the price_qty_state + /// Also anything that would have ended the order (mainly other leg fills + /// and subsequent hedges) would have been checked in waiting_for_md + _price_qty_state.out_price = _price_qty_state.computed_price; + _price_qty_state.out_qty = _price_qty_state.computed_qty; + /// This is the first and only time an order is sent from SingleLegQuoter + /// TODO send order + } + else if (new_state == QuoterState.WORKING) + { + mbts.Logger.assert(current_state == QuoterState.WAITING_FOR_FIRST_ACK, String.Format("Only {0}->{1} possible", QuoterState.WAITING_FOR_FIRST_ACK.ToString(), new_state.ToString())); + /// check for pending changes immediatly + _handle_events_in_WORKING(ExternalEvents.MDUpdate); + } + } + + #region MD/Order Callback + + private void _on_md() + { + mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.Engine, String.Format("Received MD for contract", _leg.ToString())); + _handler_map[_state](ExternalEvents.MDUpdate); + } + + private void _on_order_callback(TempFlatOrderState order_state) + { + _order_state = order_state; + ExternalEvents e = ExternalEvents.OrderStatusNormal; + if (order_state.current_state == TempFlatOrderState.State.Cancelled) + e = ExternalEvents.OrderStatusCancelled; + else if (order_state.current_state == TempFlatOrderState.State.Filled) + e = ExternalEvents.OrderStatusFilled; + /// So if an order is still Open but somehow there was an error (caused + /// by one of the last actions maybe), it is converted into an error state + /// for the order + else + { + if (order_state.last_error_state == TempFlatOrderState.ErrorState.Something) + e = ExternalEvents.OrderStatusError; + } + _handler_map[_state](e); + } + + private void _on_fill(double price, BuySell side, uint qty) + { + _price_qty_state.update_fills(qty); + _handler_map[_state](ExternalEvents.OrderFills); + } + + #endregion + + private void _handle_events_in_WAITING_FOR_MARKET(ExternalEvents e) + { + if (e == ExternalEvents.OrderStatusNormal || e == ExternalEvents.OrderStatusError || e == ExternalEvents.OrderStatusFilled || + e == ExternalEvents.OrderStatusCancelled || e == ExternalEvents.OrderFills) + { + mbts.Logger.assert(false, "Order should have already reached terminal state, in this state"); + } + else if (e == ExternalEvents.UserLegPriceChange || e == ExternalEvents.UserLegCancel) + { + mbts.Logger.assert (false, "No active working order for this leg"); + } + else if (e == ExternalEvents.MDUpdate) + { + _price_qty_state.update_md(); + if (_price_qty_state.computed_qty > 0) + _change_state(QuoterState.WAITING_FOR_FIRST_ACK); + else + { + if (_price_qty_state.aggegated_hedged_qty >= _price_qty_state.target_leg_qty) + { + /// Other fills could keep coming , reducing this leg's quoting qty. + /// If the other sides have been fully filled, this means this side + /// will be all hedges, and no need to quote + _change_state(QuoterState.END); + } + } + } + else if (e == ExternalEvents.OtherLegQuotingFill) + { + /// Since this will result in a reduced quoting + /// quantity, the above can apply + _handle_events_in_WAITING_FOR_MARKET(ExternalEvents.MDUpdate); + } + else if (e == ExternalEvents.UserSpreadPriceChange) + { + _handle_events_in_WAITING_FOR_MARKET(ExternalEvents.MDUpdate); + } + else if (e == ExternalEvents.UserSpreadQuantityChange) + { + /// if the quantity is reduced, then the md might be + /// sufficient which can make this state-machine change states + _handle_events_in_WAITING_FOR_MARKET(ExternalEvents.MDUpdate); + } + else if (e == ExternalEvents.CancelOrder) + { + _change_state(QuoterState.END); + } + } + + private void _handle_events_in_WAITING_FOR_FIRST_ACK(ExternalEvents e) + { + if (e == ExternalEvents.OrderStatusNormal) + { + _change_state(QuoterState.WORKING); + } + else if (e == ExternalEvents.OrderStatusError || e == ExternalEvents.CancelOrder || e == ExternalEvents.UserLegCancel) + { + _change_state(QuoterState.WAITING_FOR_CANCEL_ACK); + } + else if (e == ExternalEvents.OrderStatusFilled || e == ExternalEvents.OrderStatusCancelled) + { + _change_state(QuoterState.END); + } + } + + private void _handle_events_in_WAITING_FOR_CANCEL_ACK(ExternalEvents e) + { + if (e == ExternalEvents.OrderStatusCancelled || e == ExternalEvents.OrderStatusFilled) + { + _change_state(QuoterState.END); + } + } + + private void _handle_events_in_WORKING(ExternalEvents e) + { + if (e == ExternalEvents.OrderStatusNormal) + { + } + else if (e == ExternalEvents.OrderStatusError) + { + _change_state(QuoterState.WAITING_FOR_CANCEL_ACK); + } + else if (e == ExternalEvents.OrderStatusFilled) + { + _change_state(QuoterState.END); + } + else if (e == ExternalEvents.OrderStatusCancelled) + { + _change_state(QuoterState.END); + } + else if (e == ExternalEvents.OrderFills) + { + _handle_events_in_WORKING(ExternalEvents.MDUpdate); + } + else if (e == ExternalEvents.MDUpdate) + { + _price_qty_state.update_md(); + if (_price_qty_state.computed_qty == 0) + { + _change_state(QuoterState.WAITING_FOR_CANCEL_ACK); + } + else + { + if (_price_qty_state.out_qty != _price_qty_state.computed_qty) + { + _price_qty_state.out_price = _price_qty_state.computed_price; + /// TODO : modify order + } + else + { + if (_price_qty_state.computed_price != _price_qty_state.out_price) + { + /// TODO: check slop and modify order + } + } + } + } + else if (e == ExternalEvents.OtherLegQuotingFill) + { + /// Since this shoots off a hedge, the + _handle_events_in_WORKING(ExternalEvents.MDUpdate); + } + else if (e == ExternalEvents.UserSpreadPriceChange) + { + _handle_events_in_WORKING(ExternalEvents.MDUpdate); + } + else if (e == ExternalEvents.UserSpreadQuantityChange) + { + _handle_events_in_WORKING(ExternalEvents.MDUpdate); + } + else if (e == ExternalEvents.UserLegPriceChange) + { + _handle_events_in_WORKING(ExternalEvents.MDUpdate); + } + else if (e == ExternalEvents.UserLegCancel) + { + _change_state(QuoterState.WAITING_FOR_CANCEL_ACK); + } + else if (e == ExternalEvents.CancelOrder) + { + _change_state(QuoterState.WAITING_FOR_CANCEL_ACK); + } + } + + #region External Calls + + public void set_other_leg_fill(uint sec_key, bts.api.BuySell side, uint fill_qty) + { + /// reduce the leg qty and send out a hedge request + uint equivelant_qty = _get_equivelant_qty(sec_key, fill_qty); + _price_qty_state.update_hedges(equivelant_qty); + _handler_map[_state](ExternalEvents.OtherLegQuotingFill); + } + + public void change_main_order_price(double new_price) + { + _order.Price = new_price; + _price_qty_state.update_target_spread_price(new_price); + _handler_map[_state](ExternalEvents.UserSpreadPriceChange); + } + + /// This is a user changing the qty of the order + public void change_main_order_qty(uint new_qty) + { + _order.Size = new_qty; + _price_qty_state.update_target_leg_qty(_get_target_leg_qty()); + _handler_map[_state](ExternalEvents.UserSpreadQuantityChange); + } + + public void cancel_order() + { + _handler_map[_state](ExternalEvents.CancelOrder); + } + + public void change_leg_price(double new_price) + { + _price_qty_state.update_target_leg_price(new_price); + _handler_map[_state](ExternalEvents.UserLegPriceChange); + } + + public void cancel_leg_order() + { + _handler_map[_state](ExternalEvents.UserLegCancel); + } + + #endregion + } +} diff --git a/src/client/spark/mspark/Algo/Scratch/SpreaderScratchPad.cs b/src/client/spark/mspark/Algo/Scratch/SpreaderScratchPad.cs new file mode 100644 index 000000000..de096a949 --- /dev/null +++ b/src/client/spark/mspark/Algo/Scratch/SpreaderScratchPad.cs @@ -0,0 +1,96 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using bts.api; +using bts.spark; + +namespace mbts.spark +{ + public class TempFlatOrderState + { + public enum ErrorState + { + None = 0, + Something + } + + public enum State + { + Open, + Cancelled, + Filled + } + + public readonly string id; + public readonly double price; + public readonly uint qty; + public readonly uint filled; + public ErrorState last_error_state; + public State current_state; + } + + public class Spreader + { + private readonly IDictionary _quoter_map = new Dictionary(); + private readonly List _hedgers = new List(); + private readonly IDictionary _fill_map = new Dictionary(); + + public Spreader(Order synthetic_spread_order) + { + ExecutionStrategy exec_strategy = synthetic_spread_order.ExecutionStrategy; + foreach (ContractLeg l in synthetic_spread_order.Security.Synthetic.Legs) + { + var leg_spreader_params = exec_strategy.LegParamsMap[l.Security.Id]; + SingleLegQuoter quoter = new SingleLegQuoter(synthetic_spread_order, l, leg_spreader_params, null, null); + _quoter_map[l] = quoter; + quoter.on_fill += f => _on_quote_fill (l, f); + quoter.on_send_hedge_order += o => _on_send_hedge_order(l, o); + } + } + + private void _on_quote_fill(ContractLeg leg, Fill fill) + { + _update_fill(leg, fill); + /// tell all the quoters about this fill) + foreach (SingleLegQuoter q in _quoter_map.Values) + q.set_other_leg_fill(leg.Security.Id, fill.Side, fill.Size); + } + + private void _on_send_hedge_order(ContractLeg leg, Order hedge_order) + { + SingleFillHedger hedger = new SingleFillHedger(hedge_order, leg, null, null, null); + _hedgers.Add(hedger); + } + + private void _on_hedge_fill(ContractLeg leg, Fill fill) + { + _update_fill(leg, fill); + } + + private void _update_fill(ContractLeg leg, Fill fill) + { + if (!_fill_map.ContainsKey(leg)) + _fill_map.Add(leg, 0); + _fill_map[leg] = _fill_map[leg] + fill.Size; + } + + #region User Action + /// Changes qty of the spreader order + public void change_qty(uint new_qty) + { + } + + /// Changes price of the spreader order + public void change_price(double new_price) + { + } + + /// Changes price of one leg + public void change_leg_price(Security security, double new_leg_price) + { + } + #endregion + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Controls/PriceEntryControl.xaml b/src/client/spark/mspark/Controls/PriceEntryControl.xaml deleted file mode 100644 index a4562cdc4..000000000 --- a/src/client/spark/mspark/Controls/PriceEntryControl.xaml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - diff --git a/src/client/spark/mspark/Controls/PriceEntryControl.xaml.cs b/src/client/spark/mspark/Controls/PriceEntryControl.xaml.cs deleted file mode 100644 index f4485445d..000000000 --- a/src/client/spark/mspark/Controls/PriceEntryControl.xaml.cs +++ /dev/null @@ -1,73 +0,0 @@ -using bts.api; -using mbts.spark; -using mbts.ui.spark.converters; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Input; - -namespace mbts.ui.spark -{ - /// - /// Interaction logic for PriceEntryControl.xaml - /// - internal class PriceEntryControl : Control - { - static PriceEntryControl() { - DefaultStyleKeyProperty.OverrideMetadata(typeof(PriceEntryControl), new FrameworkPropertyMetadata(typeof(PriceEntryControl))); - } - - #region Value - public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(PriceEntryControl), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); - public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); } - #endregion - - #region TickUp - private static readonly DependencyPropertyKey TickUpCommandPropertyKey = DependencyProperty.RegisterReadOnly("TickUpCommand", typeof(ICommand), typeof(PriceEntryControl), new PropertyMetadata(null)); - public static readonly DependencyProperty TickUpCommandProperty = TickUpCommandPropertyKey.DependencyProperty; - public ICommand TickUpCommand { get => GetValue(TickUpCommandProperty) as ICommand; private set => SetValue(TickUpCommandPropertyKey, value); } - #endregion - - #region TickDown - private static readonly DependencyPropertyKey TickDownCommandPropertyKey = DependencyProperty.RegisterReadOnly("TickDownCommand", typeof(ICommand), typeof(PriceEntryControl), new PropertyMetadata(null)); - public static readonly DependencyProperty TickDownCommandProperty = TickDownCommandPropertyKey.DependencyProperty; - 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(ContractSpecification), typeof(PriceEntryControl), new PropertyMetadata(TickUtils.DefaultSpec, OnContractSpecChanged)); - private static void OnContractSpecChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((PriceEntryControl)d)._update_text_binding(); } - public ContractSpecification ContractSpec { get => GetValue(ContractSpecProperty) as ContractSpecification; set => SetValue(ContractSpecProperty, value); } - #endregion - - public PriceEntryControl() { - TickUpCommand = new DelegateCommand(_tick_up); - TickDownCommand = new DelegateCommand(_tick_down); - } - - private TextBox _text; - - private void _tick_up() { SetCurrentValue(ValueProperty, ContractSpec.tickup(Value)); } - private void _tick_down() { SetCurrentValue(ValueProperty, ContractSpec.tickdown(Value)); } - - private void _update_text_binding() { - if (_text != null) { - var spec = ContractSpec; - if (spec != null) { - var be = _text.GetBindingExpression(TextBox.TextProperty); - if (be != null) { - var converter = be.ParentBinding.Converter as TickDisplayTwoWayConverter; - if (converter != null) { - converter.ContractSpec = spec; - be.UpdateTarget(); - } - } - } - } - } - - public override void OnApplyTemplate() { - _text = GetTemplateChild("_text") as TextBox; - _update_text_binding(); - } - } -} diff --git a/src/client/spark/mspark/Core/OrderUtils.cs b/src/client/spark/mspark/Core/OrderUtils.cs index 1c061d861..b9ccbb82e 100644 --- a/src/client/spark/mspark/Core/OrderUtils.cs +++ b/src/client/spark/mspark/Core/OrderUtils.cs @@ -1,13 +1,12 @@ using bts.api; using bts.spark; using Google.Protobuf; -using Google.Protobuf.Reflection; using mbts.utils; using System; using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Text.RegularExpressions; +using static mbts.ui.utilities.DisplayNameHelper; namespace mbts.spark { public static class OrderUtils { @@ -16,24 +15,12 @@ namespace mbts.spark { return camel_to_title_case(order.Descriptor.Name); } - // Adds spaces to CamelCase => "Camel Case" - public static string camel_to_title_case(string name) { - StringBuilder sb = new StringBuilder(); - foreach (var ch in name) { - if (sb.Length == 0) { sb.Append(Char.ToUpper(ch)); } - else { - if (Char.IsUpper(ch)) { - sb.Append(" "); - } - sb.Append(ch); - } - } - return sb.ToString(); + public static string algo_display_name(Order.AlgoOrderTypeOneofCase algo) { + return algo_display_name(algo.ToString()); } - - public static string algo_display_name(Order.AlgoOrderTypeOneofCase algo) { - return camel_to_title_case(algo.ToString()).Replace(" Order", ""); + public static string algo_display_name(string algo_name) { + return camel_to_title_case(Regex.Replace(algo_name, "Order", string.Empty, RegexOptions.IgnoreCase)); } public static long filled(OrderBookEntry order) { @@ -54,6 +41,7 @@ namespace mbts.spark { case Order.AlgoOrderTypeOneofCase.StopLimitOrder: return order.StopLimitOrder; case Order.AlgoOrderTypeOneofCase.IcebergOrder: return order.IcebergOrder; case Order.AlgoOrderTypeOneofCase.CrossingHedgeOrder: return order.CrossingHedgeOrder; + case Order.AlgoOrderTypeOneofCase.SimpleHedgeOrder: return order.SimpleHedgeOrder; case Order.AlgoOrderTypeOneofCase.CustomOrder: return order.CustomOrder; default: throw new MissingFieldException($"No field for: {order.AlgoOrderTypeCase}"); @@ -71,10 +59,6 @@ namespace mbts.spark { } - public static IEnumerable get_active_orders_for_security(this IOrderBook book, uint security) { - return book.get_all_orders_for_security(security).Where(order => is_active(order.OrderStatus)).ToList(); - } - public static string order_summary(OrderBookEntry order) { return $"{camel_to_title_case(order.order().AlgoOrderTypeCase.ToString())}: {order.order().Side} {order.order().Size} at {order.order().Price}"; } diff --git a/src/client/spark/mspark/Core/SparkBusData.cs b/src/client/spark/mspark/Core/SparkBusData.cs index a00d21b61..fcfb650c6 100644 --- a/src/client/spark/mspark/Core/SparkBusData.cs +++ b/src/client/spark/mspark/Core/SparkBusData.cs @@ -5,7 +5,7 @@ using bts.api; namespace mbts.spark { - static class SparkBusData + internal static class SparkBusData { public class BusMessageWrapper { @@ -50,19 +50,27 @@ namespace mbts.spark } public class ShowAuditLogsMessage { } public class ShowFillsMessage { } - public class ShowLadderMessage : BusMessageWrapper> { - public ShowLadderMessage(SecurityMD smd) : this(new[] { smd }) { } - public ShowLadderMessage(IReadOnlyCollection smd) : base(smd) { } + public class ShowLadderMessage : BusMessageWrapper> { + public ShowLadderMessage(Security security) : this(new[] { security }) { } + public ShowLadderMessage(IReadOnlyCollection security) : base(security) { } + } + public class ShowLinkedLadderMessage : BusMessageWrapper> { + public ShowLinkedLadderMessage(IObservable security_md) : base(security_md) { } } public class ShowMarketViewMessage : BusMessageWrapper> { public ShowMarketViewMessage(IReadOnlyCollection securities) : base(securities) { } } public class ShowOrderBookMessage { } - public class ShowOrderModifyMessage : BusMessageWrapper { - public ShowOrderModifyMessage(Order order) : base(order) { } + public class ShowOrderModifyMessage : BusMessageWrapper> { + public ShowOrderModifyMessage(Order order) : base(new[] { order }) { } + public ShowOrderModifyMessage(IReadOnlyCollection orders) : base(orders) { } } - public class ShowOrderTicketMessage : BusMessageWrapper { - public ShowOrderTicketMessage(Order order) : base(order) { } + public class ShowOrderTicketMessage : BusMessageWrapper> { + public ShowOrderTicketMessage(Order order) : base(new[] { order }) { } + public ShowOrderTicketMessage(IReadOnlyCollection orders) : base(orders) { } + } + public class ShowLinkedOrderTicketMessage : BusMessageWrapper> { + public ShowLinkedOrderTicketMessage(IObservable order) : base(order) { } } public class ShowPositionsMessage { } public class ShowSpreadMatrixMessage : BusMessageWrapper> { diff --git a/src/client/spark/mspark/Ladder/LadderGridHost.cs b/src/client/spark/mspark/Ladder/LadderGridHost.cs index 8568b857f..1fb613ca0 100644 --- a/src/client/spark/mspark/Ladder/LadderGridHost.cs +++ b/src/client/spark/mspark/Ladder/LadderGridHost.cs @@ -1,14 +1,14 @@ -using mbts.ui.controls; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Media; -using mbts.ui; -using System.Windows.Markup; +using mbts.ui.controls; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Media; +using mbts.ui; +using System.Windows.Markup; using mbts.co2; using bts.api; using System.Windows.Input; @@ -16,45 +16,47 @@ using System.Windows.Media.Animation; using System.Collections.ObjectModel; using System.Collections.Specialized; -namespace mbts.spark { - class LadderGridHost : Control { - const int _rowcount = 1001; - - LadderSettings _settings; - LadderVM _vm; - ContractSpecification _spec; - - VisualHost _visualHost = new VisualHost() {}; - LadderOrdersHost _ordershost; - ScrollViewer _scrollViewer; - ulong _prices_updated; - NativePriceSize[] _bids, _asks; - bool _price_dirty = false; - double[] _price_list = null; - double _last_mid; - NativePriceSize _last_trade; - DrawingVisual _bidvis = new DrawingVisual(), - _askvis = new DrawingVisual(), - _pricevis = new DrawingVisual(), - _lastvis = new DrawingVisual(), - _midvis = new DrawingVisual(), - _gridvis = new DrawingVisual(); - - public LadderGridHost() { - _ordershost = new LadderOrdersHost(this) { HorizontalAlignment = HorizontalAlignment.Left }; - var scrollViewerFactory = new FrameworkElementFactory(typeof(ScrollViewer)); - scrollViewerFactory.SetValue(FocusableProperty, false); - Template = new ControlTemplate() { - VisualTree = scrollViewerFactory - }; - Loaded += (_, __) => scroll_to_center(); - RecenterCommand = new DelegateCommand(o => scroll_to_center()); - } - - public event Action click; - - public Security security => _vm.security; - +namespace mbts.spark { + class LadderGridHost : Control { + const int _rowcount = 1001; + + IDisposable _settings_sub, _tick_sub; + LadderSettings _settings; + LadderVM _vm; + ContractSpecification _spec; + + VisualHost _visualHost = new VisualHost() {}; + LadderOrdersHost _ordershost; + ScrollViewer _scrollViewer; + ulong _prices_updated; + NativePriceSize[] _bids, _asks; + bool _price_dirty = false; + double[] _price_list = null; + double _last_mid; + NativePriceSize _last_trade; + DrawingVisual _bidvis = new DrawingVisual(), + _askvis = new DrawingVisual(), + _pricevis = new DrawingVisual(), + _lastvis = new DrawingVisual(), + _midvis = new DrawingVisual(), + _gridvis = new DrawingVisual(); + + public LadderGridHost() { + _ordershost = new LadderOrdersHost(this) { HorizontalAlignment = HorizontalAlignment.Left }; + var scrollViewerFactory = new FrameworkElementFactory(typeof(ScrollViewer)); + scrollViewerFactory.SetValue(FocusableProperty, false); + Template = new ControlTemplate() { + VisualTree = scrollViewerFactory + }; + Loaded += (_, __) => scroll_to_center(); + RecenterCommand = new DelegateCommand(o => scroll_to_center()); + DataContextChanged += (s, e) => _connect_vm(); + } + + public event Action click; + + public Security security => _vm.security; + public ICommand RecenterCommand { get; } public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } @@ -96,22 +98,30 @@ namespace mbts.spark { } } base.OnMouseDown(e); - } - - public override void OnApplyTemplate() { - base.OnApplyTemplate(); - _scrollViewer = this.descendants_of_type().First(); - // _visualHost draws grid lines on top of _ordershost + } + + public override void OnApplyTemplate() { + base.OnApplyTemplate(); + _scrollViewer = this.descendants_of_type().First(); + // _visualHost draws grid lines on top of _ordershost var grid = new Grid() { Children = { _ordershost, _visualHost, } }; - _scrollViewer.Content = grid; - _vm = DataContext as LadderVM; - _spec = _vm.security.ContractSpec; - if (_vm != null) { - _vm.on_tick += tick; - _vm.settings.Subscribe(settings_updated); - } - } - + _scrollViewer.Content = grid; + _connect_vm(); + } + + private void _connect_vm() { + Disposable.dispose(ref _settings_sub); + Disposable.dispose(ref _tick_sub); + _vm = DataContext as LadderVM; + if (_vm != null) { + _spec = _vm.security.ContractSpec; + _prices_updated = 0; + _vm.on_tick += tick; + _settings_sub = _vm.settings.Subscribe(settings_updated); + _tick_sub = Disposable.Create(() => _vm.on_tick -= tick); + } + } + IEnumerable<(LadderColumnSettings, DrawingVisual)> columns { get { if (_settings != null) { @@ -122,32 +132,32 @@ namespace mbts.spark { yield return (_settings.last_column, _lastvis); } } - } - - private void settings_updated(LadderSettings s) { - _settings = s; + } + + private void settings_updated(LadderSettings s) { + _settings = s; _visualHost.Height = _rowcount * s.row_height; - _price_dirty = _settings.price_column.show; - - // Clear and re-add the columns to the viewer to ensure offset/visibility is correct - _visualHost.Clear(); - double offset = 0.0; - - // Orders column - _ordershost.Visibility = s.orders_column.show ? Visibility.Visible : Visibility.Collapsed; + _price_dirty = _settings.price_column.show; + + // Clear and re-add the columns to the viewer to ensure offset/visibility is correct + _visualHost.Clear(); + double offset = 0.0; + + // Orders column + _ordershost.Visibility = s.orders_column.show ? Visibility.Visible : Visibility.Collapsed; if (s.orders_column.show) { _ordershost.Width = s.orders_column.width; _ordershost.VerticalAlignment = VerticalAlignment.Stretch; offset += s.orders_column.width; - } - + } + foreach ((var col, var visual) in columns) { if (col.show && visual != null) { visual.Offset = new Vector(offset, 0); offset += col.width; _visualHost.AddVisualChild(visual); } - } + } // Renders the grid lines _visualHost.AddVisualChild(_gridvis); @@ -181,8 +191,8 @@ namespace mbts.spark { } } - private void tick() { - if (_settings != null) { + private void tick() { + if (_settings != null) { if (_vm.md.get_depth(ref _prices_updated, ref _bids, ref _asks)) { var mid = TickUtils.mid_tick(_spec, _bids[0].price, _asks[0].price); if (_price_dirty) { @@ -210,9 +220,9 @@ namespace mbts.spark { } } - _price_dirty = false; - } - } + _price_dirty = false; + } + } } @@ -265,5 +275,5 @@ namespace mbts.spark { #endregion - } -} + } +} diff --git a/src/client/spark/mspark/Ladder/LadderModel.cs b/src/client/spark/mspark/Ladder/LadderModel.cs index ffc54d353..3f15afcab 100644 --- a/src/client/spark/mspark/Ladder/LadderModel.cs +++ b/src/client/spark/mspark/Ladder/LadderModel.cs @@ -39,7 +39,9 @@ namespace mbts.spark { new LimitOrder (), new StopMarketOrder (), new StopLimitOrder (), - new IcebergOrder (), + new IcebergOrder(), + new BTSStopOrder (), + new BTSIcebergOrder () }; } } diff --git a/src/client/spark/mspark/Ladder/LadderVM.cs b/src/client/spark/mspark/Ladder/LadderVM.cs index 6740e1f00..ac21179b1 100644 --- a/src/client/spark/mspark/Ladder/LadderVM.cs +++ b/src/client/spark/mspark/Ladder/LadderVM.cs @@ -236,7 +236,6 @@ namespace mbts.spark { } protected override void Dispose(bool disposing) { - base.Dispose(disposing); _timer.Stop(); } } diff --git a/src/client/spark/mspark/Ladder/LadderView.xaml.cs b/src/client/spark/mspark/Ladder/LadderView.xaml.cs index 3deed83df..cdd513977 100644 --- a/src/client/spark/mspark/Ladder/LadderView.xaml.cs +++ b/src/client/spark/mspark/Ladder/LadderView.xaml.cs @@ -15,15 +15,8 @@ using System.Windows.Shapes; namespace mbts.spark { public partial class LadderView : UserControl { - readonly LadderVM _vm; - internal LadderView(LadderVM vm) { + internal LadderView() { InitializeComponent(); - DataContext = _vm = vm; - //KeyDown += key_down; } - - //private void key_down(object sender, KeyEventArgs e) { - // _vm.key_pressed(e); - //} } } diff --git a/src/client/spark/mspark/Ladder/OrderTypeVM.cs b/src/client/spark/mspark/Ladder/OrderTypeVM.cs index 8ea3414bc..c016cbf59 100644 --- a/src/client/spark/mspark/Ladder/OrderTypeVM.cs +++ b/src/client/spark/mspark/Ladder/OrderTypeVM.cs @@ -24,7 +24,7 @@ namespace mbts.spark { _order_template = order_template; _meta = meta; - name = OrderUtils.camel_to_title_case(order.Descriptor.Name); + name = OrderUtils.algo_display_name(order.Descriptor.Name); type_name = order.Descriptor.Name; _accessor = Order.Descriptor.Oneofs .First(ood => ood.Name == "algo_order_type") @@ -62,6 +62,8 @@ namespace mbts.spark { } } + public bool is_bts_type => name.Contains("BTS"); + public bool key_match(KeyEventArgs key) { return key.Key == (Key.A + name[0] - 'A'); } diff --git a/src/client/spark/mspark/MarketView/MarketViewModel.cs b/src/client/spark/mspark/MarketView/MarketViewModel.cs index 74e421930..6930d7a20 100644 --- a/src/client/spark/mspark/MarketView/MarketViewModel.cs +++ b/src/client/spark/mspark/MarketView/MarketViewModel.cs @@ -8,19 +8,15 @@ using System.Reactive.Linq; using System.Reactive.Subjects; using static mbts.spark.SparkBusData; using static mbts.spark.SparkTags; -using static mbts.spark.utilities.UserConfigurationHelper; +using MDMap = System.Collections.Generic.Dictionary; using SecurityKey = System.UInt32; namespace mbts.spark { - internal class MarketViewModel : IDisposable + internal class MarketViewModel : IDisposable { public MarketViewModel(IBus bus) { _bus = bus; - _subs.Add(_bus.subscribe>(SecuritiesTag).ObserveOnDispatcher().Subscribe(m => { - _data = m; - _fire(); - })); _subs.Add(_bus.subscribe(PositionsTag).Subscribe(m => { foreach (var kv in m.data) _positions_demuxer.push_data(kv.Key, kv.Value); })); @@ -29,33 +25,24 @@ namespace mbts.spark private readonly IBus _bus; private readonly OrdersModel _orders_model; - private readonly Subject> _rows_subject = new Subject>(); + private readonly Subject> _securities_subject = new Subject>(); private readonly ObservableDemuxer _positions_demuxer = new ObservableDemuxer(k => 0); private IList _subs = new List(); - private HashSet _active_securities = new HashSet(); private IDictionary _data = new Dictionary(); - private void _fire() { _rows_subject.OnNext(_data.Where(kv => _active_securities.Contains(kv.Key)).Select(kv => kv.Value)); } - - public IObservable> rows => _rows_subject.AsObservable(); + public IObservable> rows => _bus.subscribe(SecuritiesTag).StartWith(new MDMap()).CombineLatest(_securities_subject, (md, secs) => md.Intersect(secs, kv => kv.Key).Select(kv => kv.Value)); public IReadOnlyCollection all_securities => _data.Values.Select(s => s.security).ToList(); public OrdersModel orders_model => _orders_model; - public IObservable security_position(SecurityKey key) { return _positions_demuxer.subscribe(key); } - public void show_ladder(Security security) { if (_data.TryGetValue(security.Id, out SecurityMD smd)) _bus.post(ShowLadderTag, new ShowLadderMessage(smd)); } + public IObservable security_position(SecurityKey key) { return _positions_demuxer.subscribe(key).DistinctUntilChanged(); } + public void show_ladder(Security security) { _bus.post(ShowLadderTag, new ShowLadderMessage(security)); } public void show_order_modify(Order order) { _bus.post(ShowOrderModifyTag, new ShowOrderModifyMessage(order)); } - public void show_order_ticket(Security sec, BuySell side, double price, uint size = 1) { - _bus.post(ShowOrderTicketTag, new ShowOrderTicketMessage(new Order { User = UserName, Security = sec, Side = side, Price = price, Size = size, LimitOrder = new LimitOrder() })); - } - public void set_securities(IEnumerable securities) { - _active_securities = new HashSet(securities.Select(s => s.Id)); - _fire(); - } + public void show_order_ticket(Order order) { _bus.post(ShowOrderTicketTag, new ShowOrderTicketMessage(order)); } + public void set_securities(IEnumerable securities) { _securities_subject.OnNext(new HashSet(securities.Select(s => s.Id))); } public void Dispose() { Disposable.dispose(_subs); - _rows_subject.Dispose(); + _securities_subject.Dispose(); _positions_demuxer.Dispose(); } } - } \ No newline at end of file diff --git a/src/client/spark/mspark/MarketView/MarketViewRow.cs b/src/client/spark/mspark/MarketView/MarketViewRow.cs new file mode 100644 index 000000000..8deb07d3b --- /dev/null +++ b/src/client/spark/mspark/MarketView/MarketViewRow.cs @@ -0,0 +1,113 @@ +using bts.api; +using bts.spark; +using mbts.collections; +using mbts.spark.utilities; +using mbts.ui; +using mbts.ui.controls; +using mbts.ui.shell; +using mbts.ui.spark; +using mbts.ui.utility; +using mbts.utils; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Collections.Specialized; +using System.Linq; +using System.Reactive.Linq; +using System.Windows.Input; +using static mbts.ui.spark.MarketViewView; + +namespace mbts.spark +{ + internal partial class MarketViewVM + { + public class Row : GridRowViewModelBase + { + public Row(MarketViewVM owner, MarketViewModel model, SecurityMD smd, IObservable position) { + _owner = owner; + _model = model; + security = AddCell(Columns.Security, smd.security); + this.position = AddCell(Columns.Position, position, 0); + var md_pump = new SecurityMDPump(smd.md); + bid_price = AddCell(Columns.Bid, md_pump.bid_price, double.NaN); + bid_size = AddCell(Columns.BidSize, md_pump.bid_size, (ushort)0); + ask_price = AddCell(Columns.Ask, md_pump.ask_price, double.NaN); + ask_size = AddCell(Columns.AskSize, md_pump.ask_size, (ushort)0); + last_price = AddCell(Columns.Last, md_pump.last_price, double.NaN); + last_size = AddCell(Columns.LastSize, md_pump.last_size, (ushort)0); + settlement = AddCell(Columns.Settlement, md_pump.settlement_price, double.NaN); + volume = AddCell(Columns.Volume, md_pump.volume, (ulong)0); + // + _working_orders = new ObservableFilterCollection(_orders, o => o.is_active()); + _working_bids = new ObservableFilterCollection(_working_orders, o => o.order().Side == BuySell.Buy); + _working_asks = new ObservableFilterCollection(_working_orders, o => o.order().Side == BuySell.Sell); + _working_bids_sorted = new ObservableSortedCollection(_working_bids, CompareUtils.NullCheckComparer((x, y) => y.order().Price.CompareTo(x.order().Price))); + _working_asks_sorted = new ObservableSortedCollection(_working_asks, CompareUtils.NullCheckComparer((x, y) => x.order().Price.CompareTo(y.order().Price))); + _inside_bids = new ObservableFilterCollection(_working_bids_sorted, o => o.order().Price >= bid_price.output); + _inside_asks = new ObservableFilterCollection(_working_asks_sorted, o => o.order().Price <= ask_price.output); + var day_change_src = md_pump.settlement_price.CombineLatest(md_pump.last_price, (s, l) => l - s); + var working_best_bid_src = _working_bids_sorted.Observe().Select(_ => _working_bids_sorted.Count == 0 ? double.NaN : _working_bids_sorted.First().order().Price).DistinctUntilChanged(); + var working_best_ask_src = _working_asks_sorted.Observe().Select(_ => _working_asks_sorted.Count == 0 ? double.NaN : _working_asks_sorted.First().order().Price).DistinctUntilChanged(); + var working_bids_volume_src = _working_bids.Observe().Select(_ => _working_bids.Aggregate(0u, (v, o) => v + o.order().Size - o.Fills.Aggregate(0u, (fv, f) => fv + f.Size))).DistinctUntilChanged(); + var working_asks_volume_src = _working_asks.Observe().Select(_ => _working_asks.Aggregate(0u, (v, o) => v + o.order().Size - o.Fills.Aggregate(0u, (fv, f) => fv + f.Size))).DistinctUntilChanged(); + // + day_change = AddCell(Columns.DayChange, day_change_src, double.NaN); + session_low = AddCell(Columns.SessionLow, md_pump.session_low, double.NaN); + session_high = AddCell(Columns.SessionHigh, md_pump.session_high, double.NaN); + working_bids_text = AddCell(Columns.WorkingBids, working_bids_volume_src.CombineLatest(working_best_bid_src, (size, price) => size == 0u ? string.Empty : "{0} @ {1}".fmt(smd.security.ContractSpec.format(price), size)), string.Empty); + working_asks_text = AddCell(Columns.WorkingAsks, working_asks_volume_src.CombineLatest(working_best_ask_src, (size, price) => size == 0u ? string.Empty : "{0} @ {1}".fmt(smd.security.ContractSpec.format(price), size)), string.Empty); + _working_best_bid = backing(nameof(working_best_bid), working_best_bid_src); + _working_best_ask = backing(nameof(working_best_ask), working_best_ask_src); + _animation.AnimationsChanged += _animation_AnimationsChanged; + _dispose = Disposable.Create(md_pump, + position.PairWithPrevious().Select(vals => vals.curr > vals.prev).ObserveOnDispatcher().Subscribe(_animation.animate_position), + _working_bids.Observe().Select(_ => _working_bids.Count > 0).DistinctUntilChanged().ObserveOnDispatcher().Subscribe(_animation.animate_working_bids_active), + _working_asks.Observe().Select(_ => _working_asks.Count > 0).DistinctUntilChanged().ObserveOnDispatcher().Subscribe(_animation.animate_working_asks_active), + _inside_bids.Observe().Select(_ => _inside_bids.Count > 0).DistinctUntilChanged().ObserveOnDispatcher().Subscribe(_animation.animate_working_bids_inside), + _inside_asks.Observe().Select(_ => _inside_asks.Count > 0).DistinctUntilChanged().ObserveOnDispatcher().Subscribe(_animation.animate_working_asks_inside), + day_change_src.PairWithPrevious().Select(vals => vals.curr > vals.prev).ObserveOnDispatcher().Subscribe(_animation.animate_day_change), + Disposable.Create(() => _animation.AnimationsChanged -= _animation_AnimationsChanged) + ); + } + private readonly MarketViewVM _owner; + private readonly MarketViewModel _model; + private readonly AnimationManager _animation = new AnimationManager(); + private readonly ObservableSortedCollection _working_bids_sorted, _working_asks_sorted; + private readonly ObservableCollection _orders = new ObservableCollection(); + private readonly ObservableFilterCollection _working_orders, _working_bids, _working_asks, _inside_bids, _inside_asks; + private readonly Property _working_best_bid, _working_best_ask; + + private void _animation_AnimationsChanged() { RaisePropertyChanged(nameof(animations)); } + + #region Bound Properties + public SelectableViewModelBase security { get; } + public RXReadOnlyDataGridCell position { get; } + public RXReadOnlyDataGridCell last_price { get; } + public RXReadOnlyDataGridCell last_size { get; } + public RXReadOnlyDataGridCell bid_price { get; } + public RXReadOnlyDataGridCell bid_size { get; } + public RXReadOnlyDataGridCell ask_price { get; } + public RXReadOnlyDataGridCell ask_size { get; } + public RXReadOnlyDataGridCell volume { get; } + public RXReadOnlyDataGridCell settlement { get; } + public RXReadOnlyDataGridCell day_change { get; } + public RXReadOnlyDataGridCell session_low { get; } + public RXReadOnlyDataGridCell session_high { get; } + public RXReadOnlyDataGridCell working_bid_volume { get; } + public RXReadOnlyDataGridCell working_ask_volume { get; } + public RXReadOnlyDataGridCell working_bids_text { get; } + public RXReadOnlyDataGridCell working_asks_text { get; } + public double working_best_bid => _working_best_ask.Value; + public double working_best_ask => _working_best_ask.Value; + public IEnumerable animations => _animation.get_animations(); + public ICommand show_ladder => new DelegateCommand(() => _model.show_ladder(security.value)); + public ICommand show_order_ticket => new DelegateCommand(col => _model.show_order_ticket(_create_order(this, col))); + #endregion + + public void refresh(IEnumerable orders) { + _orders.sync_with(orders); + _working_orders.trigger_filter(); + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/MarketView/MarketViewVM.cs b/src/client/spark/mspark/MarketView/MarketViewVM.cs index ddbf4b6c0..7931a641b 100644 --- a/src/client/spark/mspark/MarketView/MarketViewVM.cs +++ b/src/client/spark/mspark/MarketView/MarketViewVM.cs @@ -1,232 +1,113 @@ using bts.api; using bts.spark; using Google.Protobuf; -using mbts.co2; -using mbts.collections; using mbts.spark.menu_items; +using mbts.spark.utilities; using mbts.ui; +using mbts.ui.controls; using mbts.ui.shell; using mbts.ui.spark; +using mbts.ui.utilities; using mbts.ui.utility; -using mbts.utils; using ProtoBuf; using System; using System.Collections.Generic; -using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; using System.Reactive.Linq; +using System.Windows.Controls; using System.Windows.Data; -using System.Windows.Input; using static mbts.ui.spark.MarketViewView; namespace mbts.spark { - internal partial class MarketViewVM : ViewModelBase, IDisposable + internal partial class MarketViewVM : DisposableViewModelBase, IDisposable { public const int VERSION = 1; public const string SAVE_NAME = "MarketView"; public MarketViewVM(IBus bus, IReadOnlyCollection securities, IReadOnlyCollection sorting_criteria) { _bus = bus; - _model = new MarketViewModel(bus); - _rows = new RXObservableCollection(_model.rows); - _row_vms = new ObservableAutoWrapper(_rows, r => new RowVM(this, _model, ref r, _model.security_position(r.security.Id))); - _row_vms.ViewDestroyed += r => r.Dispose(); - row_views = CollectionViewSource.GetDefaultView(_row_vms); - if (sorting_criteria == null || sorting_criteria.Count == 0) row_views.SortDescriptions.Add(new SortDescription(nameof(RowVM.security), ListSortDirection.Ascending)); - else row_views.SortDescriptions.AddRange(sorting_criteria.Select(sc => new SortDescription(sc.col_name, sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending))); - _model.set_securities(securities); - _model.orders_model.on_orderbook().ObserveOnDispatcher().Subscribe(ob => { + _resources.Add(_model = new MarketViewModel(bus)); + _resources.Add(_rows = new RXObservableCollection(_model.rows)); + _rows_vm = new ObservableAutoWrapper(_rows, smd => new Row(this, _model, smd, _model.security_position(smd.security.Id))); + _rows_vm.ViewDestroyed += r => r.Dispose(); + _resources.Add(Disposable.Create(() => _rows_vm.Clear())); + rows_view = CollectionViewSource.GetDefaultView(_rows_vm); + if (sorting_criteria == null || sorting_criteria.Count == 0) rows_view.SortDescriptions.Add(new SortDescription(nameof(Row.security), ListSortDirection.Ascending)); + else rows_view.SortDescriptions.AddRange(sorting_criteria.Select(sc => new SortDescription(sc.col_name, sc.is_ascending ? ListSortDirection.Ascending : ListSortDirection.Descending))); + _resources.Add(_context_menu = new ContextMenuVM(_context_menu_item_factory)); + _resources.Add(_model.orders_model.on_orderbook().ObserveOnDispatcher().Subscribe(ob => { _order_book = ob; _refresh(); - }); - context_menu = CollectionViewSource.GetDefaultView(_context_menu); - context_menu.GroupDescriptions.Add(new PropertyGroupDescription(nameof(MenuItemVM.sectional_id))); - _work_loop = WorkLoop.Start(_refresh); + })); + _model.set_securities(securities); + _resources.Add(WorkLoop.Start(_refresh)); } private readonly IBus _bus; - private readonly IDisposable _work_loop; private readonly MarketViewModel _model; - private readonly ObservableAutoWrapper _row_vms; + private readonly ContextMenuVM _context_menu; + private readonly ObservableAutoWrapper _rows_vm; private readonly RXObservableCollection _rows; + private readonly ColdObseravbleProperty _current_cell = new ColdObseravbleProperty(); + private IList _resources = new List(); private IOrderBook _order_book = new OrderBook(); - private ObservableCollection _context_menu = new ObservableCollection(); - private bool _is_context_menu_open; private void _refresh() { var orders_map = _order_book.get_order_sec_map(); - foreach(var rvm in _row_vms) rvm.refresh(orders_map.TryGetValue(rvm.security.Id, out IEnumerable orders) ? orders : Enumerable.Empty()); + foreach(var rvm in _rows_vm) rvm.refresh(orders_map.TryGetValue(rvm.security.value.Id, out IEnumerable orders) ? orders : Enumerable.Empty()); } - private void _refresh_context_menu() { - Disposable.dispose(_context_menu); - _context_menu.Clear(); - _context_menu.Add(MenuItemVM.Create("Add/Remove Securities...", "misc", Icons.Coins, new DialogCommand(() => new SecuritySelectorDialog { - DataContext = new SecuritySelectorDialogVM("Market View", _rows.Select(r => r.security).ToArray(), _model.set_securities) - }, () => true, true, -12, -30))); - var selected_securities = new ObservableCollection(_row_vms.Where(r => r.is_selected).Select(r => r.security)); - _context_menu.AddRange(new IMenuItem[] { - new LadderMenuItem(_bus), new SpreadMatrixMenuItem(_bus), new TimeAndSalesMenuItem(_bus) - }.Select(m => MenuItemVM.Create(m, selected_securities))); - const string order_actions = "order_actions"; - _context_menu.Add(MenuItemVM.Create(new OrderTicketMenuItem(_bus), selected_securities)); - var securities = _row_vms.Where(r => r.is_selected).Select(r => r.security).Ordered().ToList(); - var orders = securities.SelectMany(s => _order_book.get_active_orders_for_security(s.Id)).Select(obe => obe.order()).Ordered(OrderUtils.Compare.depth_compare).ToList(); - _context_menu.Add(MenuItemVM.Create("Modify Order", order_actions, Icons.Import, items:orders.Select(o => _create_order_item(o, _model.orders_model.get_metadata(o), () => _model.show_order_modify(o))).ToList())); - _context_menu.Add(MenuItemVM.Create("Cancel Order", order_actions, Icons.CancelOrders, items:orders.Select(o => _create_order_item(o, _model.orders_model.get_metadata(o), () => _model.orders_model.cancel_order(o.Id))).ToList())); - var sec_keys = securities.Select(s => s.Id); - _context_menu.Add(MenuItemVM.Create("Cancel Buy Orders", order_actions, Icons.CancelOrders, new DelegateCommand(() => _model.orders_model.cancel_security_orders(sec_keys, true, false)))); - _context_menu.Add(MenuItemVM.Create("Cancel Sell Orders", order_actions, Icons.CancelOrders, new DelegateCommand(() => _model.orders_model.cancel_security_orders(sec_keys, false, true)))); - _context_menu.Add(MenuItemVM.Create("Cancel All Orders", order_actions, Icons.CancelOrders, new DelegateCommand(() => _model.orders_model.cancel_security_orders(sec_keys, true, true)))); - } - - private static MenuItemVM _create_order_item(Order o, OrderMetadata omd, Action a) { return MenuItemVM.Create(_format_order(o), o.Side.ToString(), OrderIconFactory.Create(omd, o.Side), command:new DelegateCommand(a)); } - private static string _format_order(Order order) { return "{0} {1} {2} / {3}".fmt(order.Side, order.Security, order.Security.ContractSpec.format(order.Price), order.Size); } - private RowVM _get_active_row() { return selected_row ?? _row_vms.FirstOrDefault(r => r.is_selected); } - - public ICollectionView row_views { get; } - public RowVM selected_row { get; set; } - public ICollectionView context_menu { get; } - public bool is_context_menu_open { get => _is_context_menu_open; set { _is_context_menu_open = value; _refresh_context_menu(); } } - - public StartupData get_startup_data() { return new StartupData(_rows.Select(r => r.security).ToArray(), row_views.SortDescriptions.Select(sd => new SortingCriteria { col_name = sd.PropertyName, is_ascending = sd.Direction == ListSortDirection.Ascending }).ToArray()); } - - public void Dispose() { - _work_loop.Dispose(); - _rows.Dispose(); - Disposable.dispose(_row_vms); - _model.Dispose(); - Disposable.dispose(_context_menu); - } - - public class RowVM : DisposableViewModelBase { - public RowVM(MarketViewVM owner, MarketViewModel model, ref SecurityMD security_md, IObservable position) { - _owner = owner; - _model = model; - _security_md = security_md; - _position = backing(nameof(position), position); - _bid_price = backing(nameof(bid_price), double.NaN); - _bid_size = backing(nameof(bid_size), (ushort)0); - _ask_price = backing(nameof(ask_price), double.NaN); - _ask_size = backing(nameof(ask_size), (ushort)0); - _last_price = backing(nameof(last_price), double.NaN); - _last_size = backing(nameof(last_size), (ushort)0); - _settlement = backing(nameof(settlement), double.NaN); - _volume = backing(nameof(volume), (ulong)0); - _day_change = backing(nameof(day_change), _last_price.Select(v => v.newval).CombineLatest(_settlement.Select(v => v.newval), (l, s) => l - s), double.NaN); - _session_low = backing(nameof(session_low), double.NaN); - _session_high = backing(nameof(session_high), double.NaN); - _working_best_bid = backing(nameof(working_best_bid), double.NaN); - _working_best_ask = backing(nameof(working_best_ask), double.NaN); - _working_orders = new ObservableFilterCollection(_orders, o => o.is_active()); - _working_bids = new ObservableFilterCollection(_working_orders, o => o.order().Side == BuySell.Buy); - _working_asks = new ObservableFilterCollection(_working_orders, o => o.order().Side == BuySell.Sell); - _working_bids_sorted = new ObservableSortedCollection(_working_bids, CompareUtils.NullCheckComparer((x, y) => y.order().Price.CompareTo(x.order().Price))); - _working_asks_sorted = new ObservableSortedCollection(_working_asks, CompareUtils.NullCheckComparer((x, y) => x.order().Price.CompareTo(y.order().Price))); - _inside_bids = new ObservableFilterCollection(_working_bids_sorted, o => o.order().Price >= bid_price); - _inside_asks = new ObservableFilterCollection(_working_asks_sorted, o => o.order().Price <= ask_price); - _working_best_bid = backing(nameof(working_best_bid), _working_bids_sorted.Observe().Select(_ => _working_bids_sorted.Count == 0 ? double.NaN : _working_bids_sorted.First().order().Price).ObserveOnDispatcher()); - _working_best_ask = backing(nameof(working_best_ask), _working_asks_sorted.Observe().Select(_ => _working_asks_sorted.Count == 0 ? double.NaN : _working_asks_sorted.First().order().Price).ObserveOnDispatcher()); - _working_bid_volume = backing(nameof(working_bid_volume), _working_bids.Observe().Select(_ => _working_bids.Aggregate(0u, (v, o) => v + o.order().Size - o.Fills.Aggregate(0u, (fv, f) => fv + f.Size))).ObserveOnDispatcher()); - _working_ask_volume = backing(nameof(working_ask_volume), _working_asks.Observe().Select(_ => _working_asks.Aggregate(0u, (v, o) => v + o.order().Size - o.Fills.Aggregate(0u, (fv, f) => fv + f.Size))).ObserveOnDispatcher()); - _working_bids_text = backing(nameof(working_bids_text), _working_bid_volume.Select(vals => vals.newval).CombineLatest( - _working_best_bid.Select(vals => vals.newval), (size, price) => size == 0u ? string.Empty : "{0} / {1}".fmt(size, security.ContractSpec.format(price))).ObserveOnDispatcher()); - _working_asks_text = backing(nameof(working_asks_text), _working_ask_volume.Select(vals => vals.newval).CombineLatest( - _working_best_ask.Select(vals => vals.newval), (size, price) => size == 0u ? string.Empty : "{0} / {1}".fmt(size, security.ContractSpec.format(price))).ObserveOnDispatcher()); - _animation.AnimationsChanged += _animation_AnimationsChanged; - _dispose = Disposable.Create( - _position.Select(p => p.newval > p.oldval).ObserveOnDispatcher().Subscribe(_animation.animate_position), - _working_bids.Observe().Select(_ => _working_bids.Count > 0).DistinctUntilChanged().ObserveOnDispatcher().Subscribe(_animation.animate_working_bids_active), - _working_asks.Observe().Select(_ => _working_asks.Count > 0).DistinctUntilChanged().ObserveOnDispatcher().Subscribe(_animation.animate_working_asks_active), - _inside_bids.Observe().Select(_ => _inside_bids.Count > 0).DistinctUntilChanged().ObserveOnDispatcher().Subscribe(_animation.animate_working_bids_inside), - _inside_asks.Observe().Select(_ => _inside_asks.Count > 0).DistinctUntilChanged().ObserveOnDispatcher().Subscribe(_animation.animate_working_asks_inside), - _day_change.Select(vals => vals.newval > vals.oldval).ObserveOnDispatcher().Subscribe(_animation.animate_day_change), - Disposable.Create(() => _animation.AnimationsChanged -= _animation_AnimationsChanged) - ); + private IEnumerable _context_menu_item_factory() { + yield return MenuItemVM.Create(new ModifySecuritySelectionMenuItem(_rows.Select(r => r.security).ToList(), _model.set_securities)); + if (current_cell != null && current_cell.Column != null && current_cell.Item != null && !current_cell.Item.Equals(System.Windows.DependencyProperty.UnsetValue)) { + var curr_col = (Columns)DataGridEx.GetArgument(current_cell.Column); + var securities = _rows_vm.Where(r => r.is_selected).Select(r => r.security.value).ToList(); + yield return MenuItemVM.Create(new LadderMenuItem(_bus), securities); + yield return MenuItemVM.Create(new LinkedLadderMenuItem(_bus, _get_current_security_observable().ToSecurityMD())); + yield return MenuItemVM.Create(new OrderTicketMenuItem(_model.orders_model, s => _create_order(_rows_vm.First(r => r.security.value.Equals(s)), curr_col)), securities); + yield return MenuItemVM.Create(new LinkedOrderTicketMenuItem(_bus, _current_cell.Select(_create_order))); + yield return MenuItemVM.Create(new SpreadMatrixMenuItem(_bus), securities); + yield return MenuItemVM.Create(new TimeAndSalesMenuItem(_bus), securities); + yield return MenuItemVM.Create(new SyntheticCreateMenuItem(_bus), securities); + yield return MenuItemVM.Create(new SyntheticStrategyMenuItem(_bus), securities); + yield return MenuItemVM.Create(new ModifyOrderRootMenuItem(_model.orders_model, _order_book.get_active_orders_for_security(securities).Select(e => e.order()).ToList()), securities); + yield return MenuItemVM.Create(new CancelOrderRootMenuItem(_model.orders_model, _order_book.get_active_orders_for_security(securities).Select(e => e.order()).ToList()), securities); + yield return MenuItemVM.Create(new CancelBuyOrdersMenuItem(_model.orders_model), securities); + yield return MenuItemVM.Create(new CancelSellOrdersMenuItem(_model.orders_model), securities); + yield return MenuItemVM.Create(new CancelOrdersMenuItem(_model.orders_model), securities); } + } - private void _animation_AnimationsChanged() { RaisePropertyChanged(nameof(animations)); } - - private readonly MarketViewVM _owner; - private readonly MarketViewModel _model; - private readonly AnimationManager _animation = new AnimationManager(); - private readonly SecurityMD _security_md; - private readonly ObservableCollection _orders = new ObservableCollection(); - private readonly ObservableFilterCollection _working_orders, _working_bids, _working_asks, _inside_bids, _inside_asks; - private readonly ObservableSortedCollection _working_bids_sorted, _working_asks_sorted; - private ulong _bbo_time = 0, _last_time = 0; - private Property _position; - private Property _bid_size, _ask_size, _last_size; - private Property _bid_price, _ask_price, _last_price, _settlement, _day_change, _session_low, _session_high, _working_best_bid, _working_best_ask; - private Property _working_bid_volume, _working_ask_volume; - private Property _working_bids_text, _working_asks_text; - private Property _volume; - - #region Bound Properties - public Security security => _security_md.security; - public bool is_selected { get; set; } - public int position => _position.Value; - public double last_price => _last_price.Value; - public ushort last_size => _last_size.Value; - public double bid_price => _bid_price.Value; - public ushort bid_size => _bid_size.Value; - public double ask_price => _ask_price.Value; - public ushort ask_size => _ask_size.Value; - public ulong volume => _volume.Value; - public double settlement => _settlement.Value; - public double day_change => _day_change.Value; - public double session_low => _session_low.Value; - public double session_high => _session_high.Value; - public double working_best_bid => _working_best_bid.Value; - public double working_best_ask => _working_best_ask.Value; - public uint working_bid_volume => _working_bid_volume.Value; - public uint working_ask_volume => _working_ask_volume.Value; - public string working_bids_text => _working_bids_text.Value; - public string working_asks_text => _working_asks_text.Value; - public IEnumerable animations => _animation.get_animations(); - public ICommand show_ladder => new DelegateCommand(() => _model.show_ladder(_security_md.security)); - public ICommand show_order_ticket => new DelegateCommand(col => { - switch(col) { - case Columns.Bid: _model.show_order_ticket(security, BuySell.Sell, bid_price); break; - case Columns.BidSize: _model.show_order_ticket(security, BuySell.Sell, bid_price, bid_size); break; - case Columns.Ask: _model.show_order_ticket(security, BuySell.Buy, ask_price); break; - case Columns.AskSize: _model.show_order_ticket(security, BuySell.Buy, ask_price, ask_size); break; - case Columns.WorkingBids: - if (_working_bids_sorted.Count > 0) _model.show_order_modify(_working_bids_sorted.First().order()); - else _model.show_order_ticket(security, BuySell.Buy, bid_price); - break; - case Columns.WorkingAsks: - if (_working_asks_sorted.Count > 0) _model.show_order_modify(_working_asks_sorted.First().order()); - else _model.show_order_ticket(security, BuySell.Sell, ask_price); - break; - } - }); - #endregion - - public void refresh(IEnumerable orders) { - if (_security_md.md.get_bbo(ref _bbo_time, out NativePriceSize b, out NativePriceSize a)) { - _bid_price.set(b.price); - _bid_size.set(b.size); - _ask_price.set(a.price); - _ask_size.set(a.size); - } - if (_security_md.md.get_last_trade(ref _last_time, out NativePriceSize l, out DateTime ts, out ulong v)) { - _last_price.set(l.price); - _last_size.set(l.size); - _volume.set(v); - } - _settlement.set(_security_md.md.settlement_price); - _session_low.set(_security_md.md.session_low); - _session_high.set(_security_md.md.session_high); - _orders.sync_with(orders); + private IObservable _get_current_security_observable() { return _current_cell.Select(_get_security).DistinctUntilChanged(); } + private static Security _get_security(DataGridCellInfo cell) { return ((Row)cell.Item).security.value; } + private static Order _create_order(DataGridCellInfo cell) { return _create_order((Row)cell.Item, (Columns)DataGridEx.GetArgument(cell.Column)); } + private static Order _create_order(Row row, Columns col) { + var order = new Order { Security = row.security.value, MarketOrder = new MarketOrder(), Price = 0, Size = 1 }; + switch(col) { + case Columns.Bid: order.Price = row.bid_price.output; break; + case Columns.BidSize: order.Price = row.bid_price.output; order.Size = row.bid_size.output; break; + case Columns.Ask: order.Price = row.ask_price.output; break; + case Columns.AskSize: order.Price = row.ask_price.output; order.Size = row.ask_size.output; break; + case Columns.Last: order.Price = row.last_price.output; break; + case Columns.LastSize: order.Price = row.last_price.output; order.Size = row.last_size.output; break; + case Columns.WorkingBids: order.Price = row.working_best_bid; break; + case Columns.WorkingAsks: order.Price = row.working_best_ask; break; + case Columns.SessionLow: order.Price = row.session_low.output; break; + case Columns.SessionHigh: order.Price = row.session_high.output; break; } + return order; + } - public IReadOnlyList get_bids_sorted() { return _working_bids_sorted.Select(o => o.order()).ToList(); } - public IReadOnlyList get_asks_sorted() { return _working_asks_sorted.Select(o => o.order()).ToList(); } - } + public double row_height { get; set; } = 18; + public ICollectionView rows_view { get; } + public DataGridCellInfo current_cell { get => _current_cell.Value; set => _current_cell.set(value); } + public ContextMenuVM context_menu => _context_menu; + + public StartupData get_startup_data() { return new StartupData(_rows.Select(r => r.security).ToArray(), rows_view.SortDescriptions.Select(sd => new SortingCriteria { col_name = sd.PropertyName, is_ascending = sd.Direction == ListSortDirection.Ascending }).ToArray()); } + protected override void Dispose(bool disposing) { Disposable.dispose(_resources); } [ProtoContract] public class StartupData { diff --git a/src/client/spark/mspark/MarketView/MarketViewView.xaml b/src/client/spark/mspark/MarketView/MarketViewView.xaml index 2533ea67c..f76bf5616 100644 --- a/src/client/spark/mspark/MarketView/MarketViewView.xaml +++ b/src/client/spark/mspark/MarketView/MarketViewView.xaml @@ -1,158 +1,175 @@ - - - - - - - - - - - - - - - - - - - - --> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/MarketView/MarketViewView.xaml.cs b/src/client/spark/mspark/MarketView/MarketViewView.xaml.cs index 6b6c5196f..1239ec67e 100644 --- a/src/client/spark/mspark/MarketView/MarketViewView.xaml.cs +++ b/src/client/spark/mspark/MarketView/MarketViewView.xaml.cs @@ -12,7 +12,7 @@ namespace mbts.ui.spark /// public partial class MarketViewView : UserControl { - public enum Columns { Position, Bid, BidSize, WorkingBids, Ask, AskSize, WorkingAsks, Last, LastSize, DayChange } + public enum Columns { Security, Volume, Last, LastSize, Position, WorkingBids, Bid, BidSize, Ask, AskSize, WorkingAsks, Settlement, DayChange, SessionLow, SessionHigh } public MarketViewView() { InitializeComponent(); diff --git a/src/client/spark/mspark/MarketView/MarketViewWindow.cs b/src/client/spark/mspark/MarketView/MarketViewWindow.cs deleted file mode 100644 index 4330f3c8c..000000000 --- a/src/client/spark/mspark/MarketView/MarketViewWindow.cs +++ /dev/null @@ -1,56 +0,0 @@ -using mbts.ui; -using System; -using System.IO; -using System.Linq; -using System.Windows.Media; -using mbts.ui.shell; -using mbts.ui.spark; -using bts.api; -using System.Collections.Generic; -using static mbts.ui.shell.ProtoBufSerializationHelper; - -namespace mbts.spark -{ - internal class MarketViewWindow : IShellWindow - { - public MarketViewWindow(IShellModule owner, IBus bus, IReadOnlyCollection securities) : this(owner, bus, securities, new SortingCriteria[0]) { } - public MarketViewWindow(IShellModule owner, IBus bus, MarketViewVM.StartupData startup_data) : this(owner, bus, startup_data.securities.Select(deserialize).ToList(), startup_data.sorting_criteria) { } - - private MarketViewWindow(IShellModule owner, IBus bus, IReadOnlyCollection securities, IReadOnlyCollection sorting_criteria) { - _bus = bus; - _securities = securities; - _sorting_criteria = sorting_criteria; - _owner = owner; - } - - private readonly IBus _bus; - private readonly IReadOnlyCollection _securities; - private readonly IReadOnlyCollection _sorting_criteria; - private MarketViewVM _vm; - private IShellModule _owner; - private string _title = "Market Sheets"; - private ImageSource _icon = Icons.Sheets; - - public string Title { get => _title; set { _title = value; TitleChanged(); } } - public ImageSource Icon { get => _icon; set { _icon = value; IconChanged(); } } - public IShellModule Owner { get => _owner; set => _owner = value; } - - public event Action TitleChanged; - public event Action IconChanged; - public void Dispose() { Disposable.dispose(ref _vm); } - public ShellWindowUI GetContent() { - var mvv = new MarketViewView { DataContext = _vm = new MarketViewVM(_bus, _securities, _sorting_criteria) }; - const double two_thirds = 2.0 / 3.0; - const double title_panel_height = 32.0, col_header_height = 26 + two_thirds + 10.0, row_height = 15 + two_thirds; - mvv.Height = Math.Min(title_panel_height + col_header_height + _securities.Count * row_height, System.Windows.SystemParameters.WorkArea.Height); - mvv.Width = 705; - return new ShellWindowUI(mvv); - } - public void GetState(Stream save_here) { - if (_vm != null) { - serialize(save_here, new ShellSerializationHeader { name = MarketViewVM.SAVE_NAME, version = MarketViewVM.VERSION }); - serialize(save_here, _vm.get_startup_data()); - } - } - } -} \ No newline at end of file diff --git a/src/client/spark/mspark/Orders/IOrderBook.cs b/src/client/spark/mspark/Orders/IOrderBook.cs index 1d541e106..e4fa4fabf 100644 --- a/src/client/spark/mspark/Orders/IOrderBook.cs +++ b/src/client/spark/mspark/Orders/IOrderBook.cs @@ -1,5 +1,7 @@ using System.Collections.Generic; +using System.Linq; using bts.spark; +using bts.api; namespace mbts.spark { @@ -7,11 +9,40 @@ namespace mbts.spark { OrderBookEntry get_order(OrderID order_id); IEnumerable get_all_orders(); - IEnumerable get_all_orders_for_security(uint security); - IEnumerable get_all_fills(); - IEnumerable get_all_fill_tuples(); - IDictionary> get_order_sec_map(); - IDictionary> get_fill_sec_map(); - IDictionary> get_fill_tuple_sec_map(); + } + + public static class OrderBookExtensions + { + public static IEnumerable get_all_orders_for_security(this IOrderBook ob, Security security) { return ob.get_all_orders_for_security(security.Id); } + public static IEnumerable get_all_orders_for_security(this IOrderBook ob, IEnumerable security) { return ob.get_all_orders_for_security(new HashSet(security.Select(s => s.Id))); } + public static IEnumerable get_all_orders_for_security(this IOrderBook ob, uint security) { return ob.get_all_orders().Where(e => e.sec_key() == security); } + public static IEnumerable get_all_orders_for_security(this IOrderBook ob, IEnumerable securities) { return ob.get_all_orders_for_security(new HashSet(securities)); } + public static IEnumerable get_all_orders_for_security(this IOrderBook ob, HashSet securities) { return ob.get_all_orders().Where(e => securities.Contains(e.sec_key())); } + public static IDictionary> get_order_sec_map(this IOrderBook ob) { return ob.get_all_orders().Map(e => e.sec_key()); } + + public static IEnumerable get_active_orders(this IOrderBook ob) { return ob.get_all_orders().Where(e => e.is_active()); } + public static IEnumerable get_active_orders_for_security(this IOrderBook ob, Security security) { return ob.get_active_orders_for_security(security.Id); } + public static IEnumerable get_active_orders_for_security(this IOrderBook ob, IEnumerable security) { return ob.get_active_orders_for_security(new HashSet(security.Select(s => s.Id))); } + public static IEnumerable get_active_orders_for_security(this IOrderBook ob, uint security) { return ob.get_all_orders().Where(e => e.sec_key() == security && e.is_active()); } + public static IEnumerable get_active_orders_for_security(this IOrderBook ob, IEnumerable securities) { return ob.get_active_orders_for_security(new HashSet(securities)); } + public static IEnumerable get_active_orders_for_security(this IOrderBook ob, HashSet securities) { return ob.get_all_orders().Where(e => securities.Contains(e.sec_key()) && e.is_active()); } + public static IDictionary> get_active_order_sec_map(this IOrderBook ob) { return ob.get_active_orders().Map(e => e.sec_key()); } + + public static IEnumerable get_all_fills(this IOrderBook ob) { return ob.get_all_orders().SelectMany(e => e.Fills); } + public static IEnumerable get_all_fills_for_security(this IOrderBook ob, Security security) { return ob.get_all_fills_for_security(security.Id); } + public static IEnumerable get_all_fills_for_security(this IOrderBook ob, IEnumerable security) { return ob.get_all_fills_for_security(new HashSet(security.Select(s => s.Id))); } + public static IEnumerable get_all_fills_for_security(this IOrderBook ob, uint security) { return ob.get_all_orders_for_security(security).SelectMany(e => e.Fills); } + public static IEnumerable get_all_fills_for_security(this IOrderBook ob, IEnumerable securities) { return ob.get_all_fills_for_security(new HashSet(securities)); } + public static IEnumerable get_all_fills_for_security(this IOrderBook ob, HashSet securities) { return ob.get_all_orders_for_security(securities).SelectMany(e => e.Fills); } + public static IDictionary> get_fill_sec_map(this IOrderBook ob) { return ob.get_all_fills().Map(f => f.Order.Security.Id); } + + public static IEnumerable get_all_fill_tuples(this IOrderBook ob) { return ob.get_all_orders().SelectMany(e => e.Fills.Select(f => new FillTuple(f, e))); } + public static IEnumerable get_all_fill_tuples_for_security(this IOrderBook ob, Security security) { return ob.get_all_fill_tuples_for_security(security.Id); } + public static IEnumerable get_all_fill_tuples_for_security(this IOrderBook ob, IEnumerable security) { return ob.get_all_fill_tuples_for_security(new HashSet(security.Select(s => s.Id))); } + public static IEnumerable get_all_fill_tuples_for_security(this IOrderBook ob, uint security) { return ob.get_all_orders_for_security(security).SelectMany(e => e.Fills.Select(f => new FillTuple(f, e))); } + public static IEnumerable get_all_fill_tuples_for_security(this IOrderBook ob, IEnumerable securities) { return ob.get_all_fill_tuples_for_security(new HashSet(securities)); } + public static IEnumerable get_all_fill_tuples_for_security(this IOrderBook ob, HashSet securities) { return ob.get_all_orders_for_security(securities).SelectMany(e => e.Fills.Select(f => new FillTuple(f, e))); } + public static IDictionary> get_fill_tuple_sec_map(this IOrderBook ob) { return ob.get_all_orders().Map(o => o.sec_key(), o => o.Fills.Select(f => new FillTuple(f, o))); } + } } \ No newline at end of file diff --git a/src/client/spark/mspark/Orders/OrderBook.cs b/src/client/spark/mspark/Orders/OrderBook.cs index 54f7aa28a..d0bb211b8 100644 --- a/src/client/spark/mspark/Orders/OrderBook.cs +++ b/src/client/spark/mspark/Orders/OrderBook.cs @@ -19,7 +19,7 @@ namespace mbts.spark OrderBookEntry curr = get_order(order_status.Order.Id); if (curr == null) { /// new order - curr = new OrderBookEntry () { OrderStatus = order_status, }; + curr = new OrderBookEntry() { OrderStatus = order_status }; if (curr.parent_id() == null) { /// Does not have a parent => its a "Root" order _orderbook.Add(curr); @@ -74,30 +74,6 @@ namespace mbts.spark return _get_all_orders(_orderbook); } - public IEnumerable get_all_orders_for_security(uint security) { - return get_all_orders().Where(o => o.OrderStatus.Order.Security.Id == security); - } - - public IDictionary> get_order_sec_map() { - return get_all_orders().Map(o => o.sec_key(), o => o); - } - - public IEnumerable get_all_fills() { - return get_all_orders().SelectMany(o => o.Fills); - } - - public IDictionary> get_fill_sec_map() { - return get_all_fills().Map(f => f.Order.Security.Id); - } - - public IEnumerable get_all_fill_tuples() { - return get_all_orders().SelectMany(o => o.Fills.Select(f => new FillTuple(f, o))); - } - - public IDictionary> get_fill_tuple_sec_map() { - return get_all_orders().Map(o => o.sec_key(), o => o.Fills.Select(f => new FillTuple(f, o))); - } - #endregion private void _remove_child_entry(OrderID parent_order_id, OrderID child_order_id) { diff --git a/src/client/spark/mspark/Orders/OrderExtensions.cs b/src/client/spark/mspark/Orders/OrderExtensions.cs index 4d5b3066f..7e1c5fa05 100644 --- a/src/client/spark/mspark/Orders/OrderExtensions.cs +++ b/src/client/spark/mspark/Orders/OrderExtensions.cs @@ -48,5 +48,14 @@ namespace mbts.spark public static bool is_child(this OrderBookEntry me) { return me.parent_id() != null; } + + public static string summary(this Order order, bool show_side=true, bool show_security=true, bool show_price=true, bool show_qty=true) { + var parts = new List(); + if (show_side) parts.Add(order.Side); + if (show_security) parts.Add(order.Security.ToString(null)); + if (show_price) parts.Add(order.Security.ContractSpec.format(order.Price)); + if (show_qty) parts.Add("@ {0}".fmt(order.Size)); + return string.Join(" ", parts); + } } } diff --git a/src/client/spark/mspark/Orders/OrderModificationControl.xaml b/src/client/spark/mspark/Orders/OrderModificationControl.xaml index 9f6ac090c..46cb832e0 100644 --- a/src/client/spark/mspark/Orders/OrderModificationControl.xaml +++ b/src/client/spark/mspark/Orders/OrderModificationControl.xaml @@ -1,70 +1,36 @@  + xmlns:usp="clr-namespace:mbts.ui.spark" + xmlns:uag="clr-namespace:mbts.ui.spark.algo" + xmlns:sys="clr-namespace:System;assembly=mscorlib"> - + + + + + + + + + + 8.0 4.0 22.0 - @@ -78,9 +44,9 @@ - + - + @@ -117,26 +83,86 @@ - + - - + + - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - + \ No newline at end of file diff --git a/src/client/spark/mspark/Orders/OrderModificationControl.xaml.cs b/src/client/spark/mspark/Orders/OrderModificationControl.xaml.cs index 9312d30b5..bfa906775 100644 --- a/src/client/spark/mspark/Orders/OrderModificationControl.xaml.cs +++ b/src/client/spark/mspark/Orders/OrderModificationControl.xaml.cs @@ -1,17 +1,6 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using bts.spark; using System.Windows; using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; namespace mbts.ui.spark { @@ -24,4 +13,14 @@ namespace mbts.ui.spark InitializeComponent(); } } + + internal class OrderModificationTemplateSelector : DataTemplateSelector + { + public DataTemplate BTSIcebergOrderTemplate { get; set; } + public DataTemplate ReflectionTemplate { get; set; } + public override DataTemplate SelectTemplate(object item, DependencyObject container) { + if (item is BTSIcebergOrder) return BTSIcebergOrderTemplate; + else return ReflectionTemplate; + } + } } \ No newline at end of file diff --git a/src/client/spark/mspark/Orders/OrderModificationDialog.xaml b/src/client/spark/mspark/Orders/OrderModificationDialog.xaml index 22ea4fb15..04ccf9cd4 100644 --- a/src/client/spark/mspark/Orders/OrderModificationDialog.xaml +++ b/src/client/spark/mspark/Orders/OrderModificationDialog.xaml @@ -2,10 +2,8 @@ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:sys="clr-namespace:System;assembly=mscorlib" - xmlns:uc="clr-namespace:mbts.ui" xmlns:u="clr-namespace:mbts.ui" xmlns:usp="clr-namespace:mbts.ui.spark" - xmlns:uspcv="clr-namespace:mbts.ui.spark.converters" u:WindowStyle.SizeToContent="WidthAndHeight" u:WindowStyle.TitleContent="{Binding bbo, Mode=OneWay}" u:WindowStyle.CloseOnEscape="True" @@ -13,40 +11,13 @@ - + 8.0 4.0 22.0 - @@ -64,4 +35,31 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Orders/OrderParamsVM.cs b/src/client/spark/mspark/Orders/OrderParamsVM.cs index ca00d730b..65b705feb 100644 --- a/src/client/spark/mspark/Orders/OrderParamsVM.cs +++ b/src/client/spark/mspark/Orders/OrderParamsVM.cs @@ -1,39 +1,100 @@ -using bts.spark; +using bts.api; +using bts.spark; using Google.Protobuf; +using mbts.spark.utilities; using mbts.ui.shell; using mbts.ui.utility; using System; using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Reactive.Linq; +using System.Windows.Data; namespace mbts.spark { internal class OrderHelper { - public static IMessage[] get_default_algos() { return new IMessage[] { new MarketOrder(), new LimitOrder(), new StopMarketOrder(), new StopLimitOrder(), new IcebergOrder(), }; } + public static IMessage[] get_default_algos() { + return new IMessage[] { + new MarketOrder(), + new LimitOrder(), + new StopMarketOrder(), + new StopLimitOrder(), + new IcebergOrder(), + new BTSStopOrder(), + new BTSIcebergOrder { + DisplayQuantity = Defaults.QuantityMeasure, + MarketOffset = Defaults.PriceOffset, + PriceTrigger = Defaults.PriceTrigger, + TimedWindowParameters = Defaults.TimeWindow, + WithatickParameters = Defaults.WithATick + } + }; + } + public static Order get_default_order(Security security) { + return new Order { + User = ImportedResources.UserName, + Security = security, + LimitOrder = new LimitOrder() + }; + } + + public static class Defaults + { + public static QuantityMeasure QuantityMeasure => new QuantityMeasure { Absolute = 1 }; + public static PriceType PriceType => new PriceType { Status = PriceType.Types.Status.Bid }; + public static PriceOffset PriceOffset => new PriceOffset { PriceType = PriceType }; + public static QuantityTrigger QuantityTrigger => new QuantityTrigger { QuantityMeasure = QuantityMeasure, LessThanEqualto = true }; + public static AbsolutePriceTrigger AbsolutePriceTrigger => new AbsolutePriceTrigger { PriceType = PriceType, QuantityTrigger = QuantityTrigger }; + public static TrailingTrigger TrailingTrigger => new TrailingTrigger { PriceType = PriceType, Stop = true }; + public static PriceTrigger PriceTrigger => new PriceTrigger { AbsolutePriceTrigger = AbsolutePriceTrigger, TrailingTrigger = TrailingTrigger }; + public static OrderTime OrderTime => new OrderTime { Now = true }; + public static BTSTimedWindowParameters TimeWindow => new BTSTimedWindowParameters { Cancel = true, StartTime = OrderTime, StopTime = new OrderTime() }; + public static BTSWithATickParameters WithATick => new BTSWithATickParameters { QuantityThreshold = QuantityMeasure }; + public static BTSIcebergOrder BTSIcebergOrder => new BTSIcebergOrder { DisplayQuantity = QuantityMeasure, MarketOffset = PriceOffset, PriceTrigger = PriceTrigger, TimedWindowParameters = TimeWindow, WithatickParameters = WithATick }; + } } - internal class OrderParamsVM : ViewModelBase + internal class OrderParamsVM : DisposableViewModelBase { - public OrderParamsVM(Order order, OrdersModel model) { - _order = order; + public OrderParamsVM(Order order, OrdersModel model) : this(Observable.Return(order), model) { } + public OrderParamsVM(IObservable order, OrdersModel model) { _model = model; - algo_types = OrderHelper.get_default_algos().Select(algo => { - var meta = _model.get_metadata(algo); - return meta != null ? new OrderTypeVM(_order, algo, meta) : null; - }).ToArray(); - if (string.IsNullOrEmpty(account)) account = accounts[0]; + _dispose = order.Subscribe(o => { + _order = o; + _algo_types.Clear(); + foreach (var a in _get_algo_types()) _algo_types.Add(a); + RaisePropertyChanged(nameof(account), nameof(algo_type), nameof(time_in_force)); + }); + _algo_types = new ObservableCollection(_get_algo_types()); + algo_types_view = CollectionViewSource.GetDefaultView(_algo_types); + algo_types_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(OrderTypeVM.is_bts_type))); + algo_types_view.SortDescriptions.Add(new SortDescription(nameof(OrderTypeVM.is_bts_type), ListSortDirection.Ascending)); } private readonly OrdersModel _model; - private readonly Order _order; + private readonly ObservableCollection _algo_types; + private Order _order = new Order { LimitOrder = new LimitOrder() }; - public string[] accounts => new[] { "Account1", "Account2", "Account3", "Account4" }; + private IEnumerable _get_algo_types() { + return OrderHelper.get_default_algos().Select(algo => { + var meta = _model.get_metadata(algo); + return meta != null ? new OrderTypeVM(_order, algo, meta) : null; + }); + } + + public string[] accounts { get; } = new[] { "Account1", "Account2", "Account3", "Account4" }; public string account { get => _order.Account; set => _order.Account = value; } - public OrderTypeVM[] algo_types { get; } - public OrderTypeVM algo_type { get => algo_types.FirstOrDefault(o => o.is_selected); set { value.is_selected = true; RaisePropertyChanged(); } } + public ICollectionView algo_types_view { get; private set; } + public OrderTypeVM algo_type { + get => _algo_types.FirstOrDefault(o => o.is_selected); + set { + if (value != null) value.is_selected = true; + RaisePropertyChanged(); + } + } public IEnumerable time_in_forces => EnumHelper.get_values(); public Order.Types.TimeInForce time_in_force { get => _order.TimeInForce; set => _order.TimeInForce = value; } } diff --git a/src/client/spark/mspark/Orders/OrderTicket.xaml b/src/client/spark/mspark/Orders/OrderTicket.xaml index 7be5e810f..5d0641ca4 100644 --- a/src/client/spark/mspark/Orders/OrderTicket.xaml +++ b/src/client/spark/mspark/Orders/OrderTicket.xaml @@ -1,65 +1,64 @@ - - - - - - - 8.0 - 4.0 - 22.0 - - - - - - - - - - - - - - - - - - - + + + + + + + 8.0 + 4.0 + 22.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Orders/OrderTicketVM.cs b/src/client/spark/mspark/Orders/OrderTicketVM.cs index 4a84249e1..f91cb0294 100644 --- a/src/client/spark/mspark/Orders/OrderTicketVM.cs +++ b/src/client/spark/mspark/Orders/OrderTicketVM.cs @@ -10,24 +10,31 @@ namespace mbts.spark { internal class OrderTicketVM : DisposableViewModelBase { - public OrderTicketVM(Order order, OrdersModel model, SecurityMD smd, IObservable settings) { - _order = order; - order_params = new OrderParamsVM(_order, model); - bbo = new BBOVM(smd); - size_calculator = new CalculatorLogic(order.Size, settings.Select(s => s.calculator_buttons)); + public OrderTicketVM(OrdersModel model, Order order, IObservable settings) : this(model, Observable.Return(order), settings) { } + public OrderTicketVM(OrdersModel model, IObservable order, IObservable settings) { + var order_pub = order.Select(o => { + _order = o; + size_calculator.value = _order.Size; + RaisePropertyChanged(nameof(price), nameof(security)); + return _order; + }).Publish(); + order_params = new OrderParamsVM(order_pub, model); + bbo = new BBOVM(order.Select(o => o.Security)); + size_calculator = new CalculatorLogic(0, settings.Select(s => s.calculator_buttons)); set_price_command = new DelegateCommand(p => { price = p; RaisePropertyChanged(nameof(price)); }); send_order = new DelegateCommand(side => { _prepare_order(side); model.send_order(_order); }); modify_order = new DelegateCommand(() => { _prepare_order(); model.modify_order(_order); }); cancel_order = new DelegateCommand(() => model.cancel_order(new[] { _order.Id })); - _dispose = WorkLoop.Start(bbo.refresh); + _dispose = Disposable.Create(order_pub.Connect(), order_params, bbo); } - private readonly Order _order; + private Order _order = new Order { Security = Security.Empty, LimitOrder = new LimitOrder() }; private void _prepare_order(BuySell? side = null) { _order.Size = size_calculator.value; if (side != null) _order.Side = side.Value; } + public Security security => _order.Security; public CalculatorLogic size_calculator { get; } public double price { get => _order.Price; set => _order.Price = value; } @@ -37,5 +44,5 @@ namespace mbts.spark public ICommand send_order { get; } public ICommand modify_order { get; } public ICommand cancel_order { get; } - } + } } \ No newline at end of file diff --git a/src/client/spark/mspark/Orders/OrdersModel.cs b/src/client/spark/mspark/Orders/OrdersModel.cs index 20ca59e7d..ceec4df6c 100644 --- a/src/client/spark/mspark/Orders/OrdersModel.cs +++ b/src/client/spark/mspark/Orders/OrdersModel.cs @@ -94,6 +94,12 @@ namespace mbts.spark return true; } + + public void show_order_ticket(Order order) { _bus.post(SparkTags.ShowOrderTicketTag, new SparkBusData.ShowOrderTicketMessage(order)); } + public void show_order_ticket(IReadOnlyCollection orders) { _bus.post(SparkTags.ShowOrderTicketTag, new SparkBusData.ShowOrderTicketMessage(orders)); } + public void show_order_modify(Order order) { _bus.post(SparkTags.ShowOrderModifyTag, new SparkBusData.ShowOrderModifyMessage(order)); } + public void show_order_modify(IReadOnlyCollection orders) { _bus.post(SparkTags.ShowOrderModifyTag, new SparkBusData.ShowOrderModifyMessage(orders)); } + internal void show_order_details(OrderID order_id) { _bus.post(SparkTags.ShowOrderDetailsTag, order_id); } @@ -119,6 +125,7 @@ namespace mbts.spark case Order.AlgoOrderTypeOneofCase.IcebergOrder: return new OrderMetadata() { KeyBinding = "I", Color = BTSColors.module_colors[4].rgb_color() }; case Order.AlgoOrderTypeOneofCase.CrossingHedgeOrder: + case Order.AlgoOrderTypeOneofCase.SimpleHedgeOrder: case Order.AlgoOrderTypeOneofCase.CustomOrder: default: case Order.AlgoOrderTypeOneofCase.None: diff --git a/src/client/spark/mspark/Orders/Sim/OrderActivitySimulator.cs b/src/client/spark/mspark/Orders/Sim/OrderActivitySimulator.cs index e5c9b3289..0c0e74896 100644 --- a/src/client/spark/mspark/Orders/Sim/OrderActivitySimulator.cs +++ b/src/client/spark/mspark/Orders/Sim/OrderActivitySimulator.cs @@ -36,7 +36,7 @@ namespace mbts.spark if (DateTime.Now - _last_fill_activity > _fill_activity_period) { _last_fill_activity = DateTime.Now; - IEnumerable exch_orders = _orderbook.get_all_orders().Where(o => OrderUtils.is_active (o.OrderStatus) && o.order().Security.Exchange != Venue.Bts); + IEnumerable exch_orders = _orderbook.get_all_orders().Where(o => o.is_active() && o.order().Security.Exchange != Venue.Bts); foreach (var o in exch_orders) { double qty = o.order().Size, filled = OrderUtils.filled(o); @@ -46,7 +46,7 @@ namespace mbts.spark new_fill_size = filled + new_fill_size <= qty ? new_fill_size : qty - filled; if (new_fill_size + filled >= qty) o.OrderStatus.Status = OrderStatus.Types.Status.Filled; - o.Fills.Add(new Fill() { Order = o.order(), Side = o.order().Side, Size = (uint)new_fill_size, Price = o.order().Price }); + o.Fills.Add(new Fill() { Id = new FillID { Id = Guid.NewGuid().ToString() }, Order = o.order(), Side = o.order().Side, Size = (uint)new_fill_size, Price = o.order().Price }); } } _hub.update_orderbook(_orderbook); diff --git a/src/client/spark/mspark/Orders/Sim/SimExchangeGateway.cs b/src/client/spark/mspark/Orders/Sim/SimExchangeGateway.cs index 9c0aed349..4a7a378df 100644 --- a/src/client/spark/mspark/Orders/Sim/SimExchangeGateway.cs +++ b/src/client/spark/mspark/Orders/Sim/SimExchangeGateway.cs @@ -1,14 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using bts.api; using bts.spark; -using System.Reactive; -using System.Reactive.Subjects; -using System.Reactive.Linq; -using bts.api; +using System; using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Reactive.Linq; +using System.Reactive.Subjects; namespace mbts.spark { diff --git a/src/client/spark/mspark/Orders/Sim/SimSingleSecurityLimitOrderExchangeGateway.cs b/src/client/spark/mspark/Orders/Sim/SimSingleSecurityLimitOrderExchangeGateway.cs index 4342a967d..bfee5d8f6 100644 --- a/src/client/spark/mspark/Orders/Sim/SimSingleSecurityLimitOrderExchangeGateway.cs +++ b/src/client/spark/mspark/Orders/Sim/SimSingleSecurityLimitOrderExchangeGateway.cs @@ -1,155 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using bts.spark; -using System.Reactive; -using System.Reactive.Subjects; -using System.Reactive.Linq; +using bts.spark; namespace mbts.spark -{ - - public interface ISingleSecurityExchangeGateway - { - void init (Order order); - void modify_price (double new_price); - void modify_size (uint size); - void cancel_order (); - void poll (); - IObservable on_order_status{get;} - IObservable on_fills { get; } - } - - internal class SimSingleSecurityLimitOrderExchangeGateway : ISingleSecurityExchangeGateway +{ + internal class SimSingleSecurityLimitOrderExchangeGateway : SimSingleSecurityOrderExchangeGateway { - private readonly ISubject _status_sub = new Subject(); - private readonly ISubject _fill_sub = new Subject(); - private readonly IList _fills = new List(); + public SimSingleSecurityLimitOrderExchangeGateway(OrderID parent_order_id, SecurityMD md) : base(parent_order_id, md) { } - private readonly SecurityMD _md; - private OrderStatus _order; - private OrderID _parent_order_id; - private bool _stop; - private ulong _depth_ref; - public SimSingleSecurityLimitOrderExchangeGateway(OrderID parent_order_id, SecurityMD md) - { - _md = md; - _parent_order_id = parent_order_id; - } - - #region ISingleSecurityExchangeGateway - public void init(bts.spark.Order order) - { - - _order = new OrderStatus() - { - Order = order, - Status = OrderStatus.Types.Status.PendingNew, - ParentId = _parent_order_id, - }; - _fire_status(); - } - - public void modify_price(double new_price) - { - if(OrderUtils.is_active(_order)) - { - _order.Status = OrderStatus.Types.Status.PendingReplace; - _order.Order.Price = new_price; - _fire_status(); - } - } - - public void modify_size(uint new_size) - { - if(OrderUtils.is_active(_order)) - { - _order.Status = OrderStatus.Types.Status.PendingReplace; - _order.Order.Size = new_size; - _fire_status(); - } - } - - public void cancel_order() - { - lock(this) - _stop = true; - _order.Status = OrderStatus.Types.Status.Canceled; - _fire_status(); - } - - public void poll() - { - /// poll md mainly - if(!_stop) - { - lock(this) - { - if(!_stop) - _analyze(); - } - } - } - - public IObservable on_order_status => _status_sub.AsObservable(); - - public IObservable on_fills => _fill_sub.AsObservable(); - #endregion - - #region Private Methods - private void _analyze() - { - if (OrderUtils.is_active(_order)) { - if (_order.Status == OrderStatus.Types.Status.PendingReplace) { - _order.Status = OrderStatus.Types.Status.Replaced; - _fire_status(); - return; - } else { - co2.NativePriceSize[] bids = null, asks = null; - if (_md.md.get_depth(ref _depth_ref, ref bids, ref asks)) { - if (_order.Order.Side == bts.api.BuySell.Buy) { - if (_order.Order.Price >= asks[0].price) _fire_fill(asks[0].price, Math.Min(_order.Order.Size - _aggregate_fill_size(), asks[0].size)); - } else if (_order.Order.Price <= bids[0].price) { - _fire_fill(bids[0].price, Math.Min(_order.Order.Size - _aggregate_fill_size(), bids[0].size)); - } else { - /// cross hasnt happened - _order.Status = _order.Order.TimeInForce == Order.Types.TimeInForce.Fok || _order.Order.TimeInForce == Order.Types.TimeInForce.Ioc ? OrderStatus.Types.Status.Canceled : OrderStatus.Types.Status.New; - } - _fire_status(); - } - } - } - } - - private void _fire_fill(double price, uint size) { - var fill = new Fill { - Id = new FillID { Id = Guid.NewGuid().ToString() }, - Order = _order.Order, - Side = _order.Order.Side, - Price = price, - Size = size, - Timestamp = (ulong)DateTime.Now.Ticks - }; - _fills.Add(fill); - if (_aggregate_fill_size() == _order.Order.Size) { - _stop = true; - _order.Status = OrderStatus.Types.Status.Filled; - } else _order.Status = OrderStatus.Types.Status.PartiallyFilled; - _fill_sub.OnNext(fill); - } - - private uint _aggregate_fill_size() { - uint agg_size = 0; - foreach (var f in _fills) agg_size += f.Size; - return agg_size; - } - - - private void _fire_status() { _status_sub.OnNext(_order); } - - private void _fire_fill(Fill fill) { _fill_sub.OnNext(fill); } - #endregion - } -} \ No newline at end of file + protected override bool acceptable_buy_price(double price) { return price <= _order.Order.Price; } + protected override bool acceptable_sell_price(double price) { return price >= _order.Order.Price; } + } +} diff --git a/src/client/spark/mspark/Orders/Sim/SimSingleSecurityMarketOrderExchangeGateway.cs b/src/client/spark/mspark/Orders/Sim/SimSingleSecurityMarketOrderExchangeGateway.cs index 12606482a..453d4144b 100644 --- a/src/client/spark/mspark/Orders/Sim/SimSingleSecurityMarketOrderExchangeGateway.cs +++ b/src/client/spark/mspark/Orders/Sim/SimSingleSecurityMarketOrderExchangeGateway.cs @@ -1,94 +1,12 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using bts.spark; -using System.Reactive; -using System.Reactive.Subjects; -using System.Reactive.Linq; +using bts.spark; namespace mbts.spark { - internal class SimSingleSecurityMarketOrderExchangeGateway : ISingleSecurityExchangeGateway + internal class SimSingleSecurityMarketOrderExchangeGateway : SimSingleSecurityOrderExchangeGateway { - private readonly ISubject _status_sub = new Subject(); - private readonly ISubject _fill_sub = new Subject(); - private readonly SecurityMD _md; - private OrderID _parent_order_id; + public SimSingleSecurityMarketOrderExchangeGateway(OrderID parent_order_id, SecurityMD md) : base(parent_order_id, md) { } - public SimSingleSecurityMarketOrderExchangeGateway(OrderID parent_order_id, SecurityMD md) - { - _md = md; - _parent_order_id = parent_order_id; - } - - public void init(bts.spark.Order order) - { - OrderStatus order_status = new OrderStatus() - { - Order = order, - Status = OrderStatus.Types.Status.PendingNew, - ParentId = _parent_order_id, - }; - co2.NativePriceSize[] bids = null, asks = null; - _md.md.get_depth(ref bids, ref asks); - if (order_status.Order.Side == bts.api.BuySell.Buy) - { - if (asks != null && asks.Length > 0) - { - order_status.Status = OrderStatus.Types.Status.Filled; - Fill fill = new Fill() - { - Order = order_status.Order, - Price = asks[0].price, - Side = order_status.Order.Side, - Size = order_status.Order.Size - }; - _status_sub.OnNext(order_status); - _fill_sub.OnNext(fill); - } - else - { - order_status.Status = OrderStatus.Types.Status.Rejected; - _status_sub.OnNext(order_status); - } - } - else - { - if (bids != null && bids.Length > 0) - { - order_status.Status = OrderStatus.Types.Status.Filled; - Fill fill = new Fill() - { - Order = order_status.Order, - Price = bids[0].price, - Side = order_status.Order.Side, - Size = order_status.Order.Size - }; - _status_sub.OnNext(order_status); - _fill_sub.OnNext(fill); - } - else - { - order_status.Status = OrderStatus.Types.Status.Rejected; - _status_sub.OnNext(order_status); - } - } - } - - public void modify_price(double new_price) { } - - public void modify_size(uint new_size) { } - - public void cancel_order() { } - - public void poll() { } - - public IObservable on_order_status { get { return _status_sub; } } - - public IObservable on_fills { get { return _fill_sub; } } - - + protected override bool acceptable_buy_price(double price) { return true; } + protected override bool acceptable_sell_price(double price) { return true; } } } diff --git a/src/client/spark/mspark/Orders/Sim/SimSingleSecurityOrderExchangeGateway.cs b/src/client/spark/mspark/Orders/Sim/SimSingleSecurityOrderExchangeGateway.cs new file mode 100644 index 000000000..dab657db1 --- /dev/null +++ b/src/client/spark/mspark/Orders/Sim/SimSingleSecurityOrderExchangeGateway.cs @@ -0,0 +1,135 @@ +using bts.spark; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Reactive.Subjects; + +namespace mbts.spark +{ + public interface ISingleSecurityExchangeGateway + { + void init(Order order); + void modify_price(double new_price); + void modify_size(uint size); + void cancel_order(); + void poll(); + IObservable on_order_status { get; } + IObservable on_fills { get; } + } + + internal abstract class SimSingleSecurityOrderExchangeGateway : ISingleSecurityExchangeGateway + { + private readonly ISubject _status_sub = new Subject(); + private readonly ISubject _fill_sub = new Subject(); + private readonly IList _fills = new List(); + private readonly SecurityMD _md; + + protected OrderStatus _order; + + private OrderID _parent_order_id; + private bool _stop; + private ulong _depth_ref; + protected SimSingleSecurityOrderExchangeGateway(OrderID parent_order_id, SecurityMD md) { + _md = md; + _parent_order_id = parent_order_id; + } + + #region ISingleSecurityExchangeGateway + public void init(Order order) { + _order = new OrderStatus() { Order = order, Status = OrderStatus.Types.Status.PendingNew, ParentId = _parent_order_id, }; + _fire_status(); + } + + public void modify_price(double new_price) { + if (OrderUtils.is_active(_order)) { + _order.Status = OrderStatus.Types.Status.PendingReplace; + _order.Order.Price = new_price; + _fire_status(); + } + } + + public void modify_size(uint new_size) { + if (OrderUtils.is_active(_order)) { + _order.Status = OrderStatus.Types.Status.PendingReplace; + _order.Order.Size = new_size; + _fire_status(); + } + } + + public void cancel_order() { + lock (this) _stop = true; + _order.Status = OrderStatus.Types.Status.Canceled; + _fire_status(); + } + + public void poll() { + /// poll md mainly + if (!_stop) { + lock (this) { + if (!_stop) _analyze(); + _stop = !OrderUtils.is_active(_order); + } + } + } + + public IObservable on_order_status => _status_sub.AsObservable(); + + public IObservable on_fills => _fill_sub.AsObservable(); + #endregion + + #region Private Methods + private void _analyze() { + if (OrderUtils.is_active(_order)) { + if (_order.Status == OrderStatus.Types.Status.PendingReplace) { + _order.Status = OrderStatus.Types.Status.Replaced; + } else { + co2.NativePriceSize[] bids = null, asks = null; + if (_md.md.get_depth(ref _depth_ref, ref bids, ref asks)) { + if (_order.Order.Side == bts.api.BuySell.Buy) _process_fills(asks, acceptable_buy_price); + else _process_fills(bids, acceptable_sell_price); + if (_fills.Count == 0) { + /// cross hasnt happened + _order.Status = _order.Order.TimeInForce == Order.Types.TimeInForce.Fok || _order.Order.TimeInForce == Order.Types.TimeInForce.Ioc ? OrderStatus.Types.Status.Canceled : OrderStatus.Types.Status.New; + } + } + } + _fire_status(); + } + } + + private void _process_fills(co2.NativePriceSize[] depth, Func accept_price) { + int target = _get_fill_target(); + foreach (var d in depth.Where(d => d.size > 0)) { + if (target <= 0 || !accept_price(d.price)) break; + _fire_fill(_get_fill(d.price, target > d.size ? (uint)d.size : (uint)target)); + target = _get_fill_target(); + } + _order.Status = target <= 0 ? OrderStatus.Types.Status.Filled : OrderStatus.Types.Status.PartiallyFilled; + } + + private int _get_fill_target() { return (int)_order.Order.Size - _fills.Sum(f => (int)f.Size); } + + private Fill _get_fill(double price, uint size) { + return new Fill { + Id = new FillID { Id = Guid.NewGuid().ToString() }, + Order = _order.Order, + Side = _order.Order.Side, + Price = price, + Size = size, + Timestamp = (ulong)DateTime.Now.Ticks + }; + } + + private void _fire_status() { _status_sub.OnNext(_order); } + + private void _fire_fill(Fill fill) { + _fills.Add(fill); + _fill_sub.OnNext(fill); + } + #endregion + + protected abstract bool acceptable_buy_price(double price); + protected abstract bool acceptable_sell_price(double price); + } +} diff --git a/src/client/spark/mspark/Themes/generic.xaml b/src/client/spark/mspark/Resources/MenuResources.xaml similarity index 77% rename from src/client/spark/mspark/Themes/generic.xaml rename to src/client/spark/mspark/Resources/MenuResources.xaml index e8f99de97..d5b6ff836 100644 --- a/src/client/spark/mspark/Themes/generic.xaml +++ b/src/client/spark/mspark/Resources/MenuResources.xaml @@ -1,33 +1,28 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/SecurityBrowser/SecurityBrowser.xaml b/src/client/spark/mspark/SecurityBrowser/SecurityBrowser.xaml index 1b20c766b..c2d1819d2 100644 --- a/src/client/spark/mspark/SecurityBrowser/SecurityBrowser.xaml +++ b/src/client/spark/mspark/SecurityBrowser/SecurityBrowser.xaml @@ -1,224 +1,224 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/LaunchMenu/LaunchMenuItemVM.cs b/src/client/spark/mspark/Shell/LaunchMenu/LaunchMenuItemVM.cs index ba64fb99d..7a01bdd09 100644 --- a/src/client/spark/mspark/Shell/LaunchMenu/LaunchMenuItemVM.cs +++ b/src/client/spark/mspark/Shell/LaunchMenu/LaunchMenuItemVM.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; +using System.Reactive.Linq; using System.Windows.Input; using System.Windows.Media; using static mbts.ui.spark.LaunchMenuItemTemplateSelector; @@ -22,8 +23,6 @@ namespace mbts.spark.menu_items public static LaunchMenuItemVM Create(IMenuItem model) { var act_mi = model as IMenuActionItem; if (act_mi != null) return Create(act_mi); - var sec_mi = model as IMenuSecurityActionItem; - if (sec_mi != null) return Create(sec_mi); var secs_mi = model as IMenuSecuritiesActionItem; if (secs_mi != null) return Create(secs_mi); var grp_mi = model as IMenuGroupItem; @@ -37,21 +36,13 @@ namespace mbts.spark.menu_items return new LaunchMenuItemVM(model.display_name, model.sectional_id, model.icon, command, Template.Action, dispose:model as IDisposable); } - public static LaunchMenuItemVM Create(IMenuSecurityActionItem model) { - SecurityLaunchMenuItem rv = null; IDisposable sub = null; - var command = new DelegateCommand(() => model.execute(rv.selected_securities.SingleOrDefault()), () => rv.selected_securities.Count == 1 && model.can_execute(rv.selected_securities[0])); - rv = new SecurityLaunchMenuItem(model.display_name, model.sectional_id, model.icon, command, Template.Security, Disposable.Create(() => { (model as IDisposable)?.Dispose(); sub?.Dispose(); })); - sub = rv.selected_securities.Subscribe((s, e) => command.RaiseCanExecuteChanged()); - model.can_execute_changed += () => command.RaiseCanExecuteChanged(); - return rv; - } - public static LaunchMenuItemVM Create(IMenuSecuritiesActionItem model) { SecurityLaunchMenuItem rv = null; IDisposable sub = null; IRaiseCanExecuteChangedCommand command = null; command = new DelegateCommand(() => { - using (sub) model.execute(rv.selected_securities); + using (sub) model.execute(rv.selected_securities.ToList()); + rv.selected_securities.Clear(); sub = rv.selected_securities.Subscribe((s, e) => command.RaiseCanExecuteChanged()); }, () => model.can_execute(rv.selected_securities)); rv = new SecurityLaunchMenuItem(model.display_name, model.sectional_id, model.icon, command, Template.Securities, Disposable.Create(() => { (model as IDisposable)?.Dispose(); sub?.Dispose(); })); @@ -66,7 +57,7 @@ namespace mbts.spark.menu_items #endregion protected LaunchMenuItemVM(string display_name, string sectional_id, ImageSource icon, ICommand command=null, Template template_key=Template.Action, IEnumerable items=null, IDisposable dispose=null) - : base(display_name, sectional_id, icon, command, items, dispose) { + : base(Observable.Return(display_name), sectional_id, icon, command, items, dispose) { this.template_key = template_key; } diff --git a/src/client/spark/mspark/Shell/MarketModule.cs b/src/client/spark/mspark/Shell/MarketModule.cs index 994d6c89d..21020a768 100644 --- a/src/client/spark/mspark/Shell/MarketModule.cs +++ b/src/client/spark/mspark/Shell/MarketModule.cs @@ -21,20 +21,21 @@ using SecurityKey = System.UInt32; namespace mbts.spark { [Export(typeof(IShellModule))] - internal class MarketModule : IShellModule - { + internal class MarketModule : IShellModule { [ImportingConstructor] public MarketModule(IBus bus, IWindowManager wm) { _bus = bus; _wm = wm; _dispose = Disposable.Create( - _bus.subscribe>(SecuritiesTag).ObserveOnDispatcher().Subscribe(s => _securities = s), + _bus.subscribe>(SecuritiesTag).ObserveOnDispatcher().Subscribe(s => _securities = s), _bus.subscribe(SyntheticSecuritiesTag).ObserveOnDispatcher().Subscribe(ssm => _synthetic_strategy_map = ssm.data), _bus.subscribe(ShowMarketViewTag).ObserveOnDispatcher().Subscribe(show_market_view), _bus.subscribe(ShowSpreadMatrixTag).ObserveOnDispatcher().Subscribe(show_spread_matrix), _bus.subscribe(ShowLadderTag).ObserveOnDispatcher().Subscribe(show_ladder), - _bus.subscribe(ShowOrderTicketTag).ObserveOnDispatcher().Subscribe(msg => show_order_ticket(msg.data, false)), - _bus.subscribe(ShowOrderModifyTag).ObserveOnDispatcher().Subscribe(msg => show_order_ticket(msg.data, true)), + _bus.subscribe(ShowLadderTag).ObserveOnDispatcher().Subscribe(show_linked_ladder), + _bus.subscribe(ShowOrderModifyTag).ObserveOnDispatcher().Subscribe(show_order_modify), + _bus.subscribe(ShowOrderTicketTag).ObserveOnDispatcher().Subscribe(show_order_ticket), + _bus.subscribe(ShowOrderTicketTag).ObserveOnDispatcher().Subscribe(show_linked_order_ticket), _bus.subscribe(ShowSyntheticCreateTag).ObserveOnDispatcher().Subscribe(show_synthetic_create_editor), _bus.subscribe(ShowSyntheticStrategyTag).ObserveOnDispatcher().Subscribe(show_synthetic_strategy_editor) ); @@ -43,12 +44,19 @@ namespace mbts.spark private readonly IWindowManager _wm; private readonly IDisposable _dispose; private IDictionary _securities = new Dictionary(); - private IDictionary _synthetic_strategy_map = new Dictionary(); + private IDictionary _synthetic_strategy_map = new Dictionary(); public int priority => 2; public string name => "Market"; public ImageSource icon => Icons.Date; - public IShellWindow launch_ui => new LaunchMenu { DataContext = new LaunchMenuVM(new MarketViewMenuItem(_bus), new SpreadMatrixMenuItem(_bus), new LadderMenuItem(_bus), new OrderTicketMenuItem(_bus), MenuItemFactory.Create("Security Browser...", "sb", Icons.Coins, execute:show_security_browser)) }; + public IShellWindow launch_ui => new LaunchMenu { + DataContext = new LaunchMenuVM( + new MarketViewMenuItem(_bus), + new SpreadMatrixMenuItem(_bus), + new LadderMenuItem(_bus), + new OrderTicketMenuItem(new OrdersModel(_bus)), + MenuItemFactory.Create("Security Browser...", "sb", Icons.Coins, execute: show_security_browser)) + }; public void load_state(Stream state = null) { } public void get_state(Stream save_here) { } public async Task create(Stream load_stream) { @@ -59,7 +67,9 @@ namespace mbts.spark await Wait.until_true(() => _securities != null && _securities.ContainsKey(key), TimeSpan.FromSeconds(15)); if (_securities != null && _securities.TryGetValue((uint)header.version, out SecurityMD md)) return create_ladder_window(md); else break; - case MarketViewVM.SAVE_NAME: if (try_deserialize(load_stream, out MarketViewVM.StartupData data)) return new MarketViewWindow(this, _bus, data); break; + case MarketViewVM.SAVE_NAME: + if (try_deserialize(load_stream, out MarketViewVM.StartupData data)) return create_market_view(data.securities.Select(deserialize).ToList(), data.sorting_criteria); + else break; } } return null; @@ -67,28 +77,75 @@ namespace mbts.spark public void start() { } public void Dispose() { _dispose.Dispose(); } + #region SecurityBrowser private void show_security_browser() { new SecurityBrowser { DataContext = new SecurityBrowserVM(_bus) }.Show(-200, -300, true); } - private void show_market_view(ShowMarketViewMessage msg) { _wm.Windows.Add(new MarketViewWindow(this, _bus, msg.data)); } + #endregion + + #region MarketView + private void show_market_view(ShowMarketViewMessage msg) { _wm.Windows.Add(create_market_view(msg.data, null)); } + private IShellWindow create_market_view(IReadOnlyCollection securities, IReadOnlyCollection sorting) { + var vm = new MarketViewVM(_bus, securities, sorting); + var view = new MarketViewView { DataContext = vm }; + const double two_thirds = 2.0 / 3.0; + const double title_panel_height = 32.0, col_header_height = 26 + two_thirds + 10.0; + double row_height = vm.row_height + two_thirds; + view.Height = Math.Min(title_panel_height + col_header_height + securities.Count * row_height, System.Windows.SystemParameters.WorkArea.Height); + view.Width = 720; + return ShellWindow.create(this, "Market View", view, stream => { + serialize(stream, new ShellSerializationHeader { name = MarketViewVM.SAVE_NAME, version = MarketViewVM.VERSION }); + serialize(stream, vm.get_startup_data()); + }, Icons.Sheets); + } + #endregion + + #region SpreadMatrix private void show_spread_matrix(ShowSpreadMatrixMessage msg) { } - private void show_order_ticket(Order order, bool is_modify) { - if (_securities.TryGetValue(order.Security.Id, out SecurityMD smd)) { - if (string.IsNullOrEmpty(order.User)) order.User = UserConfigurationHelper.UserName; - var vm = new OrderTicketVM(order, new OrdersModel(_bus), smd, _get_ladder_settings()); - (is_modify ? (Window)new OrderModificationDialog { DataContext = vm } : new OrderTicket { DataContext = vm }).Show(-200, -160, true); + #endregion + + #region OrderTicket + private void show_order_modify(ShowOrderModifyMessage msg) { show_order_ticket(msg.data, true); } + private void show_order_ticket(ShowOrderTicketMessage msg) { show_order_ticket(msg.data, false); } + private void show_order_ticket(IReadOnlyCollection orders, bool is_modify) { + foreach (var o in orders) { + if (_securities.TryGetValue(o.Security.Id, out SecurityMD smd)) { + if (string.IsNullOrEmpty(o.User)) o.User = ImportedResources.UserName; + var vm = new OrderTicketVM(new OrdersModel(_bus), o, _get_ladder_settings()); + (is_modify ? (Window)new OrderModificationDialog { DataContext = vm } : new OrderTicket { DataContext = vm }).Show(-200, -160, true); + } } } + private void show_linked_order_ticket(ShowLinkedOrderTicketMessage msg) { + new OrderTicket { + DataContext = new OrderTicketVM(new OrdersModel(_bus), msg.data, _get_ladder_settings()) + }.Show(-200, -160, true); + } + #endregion #region Ladder - private void show_ladder(ShowLadderMessage msg) { foreach (var s in msg.data) show_ladder(s); } + private void show_ladder(ShowLadderMessage msg) { foreach (var s in msg.data) if (_securities.TryGetValue(s.Id, out SecurityMD smd)) show_ladder(smd); } private void show_ladder(SecurityMD sec) { _wm.Windows.Add(create_ladder_window(sec)); } + private async void show_linked_ladder(ShowLinkedLadderMessage msg) { _wm.Windows.Add(await create_ladder_window(msg.data)); } private IShellWindow create_ladder_window(SecurityMD md) { var model = new LadderModel(md, new OrdersModel(_bus)); var vm = new LadderVM(model, _get_ladder_settings()); - var view = new LadderView(vm); - var window = ShellWindow.create(this, md.security.ToString(), view, vm.save_state, icon: Icons.Logo); - return window; + var view = new LadderView { DataContext = vm }; + return ShellWindow.create(this, md.security.ToString(null), view, vm, vm.save_state, Icons.Depth); } private IObservable _get_ladder_settings() { return Observable.Return(new LadderSettings()); } + private async Task create_ladder_window(IObservable security_md) { + var first_smd = await security_md.FirstAsync(); + OrdersModel om = new OrdersModel(_bus); + LadderVM vm = new LadderVM(new LadderModel(first_smd, om), _get_ladder_settings()); + LadderView view = new LadderView { DataContext = vm }; + IDisposable sub = null; + var sw = ShellWindow.create(this, first_smd.security.ToString(null), view, Disposable.Create(() => { sub?.Dispose(); vm.Dispose(); }), state => vm.save_state(state), Icons.Depth); + sub = security_md.ObserveOnDispatcher().Subscribe(smd => { + vm.Dispose(); + view.DataContext = vm = new LadderVM(new LadderModel(smd, om), _get_ladder_settings()); + sw.Title = smd.security.ToString(null); + }); + return sw; + } #endregion #region Synthentic diff --git a/src/client/spark/mspark/Shell/MenuItems/AuditLogMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/AuditLogMenuItem.cs index c759780c8..9b2355283 100644 --- a/src/client/spark/mspark/Shell/MenuItems/AuditLogMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/AuditLogMenuItem.cs @@ -13,13 +13,15 @@ namespace mbts.spark.menu_items private readonly IBus _bus; - public string display_name => "Audit Logs"; + public string display_name => "Audit Logs..."; public int priority => 3; public ImageSource icon => Icons.DataCopy; - public string sectional_id => null; + public string sectional_id => MenuItemSections.OrderPassiveWindow; public void execute() { _bus.post(SparkTags.ShowAuditLogsTag, new SparkBusData.ShowAuditLogsMessage()); } public bool can_execute() { return true; } - public event Action can_execute_changed; + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/CancelOrderRootMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/CancelOrderRootMenuItem.cs new file mode 100644 index 000000000..0e5060e0b --- /dev/null +++ b/src/client/spark/mspark/Shell/MenuItems/CancelOrderRootMenuItem.cs @@ -0,0 +1,29 @@ +using bts.spark; +using mbts.ui; +using System.Collections.Generic; +using System.Windows.Media; + +namespace mbts.spark.menu_items +{ + internal class CancelOrderRootMenuItem : OrderActionMenuItemRoot + { + public CancelOrderRootMenuItem(OrdersModel model, IReadOnlyCollection orders) : base(orders) { + _model = model; + } + private OrdersModel _model; + public override string display_name => "Cancel Order"; + public override ImageSource icon => Icons.CancelOrders; + protected override OrderMenuActionItem create_item(Order order) { return new CancelOrderMenuItem(_model, order); } + + internal class CancelOrderMenuItem : OrderMenuActionItem { + public CancelOrderMenuItem(OrdersModel model, Order order) : base(order, model.get_metadata(order)) { + _model = model; + _order = order; + } + + private readonly OrdersModel _model; + private readonly Order _order; + public override void execute() { _model.cancel_order(_order.Id); } + } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/CancelOrdersMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/CancelOrdersMenuItem.cs index bbf94a5b3..ad1d9911c 100644 --- a/src/client/spark/mspark/Shell/MenuItems/CancelOrdersMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/CancelOrdersMenuItem.cs @@ -4,24 +4,46 @@ using System.Linq; using System.Windows.Media; using mbts.ui; using System; +using bts.spark; namespace mbts.spark.menu_items { internal class CancelOrdersMenuItem : IMenuSecuritiesActionItem { - public CancelOrdersMenuItem(IBus bus) { - _model = new OrdersModel(bus); + public CancelOrdersMenuItem(OrdersModel model) { + _model = model; + _sub = _model.on_orderbook().ObserveOnDispatcher().Subscribe(ob => _orderbook = ob); } - + private readonly IDisposable _sub; private readonly OrdersModel _model; + private IOrderBook _orderbook = new OrderBook(); - public string display_name => "Cancel Orders"; + public virtual string display_name => "Cancel All Orders"; public int priority => 0; public ImageSource icon => Icons.CancelOrders; - public string sectional_id => null; - public void execute(IReadOnlyList securities) { _model.cancel_security_orders(securities.Select(s => s.Id), true, true); } - public bool can_execute(IReadOnlyList securities) { return securities.Any(); } - public event Action can_execute_changed; + public string sectional_id => MenuItemSections.OrderOp; + public void execute(IReadOnlyCollection securities) { + var orders = _orderbook.get_all_orders().Select(e => e.order()).Where(o => securities.Contains(o.Security) && filter(o)).Select(o => o.Id).ToList(); + _model.cancel_order(orders); + } + public bool can_execute(IReadOnlyCollection securities) { return securities.Any(); } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; + protected virtual bool filter(Order order) { return true; } + public void Dispose() { _sub.Dispose(); } + } + + internal class CancelBuyOrdersMenuItem : CancelOrdersMenuItem { + public CancelBuyOrdersMenuItem(OrdersModel model) : base(model) { } + public override string display_name => "Cancel Buy Orders"; + protected override bool filter(Order order) { return order.Side == BuySell.Buy; } + } + + internal class CancelSellOrdersMenuItem : CancelOrdersMenuItem { + public CancelSellOrdersMenuItem(OrdersModel model) : base(model) { } + protected override bool filter(Order order) { return order.Side == BuySell.Sell; } + public override string display_name => "Cancel Sell Orders"; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/FillsMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/FillsMenuItem.cs index abea3f215..97dcef10b 100644 --- a/src/client/spark/mspark/Shell/MenuItems/FillsMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/FillsMenuItem.cs @@ -13,13 +13,15 @@ namespace mbts.spark.menu_items private readonly IBus _bus; - public string display_name => "Fills"; + public string display_name => "Fills..."; public int priority => 1; public ImageSource icon => Icons.Payment; - public string sectional_id => null; + public string sectional_id => MenuItemSections.OrderPassiveWindow; public void execute() { _bus.post(SparkTags.ShowFillsTag, new SparkBusData.ShowFillsMessage()); } public bool can_execute() { return true; } - public event Action can_execute_changed; + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/IMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/IMenuItem.cs index db4862d09..79c785a8e 100644 --- a/src/client/spark/mspark/Shell/MenuItems/IMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/IMenuItem.cs @@ -11,31 +11,40 @@ namespace mbts.spark.menu_items int priority { get; } ImageSource icon { get; } string sectional_id { get; } + event Action display_name_changed; } - public interface IMenuActionItem : IMenuItem + public interface ICanExecuteChanged + { + event Action can_execute_changed; + } + + public interface IMenuActionItem : IMenuItem, ICanExecuteChanged { void execute(); bool can_execute(); - event Action can_execute_changed; } - public interface IMenuSecuritiesActionItem : IMenuItem + public interface IMenuSecuritiesActionItem : IMenuItem, ICanExecuteChanged { - void execute(IReadOnlyList securities); - bool can_execute(IReadOnlyList securities); - event Action can_execute_changed; - } - - public interface IMenuSecurityActionItem : IMenuItem - { - bool can_execute(Security security); - void execute(Security security); - event Action can_execute_changed; + void execute(IReadOnlyCollection securities); + bool can_execute(IReadOnlyCollection securities); } public interface IMenuGroupItem : IMenuItem { IEnumerable items { get; } - } + } + + internal class MenuItemSections + { + public const string Window = nameof(Window), + SecurityWindow = nameof(SecurityWindow), + OrderActiveWindow = nameof(OrderActiveWindow), + OrderPassiveWindow = nameof(OrderPassiveWindow), + OrderOp = nameof(OrderOp), + Action = nameof(Action), + ModifySecuritySelection = nameof(ModifySecuritySelection), + Misc = nameof(Misc); + } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/LadderMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/LadderMenuItem.cs index d58ef9f33..4ad04ec54 100644 --- a/src/client/spark/mspark/Shell/MenuItems/LadderMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/LadderMenuItem.cs @@ -5,28 +5,46 @@ using System.Collections.Generic; using System.Windows.Media; using static mbts.spark.SparkBusData; using static mbts.spark.SparkTags; -using SecurityKey = System.UInt32; namespace mbts.spark.menu_items { - internal class LadderMenuItem : IMenuSecurityActionItem + internal class LadderMenuItem : IMenuSecuritiesActionItem { - public LadderMenuItem(IBus bus, string sectional_id = "rw") { - this.sectional_id = sectional_id; + public LadderMenuItem(IBus bus) { _bus = bus; - _bus.subscribe>(SecuritiesTag).ObserveOnDispatcher().Subscribe(s => { _securities = s; raise_can_execute_changed(); }); } private readonly IBus _bus; - private Dictionary _securities = new Dictionary(); public string display_name => "Ladder"; public int priority => 2; public ImageSource icon => Icons.Depth; - public string sectional_id { get; } - public void execute(Security security) { if (_securities.TryGetValue(security.Id, out SecurityMD md)) _bus.post(ShowLadderTag, new ShowLadderMessage(md)); } - public bool can_execute(Security security) { return security != null && _securities.ContainsKey(security.Id); } - public event Action can_execute_changed; + public string sectional_id => MenuItemSections.OrderActiveWindow; + public void execute(IReadOnlyCollection securities) { _bus.post(ShowLadderTag, new ShowLadderMessage(securities)); } + public bool can_execute(IReadOnlyCollection securities) { return securities.Count > 0; } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; + } + + internal class LinkedLadderMenuItem : IMenuActionItem + { + public LinkedLadderMenuItem(IBus bus, IObservable security_md) { + _bus = bus; + _security_md = security_md; + } + private readonly IBus _bus; + private readonly IObservable _security_md; + public string display_name => "Linked Ladder"; + public int priority => int.MaxValue; + public ImageSource icon => Icons.Depth; + public string sectional_id => MenuItemSections.OrderActiveWindow; + public bool can_execute() { return true; } + public void execute() { _bus.post(ShowLadderTag, new ShowLinkedLadderMessage(_security_md)); } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } + public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/MarketViewMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/MarketViewMenuItem.cs index 940c04de0..616f1a78f 100644 --- a/src/client/spark/mspark/Shell/MenuItems/MarketViewMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/MarketViewMenuItem.cs @@ -18,10 +18,12 @@ namespace mbts.spark.menu_items public string display_name => "Market View"; public int priority => 0; public ImageSource icon => Icons.Sheets; - public string sectional_id => "ro"; - public void execute(IReadOnlyList securities) { _bus.post(SparkTags.ShowMarketViewTag, new SparkBusData.ShowMarketViewMessage(securities.ToList())); } - public bool can_execute(IReadOnlyList securities) { return securities.Any(); } - public event Action can_execute_changed; + public string sectional_id => MenuItemSections.SecurityWindow; + public void execute(IReadOnlyCollection securities) { _bus.post(SparkTags.ShowMarketViewTag, new SparkBusData.ShowMarketViewMessage(securities.ToList())); } + public bool can_execute(IReadOnlyCollection securities) { return securities.Any(); } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/MenuItemFactory.cs b/src/client/spark/mspark/Shell/MenuItems/MenuItemFactory.cs index c18fec36f..716f76571 100644 --- a/src/client/spark/mspark/Shell/MenuItems/MenuItemFactory.cs +++ b/src/client/spark/mspark/Shell/MenuItems/MenuItemFactory.cs @@ -9,7 +9,8 @@ namespace mbts.spark.menu_items return new AnonymousMenuActionItem(display_name, sectional_id, icon, priority, execute, can_execute); } - private class AnonymousMenuActionItem : IMenuActionItem, IDisposable { + private class AnonymousMenuActionItem : IMenuActionItem, IDisposable + { public AnonymousMenuActionItem(string display_name, string sectional_id, ImageSource icon, int priority, Action execute, Func can_execute, IDisposable dispose = null) { this.display_name = display_name; this.sectional_id = sectional_id; @@ -30,9 +31,10 @@ namespace mbts.spark.menu_items public int priority { get; } public void execute() { _execute(); } public bool can_execute() { return _can_execute(); } - public event Action can_execute_changed; + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } - + public event Action can_execute_changed; + public event Action display_name_changed; public void Dispose() { _dispose?.Dispose(); } } } diff --git a/src/client/spark/mspark/Shell/MenuItems/MenuItemVM.cs b/src/client/spark/mspark/Shell/MenuItems/MenuItemVM.cs index 6ce8221e6..0c61523e6 100644 --- a/src/client/spark/mspark/Shell/MenuItems/MenuItemVM.cs +++ b/src/client/spark/mspark/Shell/MenuItems/MenuItemVM.cs @@ -1,5 +1,6 @@ using bts.api; using mbts.ui; +using mbts.ui.shell; using mbts.ui.utility; using System; using System.Collections.Generic; @@ -7,25 +8,37 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Linq; -using System.Windows.Controls; +using System.Reactive.Linq; using System.Windows.Data; using System.Windows.Input; using System.Windows.Media; namespace mbts.spark.menu_items { - public class MenuItemVM : IDisposable + public class MenuItemVM : DisposableViewModelBase { #region Static Factory public static IList CreateMenu(ObservableCollection selected_securities, params IMenuItem[] menu_items) { return menu_items.Select(m => Create(m, selected_securities)).ToList(); } + public static IList CreateMenu(IReadOnlyCollection selected_securities, params IMenuItem[] menu_items) { + return menu_items.Select(m => Create(m, selected_securities)).ToList(); + } + public static MenuItemVM Create(IMenuItem model, ObservableCollection selected_securities) { var act_mi = model as IMenuActionItem; if (act_mi != null) return Create(act_mi); - var sec_mi = model as IMenuSecurityActionItem; - if (sec_mi != null) return Create(sec_mi, selected_securities); + var secs_mi = model as IMenuSecuritiesActionItem; + if (secs_mi != null) return Create(secs_mi, selected_securities); + var grp_mi = model as IMenuGroupItem; + if (grp_mi != null) return Create(grp_mi, selected_securities); + throw new NotImplementedException("LaunchMenuVM cannot create vm for {0} ({1}).".fmt(model?.display_name ?? "unnamed", model?.GetType().ToString() ?? "null")); + } + + public static MenuItemVM Create(IMenuItem model, IReadOnlyCollection selected_securities) { + var act_mi = model as IMenuActionItem; + if (act_mi != null) return Create(act_mi); var secs_mi = model as IMenuSecuritiesActionItem; if (secs_mi != null) return Create(secs_mi, selected_securities); var grp_mi = model as IMenuGroupItem; @@ -34,44 +47,48 @@ namespace mbts.spark.menu_items } public static MenuItemVM Create(IMenuActionItem model) { - return new MenuItemVM(model.display_name, model.sectional_id, model.icon, new DelegateCommand(model.execute, model.can_execute), dispose: model as IDisposable); + return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, _hook_command(model, model.execute, model.can_execute), dispose: model as IDisposable); } - public static MenuItemVM Create(IMenuSecurityActionItem model, Security selected_security) { - return new MenuItemVM(model.display_name, model.sectional_id, model.icon, new DelegateCommand(() => model.execute(selected_security), () => model.can_execute(selected_security)), dispose: model as IDisposable); - } - - public static MenuItemVM Create(IMenuSecurityActionItem model, IReadOnlyList selected_securities) { - return new MenuItemVM(model.display_name, model.sectional_id, model.icon, new DelegateCommand(() => model.execute(selected_securities.SingleOrDefault()), () => selected_securities.Count == 1 && model.can_execute(selected_securities[0])), dispose: model as IDisposable); - } - - public static MenuItemVM Create(IMenuSecurityActionItem model, ObservableCollection selected_securities) { - var command = new DelegateCommand(() => model.execute(selected_securities.SingleOrDefault()), () => selected_securities.Count == 1 && model.can_execute(selected_securities[0])); - IDisposable sub = selected_securities.Subscribe((s, e) => command.RaiseCanExecuteChanged()); - return new MenuItemVM(model.display_name, model.sectional_id, model.icon, command, dispose: Disposable.Create(() => { (model as IDisposable)?.Dispose(); sub?.Dispose(); })); - } - - public static MenuItemVM Create(IMenuSecuritiesActionItem model, IReadOnlyList selected_securities) { - return new MenuItemVM(model.display_name, model.sectional_id, model.icon, new DelegateCommand(() => model.execute(selected_securities), () => model.can_execute(selected_securities))); + public static MenuItemVM Create(IMenuSecuritiesActionItem model, IReadOnlyCollection selected_securities) { + return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, _hook_command(model, () => model.execute(selected_securities), () => model.can_execute(selected_securities))); } public static MenuItemVM Create(IMenuSecuritiesActionItem model, ObservableCollection selected_securities) { - var command = new DelegateCommand(() => model.execute(selected_securities), () => model.can_execute(selected_securities)); + var command = _hook_command(model, () => model.execute(selected_securities), () => model.can_execute(selected_securities)); IDisposable sub = selected_securities.Subscribe((s, e) => command.RaiseCanExecuteChanged()); - return new MenuItemVM(model.display_name, model.sectional_id, model.icon, command, dispose: Disposable.Create(() => { (model as IDisposable)?.Dispose(); sub?.Dispose(); })); + return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, command, dispose: Disposable.Create(() => { (model as IDisposable)?.Dispose(); sub?.Dispose(); })); } public static MenuItemVM Create(IMenuGroupItem model, ObservableCollection selected_securities) { - return new MenuItemVM(model.display_name, model.sectional_id, model.icon, new DelegateCommand(() => { }, () => model.items.Any()), CreateMenu(selected_securities, model.items.ToArray())); + return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, new DelegateCommand(() => { }, () => model.items.Any()), CreateMenu(selected_securities, model.items.ToArray())); + } + + public static MenuItemVM Create(IMenuGroupItem model, IReadOnlyCollection selected_securities) { + return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, new DelegateCommand(() => { }, () => model.items.Any()), CreateMenu(selected_securities, model.items.ToArray())); + } + + public static MenuItemVM Create(IObservable display_name, string sectional_id = null, ImageSource icon = null, ICommand command = null, IEnumerable items = null) { + return new MenuItemVM(display_name, sectional_id, icon, command, items); } public static MenuItemVM Create(string display_name, string sectional_id=null, ImageSource icon=null, ICommand command=null, IEnumerable items = null) { - return new MenuItemVM(display_name, sectional_id, icon, command, items); + return new MenuItemVM(Observable.Return(display_name), sectional_id, icon, command, items); + } + + private static IRaiseCanExecuteChangedCommand _hook_command(ICanExecuteChanged model, Action execute, Func can_execute=null) { + var command = new DelegateCommand(execute, can_execute); + model.can_execute_changed += command.RaiseCanExecuteChanged; + return command; + } + + private static IObservable _observe_display_name(IMenuItem model) { + return Observable.FromEvent(cb => model.display_name_changed += cb, cb => model.display_name_changed -= cb).Select(_ => model.display_name).StartWith(model.display_name); } #endregion - - protected MenuItemVM(string display_name, string sectional_id=null, ImageSource icon=null, ICommand command=null, IEnumerable items=null, IDisposable dispose=null) { - this.display_name = display_name; + + protected MenuItemVM(IObservable display_name, string sectional_id=null, ImageSource icon=null, ICommand command=null, IEnumerable items=null, IDisposable dispose=null) { + _display_name = backing(nameof(display_name), display_name, null); this.sectional_id = sectional_id; this.icon = icon; this.command = command ?? Commands.Empty; @@ -81,20 +98,15 @@ namespace mbts.spark.menu_items _dispose = dispose; } - private IDisposable _dispose; private IList _items; + private readonly Property _display_name; - public string display_name { get; } + public string display_name { get => _display_name.Value; set => _display_name.set(value); } public string sectional_id { get; } public ImageSource icon { get; } public ICommand command { get; } public ICollectionView items_view { get; } - protected virtual void Dispose(bool disposing) { } - public void Dispose() { - Dispose(true); - Disposable.dispose(ref _dispose); - Disposable.dispose(_items); - } + protected override void Dispose(bool disposing) { Disposable.dispose(_items); } } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/ModifyOrderRootMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/ModifyOrderRootMenuItem.cs new file mode 100644 index 000000000..45e80636c --- /dev/null +++ b/src/client/spark/mspark/Shell/MenuItems/ModifyOrderRootMenuItem.cs @@ -0,0 +1,33 @@ +using bts.spark; +using mbts.ui; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using System.Windows.Media; + +namespace mbts.spark.menu_items +{ + internal class ModifyOrderRootMenuItem : OrderActionMenuItemRoot + { + public ModifyOrderRootMenuItem(OrdersModel model, IReadOnlyCollection orders) : base(orders) { + _model = model; + } + private OrdersModel _model; + public override string display_name => "Modify Order"; + public override ImageSource icon => Icons.Import; + protected override OrderMenuActionItem create_item(Order order) { return new ModifyOrderMenuItem(_model, order); } + + internal class ModifyOrderMenuItem : OrderMenuActionItem { + public ModifyOrderMenuItem(OrdersModel model, Order order) : base(order, model.get_metadata(order)) { + _model = model; + _order = order; + } + + private readonly OrdersModel _model; + private readonly Order _order; + public override void execute() { _model.show_order_modify(_order); } + } + } +} diff --git a/src/client/spark/mspark/Shell/MenuItems/ModifySecuritySelectionMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/ModifySecuritySelectionMenuItem.cs new file mode 100644 index 000000000..43e97e1c4 --- /dev/null +++ b/src/client/spark/mspark/Shell/MenuItems/ModifySecuritySelectionMenuItem.cs @@ -0,0 +1,35 @@ +using bts.api; +using mbts.ui; +using mbts.ui.spark; +using System; +using System.Collections.Generic; +using System.Windows.Media; + +namespace mbts.spark.menu_items +{ + internal class ModifySecuritySelectionMenuItem : IMenuActionItem + { + public ModifySecuritySelectionMenuItem(IReadOnlyCollection securities, Action> commit, string dialog_title="Select Securities") { + _securities = securities; + _commit = commit; + _dialog_title = dialog_title; + } + private readonly string _dialog_title; + private readonly IReadOnlyCollection _securities; + private readonly Action> _commit; + public string display_name => "Add/Remove Securities"; + public int priority => int.MinValue; + public ImageSource icon => Icons.Coins; + public string sectional_id => MenuItemSections.ModifySecuritySelection; + public bool can_execute() { return true; } + private IDisposable _dialog; + public void execute() { + Disposable.dispose(ref _dialog); + _dialog = new SecuritySelectorDialog { DataContext = new SecuritySelectorDialogVM(_dialog_title, _securities, _commit) }.Show(-12, -30, true); + } + public event Action display_name_changed; + public event Action can_execute_changed; + public void raise_display_name_changed() { display_name_changed?.Invoke(); } + public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/OrderBookMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/OrderBookMenuItem.cs index b49efef6f..d674e3a6c 100644 --- a/src/client/spark/mspark/Shell/MenuItems/OrderBookMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/OrderBookMenuItem.cs @@ -5,6 +5,7 @@ using System.Windows.Media; using static mbts.spark.SparkBusData; using static mbts.spark.SparkTags; using static mbts.spark.menu_items.MenuItemFactory; +using System; namespace mbts.spark.menu_items { @@ -12,16 +13,18 @@ namespace mbts.spark.menu_items { public OrderBookMenuItem(IBus bus) { items = new [] { - Create("All Orders...", execute:() => bus.post(ShowOrderBookTag, new ShowOrderBookMessage())), - Create("Active Orders...", execute:() => bus.post(ShowOrderBookTag, new ShowOrderBookMessage())), - Create("Spreader Orders...", execute:() => bus.post(ShowOrderBookTag, new ShowOrderBookMessage())) + Create("All Orders...", "a", Icons.Book, execute:() => bus.post(ShowOrderBookTag, new ShowOrderBookMessage())), + Create("Active Orders...", "b", Icons.Book, execute:() => bus.post(ShowOrderBookTag, new ShowOrderBookMessage())), + Create("Spreader Orders...", "b", Icons.Book, execute:() => bus.post(ShowOrderBookTag, new ShowOrderBookMessage())) }; } public string display_name => "Order Book"; public int priority => 0; - public ImageSource icon => Icons.Orders; - public string sectional_id => null; + public ImageSource icon => Icons.Book; + public string sectional_id => MenuItemSections.OrderPassiveWindow; public IEnumerable items { get; } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } + public event Action display_name_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/OrderMenuActionItemRoot.cs b/src/client/spark/mspark/Shell/MenuItems/OrderMenuActionItemRoot.cs new file mode 100644 index 000000000..2d033872a --- /dev/null +++ b/src/client/spark/mspark/Shell/MenuItems/OrderMenuActionItemRoot.cs @@ -0,0 +1,48 @@ +using bts.spark; +using mbts.ui; +using mbts.ui.spark; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Windows.Media; + +namespace mbts.spark.menu_items +{ + internal abstract class OrderActionMenuItemRoot : IMenuGroupItem + { + public OrderActionMenuItemRoot(IReadOnlyCollection orders) { + _orders = orders; + _items = new Lazy>(() => _orders.Select(create_item).ToList()); + } + private readonly IReadOnlyCollection _orders; + private readonly Lazy> _items; + public abstract string display_name { get; } + public abstract ImageSource icon { get; } + public int priority => int.MaxValue; + public string sectional_id => MenuItemSections.OrderOp; + public IEnumerable items => _items.Value; + public event Action display_name_changed; + public void raise_display_name_changed() { display_name_changed?.Invoke(); } + protected abstract OrderMenuActionItem create_item(Order order); + } + + internal abstract class OrderMenuActionItem : IMenuActionItem + { + public OrderMenuActionItem(Order order, OrderMetadata metadata) { + _order = order; + _metadata = metadata; + } + private readonly Order _order; + private readonly OrderMetadata _metadata; + public string display_name => _order.summary(); + public int priority => int.MaxValue; + public ImageSource icon => OrderIconFactory.Create(_metadata, _order.Side); + public string sectional_id => MenuItemSections.OrderOp; + public abstract void execute(); + public bool can_execute() { return true; } + public event Action display_name_changed; + public event Action can_execute_changed; + public void raise_display_name_changed() { display_name_changed?.Invoke(); } + public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/OrderTicketMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/OrderTicketMenuItem.cs index b26c32534..a4bc181bd 100644 --- a/src/client/spark/mspark/Shell/MenuItems/OrderTicketMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/OrderTicketMenuItem.cs @@ -3,31 +3,56 @@ using bts.spark; using mbts.ui; using System; using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; using System.Windows.Media; using static mbts.spark.SparkBusData; using static mbts.spark.SparkTags; -using SecurityKey = System.UInt32; namespace mbts.spark.menu_items { - internal class OrderTicketMenuItem : IMenuSecurityActionItem + internal class OrderTicketMenuItem : IMenuSecuritiesActionItem { - public OrderTicketMenuItem(IBus bus, string sectional_id = "rw") { - this.sectional_id = sectional_id; - _bus = bus; - _bus.subscribe>(SecuritiesTag).ObserveOnDispatcher().Subscribe(s => _securities = s); + public OrderTicketMenuItem(OrdersModel model, Func order_factory=null) { + _model = model; + _order_factory = order_factory ?? new Func(s => new Order { Security = s, LimitOrder = new LimitOrder(), Size = 1 }); } - private readonly IBus _bus; - private Dictionary _securities = new Dictionary(); - + private readonly OrdersModel _model; + private readonly Func _order_factory; + public string display_name => "Order Ticket"; public int priority => 3; public ImageSource icon => Icons.Ticket; - public string sectional_id { get; } - public void execute(Security security) { _bus.post(ShowOrderTicketTag, new ShowOrderTicketMessage(new Order { Security = security, LimitOrder = new LimitOrder() })); } - public bool can_execute(Security security) { return security != null; } - public event Action can_execute_changed; + public string sectional_id => MenuItemSections.OrderActiveWindow; + public void execute(IReadOnlyCollection securities) { _model.show_order_ticket(securities.Select(_order_factory).ToList()); } + public bool can_execute(IReadOnlyCollection securities) { return securities.Count > 0; } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; + } + + internal class LinkedOrderTicketMenuItem : IMenuActionItem + { + public LinkedOrderTicketMenuItem(IBus bus, IObservable security, Func order_factory) : this(bus, security.Select(order_factory).Where(o => o != null)) { } + public LinkedOrderTicketMenuItem(IBus bus, IObservable order) { + _bus = bus; + _order = order; + } + + private readonly IBus _bus; + private readonly IObservable _order; + + public string display_name => "Linked Order Ticket"; + public int priority => int.MaxValue; + public ImageSource icon => Icons.Ticket; + public string sectional_id => MenuItemSections.OrderActiveWindow; + public bool can_execute() { return true; } + public void execute() { _bus.post(ShowOrderTicketTag, new ShowLinkedOrderTicketMessage(_order)); } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } + public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/PositionsMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/PositionsMenuItem.cs index 1123291ee..f8d0259b6 100644 --- a/src/client/spark/mspark/Shell/MenuItems/PositionsMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/PositionsMenuItem.cs @@ -6,10 +6,8 @@ using System.Windows.Media; namespace mbts.spark.menu_items { - [Export(nameof(TradesModule), typeof(IMenuItem))] internal class PositionsMenuItem : IMenuActionItem { - [ImportingConstructor] public PositionsMenuItem(IBus bus) { _bus = bus; } @@ -19,10 +17,12 @@ namespace mbts.spark.menu_items public string display_name => "Positions/PnL..."; public int priority => 3; public ImageSource icon => Icons.Accounting; - public string sectional_id => nameof(PositionsMenuItem); + public string sectional_id => MenuItemSections.Window; public void execute() { _bus.post(SparkTags.ShowPositionsTag, new SparkBusData.ShowPositionsMessage()); } public bool can_execute() { return true; } - public event Action can_execute_changed; + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/SpreadMatrixMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/SpreadMatrixMenuItem.cs index 4a16755b3..d16a43673 100644 --- a/src/client/spark/mspark/Shell/MenuItems/SpreadMatrixMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/SpreadMatrixMenuItem.cs @@ -9,8 +9,7 @@ namespace mbts.spark.menu_items { internal class SpreadMatrixMenuItem : IMenuSecuritiesActionItem { - public SpreadMatrixMenuItem(IBus bus, string sectional_id = "rw") { - this.sectional_id = sectional_id; + public SpreadMatrixMenuItem(IBus bus) { _bus = bus; } @@ -19,10 +18,12 @@ namespace mbts.spark.menu_items public string display_name => "Spread Matrix"; public int priority => 1; public ImageSource icon => Icons.Cube3d; - public string sectional_id { get; } - public void execute(IReadOnlyList securities) { _bus.post(SparkTags.ShowSpreadMatrixTag, new SparkBusData.ShowSpreadMatrixMessage(securities.ToList())); } - public bool can_execute(IReadOnlyList securities) { return securities.Any(); } - public event Action can_execute_changed; + public string sectional_id => MenuItemSections.SecurityWindow; + public void execute(IReadOnlyCollection securities) { _bus.post(SparkTags.ShowSpreadMatrixTag, new SparkBusData.ShowSpreadMatrixMessage(securities.ToList())); } + public bool can_execute(IReadOnlyCollection securities) { return securities.Any(); } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/SyntheticCreateMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/SyntheticCreateMenuItem.cs index 75d0f1282..68708f493 100644 --- a/src/client/spark/mspark/Shell/MenuItems/SyntheticCreateMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/SyntheticCreateMenuItem.cs @@ -2,7 +2,6 @@ using mbts.ui; using System; using System.Collections.Generic; -using System.ComponentModel.Composition; using System.Linq; using System.Windows.Media; using static bts.api.Security; @@ -13,22 +12,23 @@ namespace mbts.spark.menu_items { internal class SyntheticCreateMenuItem : IMenuSecuritiesActionItem { - [ImportingConstructor] public SyntheticCreateMenuItem(IBus bus) { _bus = bus; } private readonly IBus _bus; - public string display_name => "Create Synthetic"; + public string display_name => "Create Synthetic..."; public int priority => 2; - public ImageSource icon => Icons.Cube3d; - public string sectional_id => null; - public void execute(IReadOnlyList securities) { _bus.post(ShowSyntheticCreateTag, new ShowSyntheticCreateMessage(securities)); } - public bool can_execute(IReadOnlyList securities) { + public ImageSource icon => Icons.Tetris; + public string sectional_id => MenuItemSections.SecurityWindow; + public void execute(IReadOnlyCollection securities) { _bus.post(ShowSyntheticCreateTag, new ShowSyntheticCreateMessage(securities)); } + public bool can_execute(IReadOnlyCollection securities) { return securities.Count > 1 || (securities.Count == 1 && (securities.First().ContractCase == ContractOneofCase.Synthetic || securities.First().ContractCase == ContractOneofCase.Spread)); } - public event Action can_execute_changed; + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/SyntheticStrategyMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/SyntheticStrategyMenuItem.cs index 686d96e5b..3dc941cd8 100644 --- a/src/client/spark/mspark/Shell/MenuItems/SyntheticStrategyMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/SyntheticStrategyMenuItem.cs @@ -19,11 +19,13 @@ namespace mbts.spark.menu_items public string display_name => "Execution Strategy..."; public int priority => 1; - public ImageSource icon => Icons.Target; - public string sectional_id => null; - public void execute(IReadOnlyList securities) { _bus.post(ShowSyntheticStrategyTag, new ShowSyntheticStrategyMessage(securities.First())); } - public bool can_execute(IReadOnlyList securities) { return securities.Count == 1 && securities.First().ContractCase == Security.ContractOneofCase.Synthetic; } - public event Action can_execute_changed; + public ImageSource icon => Icons.Knight; + public string sectional_id => MenuItemSections.SecurityWindow; + public void execute(IReadOnlyCollection securities) { _bus.post(ShowSyntheticStrategyTag, new ShowSyntheticStrategyMessage(securities.First())); } + public bool can_execute(IReadOnlyCollection securities) { return securities.Count == 1 && securities.First().ContractCase == Security.ContractOneofCase.Synthetic; } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/MenuItems/TimeAndSalesMenuItem.cs b/src/client/spark/mspark/Shell/MenuItems/TimeAndSalesMenuItem.cs index c399c213d..c19acea3f 100644 --- a/src/client/spark/mspark/Shell/MenuItems/TimeAndSalesMenuItem.cs +++ b/src/client/spark/mspark/Shell/MenuItems/TimeAndSalesMenuItem.cs @@ -2,16 +2,13 @@ using mbts.ui; using System; using System.Collections.Generic; -using System.ComponentModel.Composition; using System.Linq; using System.Windows.Media; namespace mbts.spark.menu_items { - [Export(nameof(TradesModule), typeof(IMenuItem))] public class TimeAndSalesMenuItem : IMenuSecuritiesActionItem { - [ImportingConstructor] public TimeAndSalesMenuItem(IBus bus) { _bus = bus; } @@ -21,10 +18,12 @@ namespace mbts.spark.menu_items public string display_name => "Time And Sales"; public int priority => 4; public ImageSource icon => Icons.Clock; - public string sectional_id => nameof(TimeAndSalesMenuItem); - public void execute(IReadOnlyList ordered_selection) { _bus.post(SparkTags.ShowTimeAndSalesTag, new SparkBusData.ShowTimeAndSalesMessage(ordered_selection.ToList())); } - public bool can_execute(IReadOnlyList ordered_selection) { return ordered_selection.Any(); } - public event Action can_execute_changed; + public string sectional_id => MenuItemSections.SecurityWindow; + public void execute(IReadOnlyCollection ordered_selection) { _bus.post(SparkTags.ShowTimeAndSalesTag, new SparkBusData.ShowTimeAndSalesMessage(ordered_selection.ToList())); } + public bool can_execute(IReadOnlyCollection ordered_selection) { return ordered_selection.Any(); } + public void raise_display_name_changed() { display_name_changed?.Invoke(); } public void raise_can_execute_changed() { can_execute_changed?.Invoke(); } + public event Action display_name_changed; + public event Action can_execute_changed; } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/OrderBook/OrderBookRowVM.cs b/src/client/spark/mspark/Shell/OrderBook/OrderBookRowVM.cs index 78c08a48e..6fdb85d54 100644 --- a/src/client/spark/mspark/Shell/OrderBook/OrderBookRowVM.cs +++ b/src/client/spark/mspark/Shell/OrderBook/OrderBookRowVM.cs @@ -1,12 +1,13 @@ -using bts.spark; +using bts.api; +using bts.spark; +using mbts.ui; using mbts.ui.shell; using System; -using System.Windows.Input; using System.Linq; -using bts.api; -using mbts.ui; +using System.Windows.Input; -namespace mbts.spark { +namespace mbts.spark +{ class OrderBookRowVM : ViewModelBase { readonly OrderBookVM _parent; readonly OrdersModel _model; @@ -35,6 +36,7 @@ namespace mbts.spark { // need actual security prop for sorting public Security security => _order.order().Security; + public OrderBookEntry order => _order; public string security_text { // indent child 3 spaces get => (is_child ? " " : "") + _order.order().Security.ToString(""); @@ -68,7 +70,7 @@ namespace mbts.spark { set => ignore(); } public string exchange { - get => bts.security_model.Exchange.type.GLBX.ToString(); + get => string.Empty; set => ignore(); } public Order.AlgoOrderTypeOneofCase algo_type { @@ -135,6 +137,7 @@ namespace mbts.spark { get => _order.ChildOrders.Count; set => ignore(); } + public bool is_selected { get; set; } public ContractSpecification contract_spec => _order.order().Security.ContractSpec; diff --git a/src/client/spark/mspark/Shell/OrderBook/OrderBookVM.cs b/src/client/spark/mspark/Shell/OrderBook/OrderBookVM.cs index f840dafad..c4e902150 100644 --- a/src/client/spark/mspark/Shell/OrderBook/OrderBookVM.cs +++ b/src/client/spark/mspark/Shell/OrderBook/OrderBookVM.cs @@ -1,4 +1,7 @@ -using bts.spark; +using bts.api; +using bts.spark; +using mbts.spark.menu_items; +using mbts.spark.utilities; using mbts.ui; using mbts.ui.shell; using mbts.ui.utility; @@ -16,7 +19,8 @@ namespace mbts.spark { public const string SAVE_NAME = "SparkOrderBookWindow"; readonly OrdersModel _model; - public OrderBookVM(OrdersModel model, OrderBookState state, IObservable settings) { + public OrderBookVM(IBus bus, OrdersModel model, OrderBookState state, IObservable settings) { + _bus = bus; _model = model; _order_books = new ObservableCollection(); @@ -39,6 +43,7 @@ namespace mbts.spark { _enable_calculator = backing(nameof(enable_calculator), false); _calculator_price = backing(nameof(calculator_price), double.NaN); + _dispose = _context_menu = new ContextMenuVM(_context_menu_item_factory); } public void get_state(System.IO.Stream output) { @@ -50,6 +55,7 @@ namespace mbts.spark { ProtoBuf.Serializer.SerializeWithLengthPrefix(output, new OrderBookState(), ProtoBuf.PrefixStyle.Fixed32); } + private readonly IBus _bus; ObservableCollection _order_books; OrderIDComparer _order_cmp = new OrderIDComparer(); void orders_updated(IOrderBook order_book) { @@ -71,6 +77,23 @@ namespace mbts.spark { OrderBookRowVM wrap(OrderBookEntry entry) => new OrderBookRowVM(this, _model, entry); + private IEnumerable _context_menu_item_factory() { + var selected_rows = this.orders.Where(vm => vm.is_selected && vm.is_visible).ToList(); + var orders = selected_rows.Select(vm => vm.order).ToList(); + var securities = new HashSet(selected_rows.Select(vm => vm.security)); + yield return MenuItemVM.Create(new LadderMenuItem(_bus), securities); + yield return MenuItemVM.Create(new OrderTicketMenuItem(_model), securities); + yield return MenuItemVM.Create(new MarketViewMenuItem(_bus), securities); + yield return MenuItemVM.Create(new SpreadMatrixMenuItem(_bus), securities); + yield return MenuItemVM.Create(new SyntheticCreateMenuItem(_bus), securities); + yield return MenuItemVM.Create(new SyntheticStrategyMenuItem(_bus), securities); + yield return MenuItemVM.Create(new ModifyOrderRootMenuItem(_model, selected_rows.Select(vm => vm.order.order()).ToList()), securities); + yield return MenuItemVM.Create(new CancelOrderRootMenuItem(_model, selected_rows.Where(vm => vm.order.status() != OrderStatus.Types.Status.Canceled).Select(vm => vm.order.order()).ToList()), securities); + yield return MenuItemVM.Create(new CancelBuyOrdersMenuItem(_model), securities); + yield return MenuItemVM.Create(new CancelSellOrdersMenuItem(_model), securities); + yield return MenuItemVM.Create(new CancelOrdersMenuItem(_model), securities); + } + private ICommand top_bar_command(Action> call) { return new DelegateCommand>(items => { call(items.Select(i => ((OrderBookRowVM)i).order_id).ToList()); @@ -130,10 +153,13 @@ namespace mbts.spark { #endregion + private ContextMenuVM _context_menu; + public ContextMenuVM context_menu => _context_menu; public ObservableCollection orders { get; } // Bind column visibility Property _settings; public OrderBookSettings settings => _settings.Value; + public double row_height { get; set; } = 18; } diff --git a/src/client/spark/mspark/Shell/OrderBook/OrderBookView.xaml b/src/client/spark/mspark/Shell/OrderBook/OrderBookView.xaml index ca7347d74..32f358b7a 100644 --- a/src/client/spark/mspark/Shell/OrderBook/OrderBookView.xaml +++ b/src/client/spark/mspark/Shell/OrderBook/OrderBookView.xaml @@ -1,261 +1,275 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - fills - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + fills + + + + + + + + + + diff --git a/src/client/spark/mspark/Shell/Securities/Synthetic/ExecutionStrategyEditor.xaml b/src/client/spark/mspark/Shell/Securities/Synthetic/ExecutionStrategyEditor.xaml index 37051375d..3f0e2b9f3 100644 --- a/src/client/spark/mspark/Shell/Securities/Synthetic/ExecutionStrategyEditor.xaml +++ b/src/client/spark/mspark/Shell/Securities/Synthetic/ExecutionStrategyEditor.xaml @@ -1,156 +1,156 @@ - - - 8.0 - 4.0 - - - - - - - - - - - - - - - - - - - - - - - - - - - - Hedge Ratio - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Ticks - - Size - - Ratio - - - - - - - - - - - - - - - - - - - - - Ticks - - Size - - Ratio - - - - - - - - - - - - - - - - - - - Size - - Ratio - - - - - - - + + + 8.0 + 4.0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + Hedge Ratio + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Ticks + + Size + + Ratio + + + + + + + + + + + + + + + + + + + + + Ticks + + Size + + Ratio + + + + + + + + + + + + + + + + + + + Size + + Ratio + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/Securities/Synthetic/SyntheticEditor.xaml b/src/client/spark/mspark/Shell/Securities/Synthetic/SyntheticEditor.xaml index 836dff4c5..62d23010b 100644 --- a/src/client/spark/mspark/Shell/Securities/Synthetic/SyntheticEditor.xaml +++ b/src/client/spark/mspark/Shell/Securities/Synthetic/SyntheticEditor.xaml @@ -1,212 +1,212 @@ - - - 8.0 - 4.0 - - - None - - - - - - - - - - - - - - - - - - - - - - - - - Name - - Tick - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + 8.0 + 4.0 + + + None + + + + + + + + + + + + + + + + + + + + + + + + + Name + + Tick + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/Securities/Synthetic/SyntheticEditorVM.cs b/src/client/spark/mspark/Shell/Securities/Synthetic/SyntheticEditorVM.cs index 7727124b0..36136bd13 100644 --- a/src/client/spark/mspark/Shell/Securities/Synthetic/SyntheticEditorVM.cs +++ b/src/client/spark/mspark/Shell/Securities/Synthetic/SyntheticEditorVM.cs @@ -63,7 +63,7 @@ namespace mbts.spark #region Defaults/Sanitization private static QuoteParams _default_quote_params() { - var rv = new QuoteParams { HedgeRatio = 1.0, IsWorking = true, PessimisticHedgePricing = true }; + var rv = new QuoteParams { LeanQuantityRatio = 1.0, IsWorking = true, PessimisticHedgePricing = true }; _sanitize_quote_params(rv); return rv; } @@ -77,7 +77,7 @@ namespace mbts.spark _sanitize_hedge_params(selp.HedgeParams); } private static void _sanitize_quote_params(QuoteParams quote_parms) { - if (quote_parms == null) quote_parms = new QuoteParams { HedgeRatio = 1.0, IsWorking = true, PessimisticHedgePricing = true }; + if (quote_parms == null) quote_parms = new QuoteParams { LeanQuantityRatio = 1.0, IsWorking = true, PessimisticHedgePricing = true }; if (quote_parms.TickRangeRequoteRules == null) quote_parms.TickRangeRequoteRules = new TickRangeRequoteRules(); } private static void _sanitize_hedge_params(HedgeParams hedge_params) { @@ -102,20 +102,20 @@ namespace mbts.spark public class QuoteParamsVM { public QuoteParamsVM(QuoteParams from) { - hedge_ratio = from.HedgeRatio; + lean_quantity_ratio = from.LeanQuantityRatio; pessimistic_hedge_pricing = from.PessimisticHedgePricing; foreach (var rr in from.TickRangeRequoteRules.TicksAwayToSensitivity) tick_range_requote_items.Add(new TickRangeRequoteVM(rr.Key, rr.Value)); remove_tick_range_requote_item = new DelegateCommand(item => tick_range_requote_items.Remove(item)); add_tick_range_requote_item = new DelegateCommand(() => tick_range_requote_items.Add(new TickRangeRequoteVM(tick_range_requote_items.Count == 0 ? 0 : tick_range_requote_items.Select(trr => trr.range).Max(), 1))); } - public double hedge_ratio { get; set; } + public double lean_quantity_ratio { get; set; } public bool pessimistic_hedge_pricing { get; set; } public ObservableCollection tick_range_requote_items { get; } = new ObservableCollection(); public ICommand remove_tick_range_requote_item { get; private set; } public ICommand add_tick_range_requote_item { get; private set; } public QuoteParams get_params_obj(bool is_working) { - var rv = new QuoteParams { PessimisticHedgePricing = pessimistic_hedge_pricing, HedgeRatio = hedge_ratio, IsWorking = is_working, TickRangeRequoteRules = new TickRangeRequoteRules() }; + var rv = new QuoteParams { PessimisticHedgePricing = pessimistic_hedge_pricing, LeanQuantityRatio = lean_quantity_ratio, IsWorking = is_working, TickRangeRequoteRules = new TickRangeRequoteRules() }; foreach (var rr in tick_range_requote_items) rv.TickRangeRequoteRules.TicksAwayToSensitivity[rr.range] = rr.sensitivity; return rv; } diff --git a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesModel.cs b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesModel.cs index aeb799338..938679736 100644 --- a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesModel.cs +++ b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesModel.cs @@ -6,37 +6,38 @@ using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; -using System.Windows.Threading; using static bts.api.SecurityConverter; namespace mbts.spark { internal class TimeAndSalesModel : IDisposable { - public TimeAndSalesModel(IReadOnlyCollection securities) { - this.securities = securities; - _timer = new DispatcherTimer(TimeSpan.FromSeconds(0.1), DispatcherPriority.Normal, _tick, Dispatcher.CurrentDispatcher); + public TimeAndSalesModel(IBus bus, IReadOnlyCollection securities) { + set_securities(securities); + _orders_model = new OrdersModel(bus); + _work_loop = WorkLoop.Start(_refresh); } - private readonly DispatcherTimer _timer; + private readonly IDisposable _work_loop; + private readonly OrdersModel _orders_model; + private readonly Subject>> _trades = new Subject>>(); private readonly Dictionary _channels = new Dictionary(); - private void _tick(object sender, EventArgs e) { + private void _refresh() { var ts = _channels.SelectMany(kv => kv.Value.read_trades().Select(t => Tuple.Create(kv.Key, t))).ToList(); if (ts.Count > 0) _trades.OnNext(ts); } public IObservable>> trades => _trades.AsObservable(); - public IReadOnlyCollection securities { - get => _channels.Keys; - set { - foreach (var r in _channels.Keys.Except(value).ToList()) _channels.Remove(r); - foreach (var a in value.Except(_channels.Keys).ToList()) _channels.Add(a, Co2RelayControl.instance.consumer.get_channel(a.symbol, get_type(a.ContractCase), get_exchange(a.Exchange))); - } + public IReadOnlyCollection securities => _channels.Keys; + public OrdersModel orders_model => _orders_model; + + public void set_securities(IEnumerable securities) { + foreach (var r in _channels.Keys.Except(securities).ToList()) _channels.Remove(r); + foreach (var a in securities.Except(_channels.Keys).ToList()) _channels.Add(a, Co2RelayControl.instance.consumer.get_channel(a.symbol, get_type(a.ContractCase), get_exchange(a.Exchange))); } - public void start() { _timer.Start(); } - public void Dispose() { _timer.Stop(); } + public void Dispose() { _work_loop.Dispose(); } } } \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesVM.cs b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesVM.cs index 1ddcdd911..73c220fcb 100644 --- a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesVM.cs +++ b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesVM.cs @@ -1,8 +1,12 @@ using bts.api; using bts.co2; +using bts.spark; using Google.Protobuf; +using mbts.spark.menu_items; +using mbts.spark.utilities; using mbts.ui; -using mbts.ui.spark; +using mbts.ui.shell; +using mbts.ui.utilities; using mbts.ui.utility; using ProtoBuf; using System; @@ -10,7 +14,10 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; +using System.Reactive.Linq; +using System.Windows.Controls; using System.Windows.Data; +using static mbts.ui.spark.TimeAndSalesView; namespace mbts.spark { @@ -19,13 +26,18 @@ namespace mbts.spark public const int VERSION = 1; public const string SAVE_NAME = "TimeAndSales"; - public TimeAndSalesVM(IReadOnlyCollection securities, IReadOnlyCollection sorting_criteria = null) { - _model = new TimeAndSalesModel(securities); - var rows = new ObservableAutoWrapper>(_trades, tup => new Row(tup.Item1, tup.Item2)); - row_views = CollectionViewSource.GetDefaultView(rows); - if (sorting_criteria != null) row_views.SortDescriptions.AddRange(sorting_criteria.Select(sc => sc.to_sort_description())); - else row_views.SortDescriptions.Add(new SortDescription(nameof(Row.trade_time), ListSortDirection.Descending)); - _sub = _model.trades.ObserveOnDispatcher().Subscribe(ts => { + public TimeAndSalesVM(IBus bus, IReadOnlyCollection securities, IReadOnlyCollection sorting_criteria = null) { + _bus = bus; + _resources.Add(_model = new TimeAndSalesModel(bus, securities)); + _rows = new ObservableAutoWrapper>(_trades, tup => new Row(tup.Item1, tup.Item2)); + _rows.ViewDestroyed += r => r.Dispose(); + _resources.Add(Disposable.Create(() => _rows.Clear())); + rows_view = CollectionViewSource.GetDefaultView(_rows); + if (sorting_criteria != null) rows_view.SortDescriptions.AddRange(sorting_criteria.Select(sc => sc.to_sort_description())); + else rows_view.SortDescriptions.Add(new SortDescription(nameof(Row.trade_time), ListSortDirection.Descending)); + _resources.Add(_context_menu = new ContextMenuVM(_context_menu_item_factory)); + _resources.Add(_model.orders_model.on_orderbook().ObserveOnDispatcher().Subscribe(ob => _order_book = ob)); + _resources.Add(_model.trades.ObserveOnDispatcher().Subscribe(ts => { if (ts.Count >= 1000) { _trades.Clear(); for (int i = ts.Count - 1000; i < ts.Count; i++) _trades.Add(ts[i]); @@ -35,38 +47,63 @@ namespace mbts.spark while (remove-- > 0) _trades.RemoveAt(0); _trades.AddRange(ts); } - }); - modify_security_selection = new DialogCommand(() => new SecuritySelectorDialog { - DataContext = new SecuritySelectorDialogVM("Time And Sales", _model.securities.ToArray(), - s => { - var new_secs = s.ToList(); - foreach (var r in _trades.Where(tup => !new_secs.Contains(tup.Item1)).ToList()) _trades.Remove(r); - _model.securities = new_secs; - }) }, () => true, true, -12, -30); + })); + _resources.Add(_current_cell); } + private readonly IBus _bus; + private readonly TimeAndSalesModel _model; private readonly ObservableCollection> _trades = new ObservableCollection>(); - private TimeAndSalesModel _model; - private IDisposable _sub; + private readonly ObservableAutoWrapper> _rows; + private readonly ContextMenuVM _context_menu; + private readonly ColdObseravbleProperty _current_cell = new ColdObseravbleProperty(); + private IList _resources = new List(); + private IOrderBook _order_book = new OrderBook(); - public ICollectionView row_views { get; private set; } - public IDialogCommand modify_security_selection { get; private set; } - - public StartupData get_startup_data() { return new StartupData(_model.securities, row_views.SortDescriptions.Select(sd => new SortingCriteria(sd)).ToArray()); } - public void Dispose() { Disposable.dispose(ref _sub); Disposable.dispose(ref _model); } - - private class Row { - public Row(Security security, TradeMessage trade) { - _security = security; - _trade = trade; + private IEnumerable _context_menu_item_factory() { + yield return MenuItemVM.Create(new ModifySecuritySelectionMenuItem(new HashSet(_rows.Select(r => r.security.value)), _model.set_securities)); + if (current_cell != null && current_cell.Column != null && current_cell.Item != null && !current_cell.Item.Equals(System.Windows.DependencyProperty.UnsetValue)) { + var securities = _rows.Where(r => r.is_selected).Select(r => r.security.value).ToList(); + yield return MenuItemVM.Create(new LadderMenuItem(_bus), securities); + yield return MenuItemVM.Create(new LinkedLadderMenuItem(_bus, _get_current_security_observable().ToSecurityMD())); + yield return MenuItemVM.Create(new OrderTicketMenuItem(_model.orders_model), securities); + yield return MenuItemVM.Create(new LinkedOrderTicketMenuItem(_bus, _get_current_security_observable().Select(OrderHelper.get_default_order))); + yield return MenuItemVM.Create(new MarketViewMenuItem(_bus), securities); + yield return MenuItemVM.Create(new SpreadMatrixMenuItem(_bus), securities); + yield return MenuItemVM.Create(new SyntheticCreateMenuItem(_bus), securities); + yield return MenuItemVM.Create(new SyntheticStrategyMenuItem(_bus), securities); + yield return MenuItemVM.Create(new ModifyOrderRootMenuItem(_model.orders_model, _order_book.get_active_orders_for_security(securities).Select(e => e.order()).ToList()), securities); + yield return MenuItemVM.Create(new CancelOrderRootMenuItem(_model.orders_model, _order_book.get_active_orders_for_security(securities).Select(e => e.order()).ToList()), securities); + yield return MenuItemVM.Create(new CancelBuyOrdersMenuItem(_model.orders_model), securities); + yield return MenuItemVM.Create(new CancelSellOrdersMenuItem(_model.orders_model), securities); + yield return MenuItemVM.Create(new CancelOrdersMenuItem(_model.orders_model), securities); } - private readonly Security _security; - private readonly TradeMessage _trade; + } - public Security security => _security; - public uint quantity => _trade.size; - public double price => _trade.mantissa * Math.Pow(10, _trade.exponent); - public DateTime trade_time => _trade.time.lldatetime(); + private IObservable _get_current_security_observable() { return _current_cell.Select(_get_security).DistinctUntilChanged(); } + private static Security _get_security(DataGridCellInfo cell) { return ((Row)cell.Item).security.value; } + + public ICollectionView rows_view { get; private set; } + public DataGridCellInfo current_cell { get => _current_cell.Value; set => _current_cell.set(value); } + public ContextMenuVM context_menu => _context_menu; + + public StartupData get_startup_data() { return new StartupData(_model.securities, rows_view.SortDescriptions.Select(sd => new SortingCriteria(sd)).ToArray()); } + public void Dispose() { Disposable.dispose(_resources); } + + private class Row : GridRowViewModelBase { + public Row(Security security, TradeMessage trade) { + this.security = AddCell(Columns.Security, security); + quantity = AddCell(Columns.Size, trade.size); + price = AddCell(Columns.Price, trade.mantissa * Math.Pow(10, trade.exponent)); + trade_time = AddCell(Columns.TradeTime, trade.time.lldatetime()); + order_type = AddCell(Columns.OrderType, Order.AlgoOrderTypeOneofCase.None); + } + + public SelectableViewModelBase security { get; } + public SelectableViewModelBase quantity { get; } + public SelectableViewModelBase price { get; } + public SelectableViewModelBase trade_time { get; } + public SelectableViewModelBase order_type { get; } } [ProtoContract] diff --git a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesView.xaml b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesView.xaml index c788633b4..a385a0eb3 100644 --- a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesView.xaml +++ b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesView.xaml @@ -1,34 +1,57 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesView.xaml.cs b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesView.xaml.cs index a0976718f..8bf743c48 100644 --- a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesView.xaml.cs +++ b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesView.xaml.cs @@ -7,6 +7,8 @@ namespace mbts.ui.spark /// public partial class TimeAndSalesView : UserControl { + public enum Columns { TradeTime, Security, Price, Size, OrderType } + public TimeAndSalesView() { InitializeComponent(); } diff --git a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesWindow.cs b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesWindow.cs index 4318eeb03..0cedfcb20 100644 --- a/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesWindow.cs +++ b/src/client/spark/mspark/Shell/TimeAndSales/TimeAndSalesWindow.cs @@ -12,15 +12,17 @@ namespace mbts.spark { internal class TimeAndSalesWindow : IShellWindow { - public TimeAndSalesWindow(IShellModule owner, IReadOnlyCollection securities) : this (owner, securities, null) { } - public TimeAndSalesWindow(IShellModule owner, TimeAndSalesVM.StartupData startup_data) : this(owner, startup_data.securities.Select(deserialize).ToList(), startup_data.sorting_criteria) { } + public TimeAndSalesWindow(IShellModule owner, IBus bus, IReadOnlyCollection securities) : this (owner, bus, securities, null) { } + public TimeAndSalesWindow(IShellModule owner, IBus bus, TimeAndSalesVM.StartupData startup_data) : this(owner, bus, startup_data.securities.Select(deserialize).ToList(), startup_data.sorting_criteria) { } - private TimeAndSalesWindow(IShellModule owner, IReadOnlyCollection securities, IReadOnlyCollection sorting_criteria) { + private TimeAndSalesWindow(IShellModule owner, IBus bus, IReadOnlyCollection securities, IReadOnlyCollection sorting_criteria) { + _bus = bus; _securities = securities; _sorting_criteria = sorting_criteria; _owner = owner; } + private readonly IBus _bus; private readonly IReadOnlyCollection _securities; private readonly IReadOnlyCollection _sorting_criteria; private TimeAndSalesVM _vm; @@ -35,7 +37,7 @@ namespace mbts.spark public event Action TitleChanged; public event Action IconChanged; public void Dispose() { Disposable.dispose(ref _vm); } - public ShellWindowUI GetContent() { return new ShellWindowUI(new TimeAndSalesView { DataContext = _vm = new TimeAndSalesVM(_securities, _sorting_criteria), Width = 400, Height = 500 }); } + public ShellWindowUI GetContent() { return new ShellWindowUI(new TimeAndSalesView { DataContext = _vm = new TimeAndSalesVM(_bus, _securities, _sorting_criteria), Width = 400, Height = 500 }); } public void GetState(Stream save_here) { if (_vm != null) { serialize(save_here, new ShellSerializationHeader { name = TimeAndSalesVM.SAVE_NAME, version = TimeAndSalesVM.VERSION }); diff --git a/src/client/spark/mspark/Shell/TradesModule.cs b/src/client/spark/mspark/Shell/TradesModule.cs index ea06c7e35..31fe57fba 100644 --- a/src/client/spark/mspark/Shell/TradesModule.cs +++ b/src/client/spark/mspark/Shell/TradesModule.cs @@ -40,7 +40,14 @@ namespace mbts.spark public int priority => 1; public string name => "Trades"; public ImageSource icon => Icons.Trades; - public IShellWindow launch_ui => new LaunchMenu { DataContext = new LaunchMenuVM(new OrderBookMenuItem(_bus), new FillsMenuItem(_bus), new AuditLogsMenuItem(_bus), new PositionsMenuItem(_bus), new TimeAndSalesMenuItem(_bus)) }; + public IShellWindow launch_ui => new LaunchMenu { + DataContext = new LaunchMenuVM( + new OrderBookMenuItem(_bus), + new FillsMenuItem(_bus), + new AuditLogsMenuItem(_bus), + new PositionsMenuItem(_bus), + new TimeAndSalesMenuItem(_bus)) + }; public void load_state(Stream state = null) { } public void get_state(Stream save_here) { } public Task create(Stream load_stream) { @@ -48,7 +55,7 @@ namespace mbts.spark switch(header?.name) { case OrderBookVM.SAVE_NAME: if (try_deserialize(load_stream, out OrderBookState orders_state)) return Task.FromResult(create_order_book_window(orders_state)); break; case FillsVM.SAVE_NAME: { if (try_deserialize(load_stream, out FillsVM.StartupData state)) return Task.FromResult(create_fills_window(state)); break; } - case TimeAndSalesVM.SAVE_NAME: { if (try_deserialize(load_stream, out TimeAndSalesVM.StartupData state)) return Task.FromResult(new TimeAndSalesWindow(this, state)); break; } + case TimeAndSalesVM.SAVE_NAME: { if (try_deserialize(load_stream, out TimeAndSalesVM.StartupData state)) return Task.FromResult(new TimeAndSalesWindow(this, _bus, state)); break; } } return Task.FromResult(null); } @@ -56,7 +63,7 @@ namespace mbts.spark public void Dispose() { _dispose.Dispose(); } private IShellWindow create_order_book_window(OrderBookState state) { - var vm = new OrderBookVM(new OrdersModel(_bus), state, Observable.Return(new OrderBookSettings())); + var vm = new OrderBookVM(_bus, new OrdersModel(_bus), state, Observable.Return(new OrderBookSettings())); var view = new OrderBookView(vm) { Width = 1526, Height = 800 }; return ShellWindow.create(this, "Order Book", view, vm.get_state); } @@ -64,7 +71,7 @@ namespace mbts.spark private IShellWindow create_fills_window(FillsVM.StartupData startup_data) { return create_fills_window(startup_data.securities.Select(deserialize).ToList(), startup_data.sorting_criteria); } private IShellWindow create_fills_window(IReadOnlyCollection securities) { return create_fills_window(securities, null); } private IShellWindow create_fills_window(IReadOnlyCollection securities, IReadOnlyCollection sorting_criteria) { - var vm = new FillsVM(new OrdersModel(_bus), securities, sorting_criteria); + var vm = new FillsVM(_bus, new OrdersModel(_bus), securities, sorting_criteria); var view = new FillsView { DataContext = vm, Width = 1024, Height = 800 }; return ShellWindow.create(this, "Fills", view, vm.get_state, Icons.Ticket); } @@ -73,6 +80,6 @@ namespace mbts.spark private void show_fills(ShowFillsMessage msg) { _wm.Windows.Add(create_fills_window(new List())); } private void show_audit_log(ShowAuditLogsMessage msg) { } private void show_positions(ShowPositionsMessage msg) { } - private void show_time_and_sales(ShowTimeAndSalesMessage msg) { _wm.Windows.Add(new TimeAndSalesWindow(this, msg.data)); } + private void show_time_and_sales(ShowTimeAndSalesMessage msg) { _wm.Windows.Add(new TimeAndSalesWindow(this, _bus, msg.data)); } } } \ No newline at end of file diff --git a/src/client/spark/mspark/Utilities/BBOVM.cs b/src/client/spark/mspark/Utilities/BBOVM.cs index 8fa6defa0..4d85c8691 100644 --- a/src/client/spark/mspark/Utilities/BBOVM.cs +++ b/src/client/spark/mspark/Utilities/BBOVM.cs @@ -1,38 +1,32 @@ using bts.api; -using mbts.co2; +using mbts.spark.utilities; using mbts.ui.shell; +using System; +using System.Reactive.Linq; namespace mbts.spark { - internal class BBOVM : ViewModelBase + internal class BBOVM : DisposableViewModelBase { - public BBOVM(SecurityMD smd) { - _smd = smd; - _bid = backing(nameof(bid), double.NaN); - _ask = backing(nameof(ask), double.NaN); - _bid_size = backing(nameof(bid_size), (ushort)0); - _ask_size = backing(nameof(ask_size), (ushort)0); - refresh(); + public BBOVM(uint security) : this(Observable.Return(security)) { } + public BBOVM(IObservable security) : this(security.ToSecurity()) { } + public BBOVM(IObservable security) : this(security, new SecurityMDPump(security)) { } + public BBOVM(IObservable security, ISecurityMDPump md_pump) { + _security = backing(nameof(security), security, Security.Empty); + _bid = backing(nameof(bid), md_pump.bid_price, double.NaN); + _ask = backing(nameof(ask), md_pump.ask_price, double.NaN); + _bid_size = backing(nameof(bid_size), md_pump.bid_size, (ushort)0); + _ask_size = backing(nameof(ask_size), md_pump.ask_size, (ushort)0); } - private readonly SecurityMD _smd; + private readonly Property _security; private readonly Property _bid, _ask; private readonly Property _bid_size, _ask_size; - private ulong _time = 0; - public Security security => _smd.security; + public Security security => _security.Value; public double bid => _bid.Value; public double ask => _ask.Value; public ushort bid_size => _bid_size.Value; public ushort ask_size => _ask_size.Value; - - public void refresh() { - if (_smd.md.get_bbo(ref _time, out NativePriceSize b, out NativePriceSize a)) { - _bid.set(b.price); - _bid_size.set(b.size); - _ask.set(a.price); - _ask_size.set(a.size); - } - } } } \ No newline at end of file diff --git a/src/client/spark/mspark/Utilities/ContextMenuVM.cs b/src/client/spark/mspark/Utilities/ContextMenuVM.cs new file mode 100644 index 000000000..038faa496 --- /dev/null +++ b/src/client/spark/mspark/Utilities/ContextMenuVM.cs @@ -0,0 +1,34 @@ +using mbts.spark.menu_items; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Windows.Data; + +namespace mbts.spark.utilities +{ + internal class ContextMenuVM : IDisposable + { + public ContextMenuVM(Func> menu_factory) { + _menu_factory = menu_factory; + _items = new ObservableCollection(_menu_factory()); + items_view = CollectionViewSource.GetDefaultView(_items); + items_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(MenuItemVM.sectional_id))); + } + + private readonly Func> _menu_factory; + private readonly ObservableCollection _items; + private bool _is_open; + public bool is_open { + get => _is_open; + set { + _is_open = value; + Disposable.dispose(_items); + foreach (var item in _menu_factory()) _items.Add(item); + } + } + public ICollectionView items_view { get; } + + public void Dispose() { Disposable.dispose(_items); } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Utilities/Grid/GridRowViewModelBase.cs b/src/client/spark/mspark/Utilities/Grid/GridRowViewModelBase.cs new file mode 100644 index 000000000..641e9adb5 --- /dev/null +++ b/src/client/spark/mspark/Utilities/Grid/GridRowViewModelBase.cs @@ -0,0 +1,54 @@ +using mbts.collections; +using mbts.ui.controls; +using mbts.ui.shell; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.Linq; +using System.Reactive.Linq; + +namespace mbts.spark.utilities +{ + internal class GridRowViewModelBase : DisposableViewModelBase + { + private readonly IList _column_containers = new List(); + private readonly ObservableCollectionEx _selected_columns = new ObservableCollectionEx(); + + private void _check_column_present(TColumn column) { if (_column_containers.Any(c => c.column.Equals(column))) throw new InvalidOperationException("Column '{0}' already added.".fmt(column)); } + + public SelectableViewModelBase AddCell(TColumn column, T initial_value = default(T)) { + _check_column_present(column); + var cell = new SelectableViewModelBase(initial_value); + _column_containers.Add(new ColumnContainer(column, cell.observe_is_selected(), this)); + return cell; + } + + public RXReadOnlyDataGridCell AddCell(TColumn column, IObservable data, T initial_value = default(T)) { + _check_column_present(column); + var cell = new RXReadOnlyDataGridCell(data, initial_value); + _column_containers.Add(new ColumnContainer(column, cell.observe_is_selected(), this)); + return cell; + } + + public void RemoveCell(TColumn column) { _column_containers.PopDispose(column, c => c.column); } + + public bool is_selected => _selected_columns.Any(); + public IReadOnlyObservableCollectionEx selected_columns => _selected_columns; + public IObservable observe_is_selected() { return _selected_columns.Observe().Select(_ => _selected_columns.Count > 0).DistinctUntilChanged(); } + + protected override void Dispose(bool disposing) { Disposable.dispose(_column_containers); } + + private class ColumnContainer : IDisposable { + public ColumnContainer(TColumn column, IObservable is_selected, GridRowViewModelBase owner) { + this.column = column; + _dispose = is_selected.ObserveOnDispatcher().Subscribe(selected => { + if (selected) owner._selected_columns.Add(column); + else owner._selected_columns.Remove(column); + }); + } + public readonly TColumn column; + private IDisposable _dispose; + public void Dispose() { Disposable.dispose(ref _dispose); } + } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Utilities/ISecurityMDPump.cs b/src/client/spark/mspark/Utilities/ISecurityMDPump.cs new file mode 100644 index 000000000..1044c2893 --- /dev/null +++ b/src/client/spark/mspark/Utilities/ISecurityMDPump.cs @@ -0,0 +1,108 @@ +using bts.api; +using mbts.co2; +using mbts.collections.extensions; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reactive.Linq; +using System.Reactive.Subjects; +using MDMap = System.Collections.Generic.Dictionary; + +namespace mbts.spark.utilities +{ + internal interface ISecurityMDPump + { + IObservable<(double bid, ushort bid_size, double ask, ushort ask_size)> bbo { get; } + IObservable<(double last, ushort last_size, DateTime time_stamp, ulong volume)> last_trade { get; } + IObservable bid_price { get; } + IObservable bid_size { get; } + IObservable ask_price { get; } + IObservable ask_size { get; } + IObservable last_price { get; } + IObservable last_size { get; } + IObservable volume { get; } + IObservable session_low { get; } + IObservable session_high { get; } + IObservable settlement_price { get; } + } + + internal class SecurityMDPump : ISecurityMDPump, IDisposable + { + public SecurityMDPump(Security security) : this(security, WorkLoop.DefaultPollInterval) { } + public SecurityMDPump(Security security, TimeSpan poll_interval) : this(security, Observable.Interval(poll_interval)) { } + public SecurityMDPump(Security security, IObservable poll) : this(security.Id, poll) { } + public SecurityMDPump(IObservable security) : this(security.Select(s => s.Id)) { } + public SecurityMDPump(IObservable security, TimeSpan poll_interval) : this(security.Select(s => s.Id), poll_interval) { } + public SecurityMDPump(IObservable security, IObservable poll) : this(security.Select(s => s.Id), poll) { } + public SecurityMDPump(uint security) : this(security, WorkLoop.DefaultPollInterval) { } + public SecurityMDPump(uint security, TimeSpan poll_interval) : this(security, Observable.Interval(poll_interval)) { } + public SecurityMDPump(uint security, IObservable poll) : this(Observable.Return(security).ToSecurity(), poll) { } + public SecurityMDPump(IObservable security) : this(security, WorkLoop.DefaultPollInterval) { } + public SecurityMDPump(IObservable security, TimeSpan poll_interval) : this(security, Observable.Interval(poll_interval)) { } + public SecurityMDPump(IObservable security, IObservable poll) : this(security.CombineLatest(ImportedResources.Bus.subscribe(SparkTags.SecuritiesTag), (s, m) => m.GetValueOrDefault(s).md).Where(md => md != null), poll) { } + public SecurityMDPump(IMDHandle md) : this(Observable.Return(md)) { } + public SecurityMDPump(IMDHandle md, TimeSpan poll_interval) : this(Observable.Return(md), poll_interval) { } + public SecurityMDPump(IMDHandle md, IObservable poll) : this(Observable.Return(md), poll) { } + public SecurityMDPump(IObservable md_source) : this(md_source, WorkLoop.DefaultPollInterval) { } + public SecurityMDPump(IObservable md_source, TimeSpan poll_interval) : this(md_source, Observable.Interval(poll_interval)) { } + public SecurityMDPump(IObservable md_source, IObservable poll) { + _root_pump = poll.CombineLatest(md_source, (_, md) => md); + _bbo_pump = _root_pump.Select(_refresh_bbo).Where(r => r).Publish(); + _last_pump = _root_pump.Select(_refresh_last).Where(r => r).Publish(); + _connections.Add(_bbo_pump.Connect()); + _connections.Add(_last_pump.Connect()); + } + + private readonly IObservable _root_pump; + private readonly IConnectableObservable _bbo_pump; + private readonly IConnectableObservable _last_pump; + private readonly IList _connections= new List(); + + private ulong _bbo_ref, _last_ref; + private double _bid_price, _ask_price, _last_price; + private ushort _bid_size, _ask_size, _last_size; + private ulong _volume; + private DateTime _last_time; + + private bool _refresh_bbo(IMDHandle md) { + if (md.get_bbo(ref _bbo_ref, out NativePriceSize b, out NativePriceSize a)) { + _bid_price = b.price; + _bid_size = b.size; + _ask_price = a.price; + _ask_size = a.size; + return true; + } + return false; + } + + private bool _refresh_last(IMDHandle md) { + if (md.get_last_trade(ref _last_ref, out NativePriceSize ps, out DateTime ts, out ulong v)) { + _last_price = ps.price; + _last_size = ps.size; + _last_time = ts; + _volume = v; + return true; + } + return false; + } + + private (double, ushort, double, ushort) _select_bbo() { return (_bid_price, _bid_size, _ask_price, _ask_size); } + private (double, ushort, DateTime, ulong) _select_last() { return (_last_price, _last_size, _last_time, _volume); } + + public IObservable<(double bid, ushort bid_size, double ask, ushort ask_size)> bbo => _bbo_pump.Select(_ => _select_bbo()).StartWith(_select_bbo()); + public IObservable<(double last, ushort last_size, DateTime time_stamp, ulong volume)> last_trade => _last_pump.Select(_ => _select_last()).StartWith(_select_last()); + public IObservable bid_price => _bbo_pump.Select(_ => _bid_price).DistinctUntilChanged().StartWith(_bid_price); + public IObservable bid_size => _bbo_pump.Select(_ => _bid_size).DistinctUntilChanged().StartWith(_bid_size); + public IObservable ask_price => _bbo_pump.Select(_ => _ask_price).DistinctUntilChanged().StartWith(_ask_price); + public IObservable ask_size => _bbo_pump.Select(_ => _ask_size).DistinctUntilChanged().StartWith(_ask_size); + public IObservable last_price => _bbo_pump.Select(_ => _last_price).DistinctUntilChanged().StartWith(_last_price); + public IObservable last_size => _bbo_pump.Select(_ => _last_size).DistinctUntilChanged().StartWith(_last_size); + public IObservable last_time => _last_pump.Select(_ => _last_time).DistinctUntilChanged().StartWith(_last_time); + public IObservable volume => _last_pump.Select(_ => _volume).DistinctUntilChanged().StartWith(_volume); + public IObservable session_low => _root_pump.Select(md => md.session_low).DistinctUntilChanged(); + public IObservable session_high => _root_pump.Select(md => md.session_high).DistinctUntilChanged(); + public IObservable settlement_price => _root_pump.Select(md => md.settlement_price).DistinctUntilChanged(); + + public void Dispose() { Disposable.dispose(_connections); } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Utilities/ImportedResources.cs b/src/client/spark/mspark/Utilities/ImportedResources.cs new file mode 100644 index 000000000..49b31c956 --- /dev/null +++ b/src/client/spark/mspark/Utilities/ImportedResources.cs @@ -0,0 +1,47 @@ +using bts.api; +using mbts.collections.extensions; +using mbts.ui; +using System; +using System.ComponentModel.Composition; +using System.Reactive.Linq; +using static mbts.spark.SparkTags; +using MDMap = System.Collections.Generic.Dictionary; + +namespace mbts.spark.utilities +{ + internal static class ImportedResources + { + public static IBus Bus => _instance.bus; + public static string UserName => _instance.user_name; + + #region Misc Extensions (should put these in a more appropriate place eventually) + public static IObservable ToSecurity(this IObservable securityKey) { + return securityKey.CombineLatest(Bus.subscribe(SecuritiesTag), (sk, map) => map.GetValueOrDefault(sk).security).Where(s => s != null); + } + public static IObservable ToSecurityMD(this IObservable securityKey) { + return securityKey.CombineLatest(Bus.subscribe(SecuritiesTag), (sk, map) => map.GetValueOrDefault(sk)); + } + public static IObservable ToSecurityMD(this IObservable security) { + return security.CombineLatest(Bus.subscribe(SecuritiesTag), (s, map) => map.GetValueOrDefault(s.Id)); + } + #endregion + + private static HiddenInstance _instance; + + [Export(typeof(IInitializable))] + private class HiddenInstance : IInitializable + { + [ImportingConstructor] + public HiddenInstance(IBus bus, [Import("username")]string user_name) { + this.bus = bus; + this.user_name = user_name; + } + + internal readonly IBus bus; + internal readonly string user_name; + + public int priority => int.MaxValue; + public void initialize() { _instance = this; } + } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Utilities/UserConfigurationHelper.cs b/src/client/spark/mspark/Utilities/UserConfigurationHelper.cs deleted file mode 100644 index 345dfaa01..000000000 --- a/src/client/spark/mspark/Utilities/UserConfigurationHelper.cs +++ /dev/null @@ -1,22 +0,0 @@ -using mbts.ui; -using System.ComponentModel.Composition; - -namespace mbts.spark.utilities -{ - [Export(typeof(IInitializable))] - internal class UserConfigurationHelper : IInitializable - { - public static string UserName => _instance?._user_name; - private static UserConfigurationHelper _instance; - - [ImportingConstructor] - public UserConfigurationHelper([Import("username")]string user_name) { - _user_name = user_name; - } - - private readonly string _user_name; - - public int priority => int.MaxValue; - public void initialize() { _instance = this; } - } -} \ No newline at end of file diff --git a/src/client/spark/mspark/Utilities/WorkLoop.cs b/src/client/spark/mspark/Utilities/WorkLoop.cs index 4d062f1fb..3451176df 100644 --- a/src/client/spark/mspark/Utilities/WorkLoop.cs +++ b/src/client/spark/mspark/Utilities/WorkLoop.cs @@ -5,11 +5,13 @@ namespace mbts.spark { internal static class WorkLoop { - public static IDisposable Start(Action work) { return Start(work, TimeSpan.FromSeconds(0.1)); } - public static IDisposable Start(Action work, TimeSpan interval) { - var timer = new DispatcherTimer(interval, DispatcherPriority.Normal, new EventHandler((s, e) => work()), Dispatcher.CurrentDispatcher); + public static IDisposable Start(Action work) { return Start(work, DefaultPollInterval); } + public static IDisposable Start(Action work, TimeSpan poll_interval) { + var timer = new DispatcherTimer(poll_interval, DispatcherPriority.Normal, new EventHandler((s, e) => work()), Dispatcher.CurrentDispatcher); timer.Start(); return Disposable.Create(timer.Stop); } + + public static readonly TimeSpan DefaultPollInterval = TimeSpan.FromSeconds(0.1); } } \ No newline at end of file diff --git a/src/client/spark/uicore/Images/Icons.cs b/src/client/spark/uicore/Images/Icons.cs index d7081ad05..2a10c2667 100644 --- a/src/client/spark/uicore/Images/Icons.cs +++ b/src/client/spark/uicore/Images/Icons.cs @@ -76,14 +76,17 @@ namespace mbts.ui public static ImageSource Crucible { get { return (DrawingImage)_resources["Crucible"]; } } public static ImageSource Accounting { get { return (DrawingImage)_resources["Accounting"]; } } + public static ImageSource Beaker { get { return (DrawingImage)_resources["Beaker"]; } } public static ImageSource Book { get { return (DrawingImage)_resources["Book"]; } } public static ImageSource CancelOrders { get { return (DrawingImage)_resources["CancelOrders"]; } } public static ImageSource Clock { get { return (DrawingImage)_resources["Clock"]; } } public static ImageSource Defrag { get { return (DrawingImage)_resources["Defrag"]; } } public static ImageSource Display { get { return (DrawingImage)_resources["Display"]; } } + public static ImageSource Knight { get { return (DrawingImage)_resources["Knight"]; } } public static ImageSource Payment { get { return (DrawingImage)_resources["Payment"]; } } public static ImageSource Spawn { get { return (DrawingImage)_resources["Spawn"]; } } public static ImageSource Target { get { return (DrawingImage)_resources["Target"]; } } + public static ImageSource Tetris { get { return (DrawingImage)_resources["Tetris"]; } } public static ImageSource Wrench { get { return (DrawingImage)_resources["Wrench"]; } } } } \ No newline at end of file diff --git a/src/client/spark/uicore/Images/Vector/Icons.xaml b/src/client/spark/uicore/Images/Vector/Icons.xaml index 93c842a8c..347cfe9be 100644 --- a/src/client/spark/uicore/Images/Vector/Icons.xaml +++ b/src/client/spark/uicore/Images/Vector/Icons.xaml @@ -324,6 +324,27 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z"> + + + + + + + + + + @@ -347,6 +368,20 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z"> + + + + + + + + + + + + + + @@ -357,7 +392,18 @@ M0,0L63.999001,0 63.999001,48.792999 0,48.792999z"> - + + + + + + + + + + + + diff --git a/src/client/spark/uicore/Settings/UISettings.proto b/src/client/spark/uicore/Settings/UISettings.proto index 83edbc73f..35b257c22 100644 --- a/src/client/spark/uicore/Settings/UISettings.proto +++ b/src/client/spark/uicore/Settings/UISettings.proto @@ -1,127 +1,127 @@ -syntax="proto3"; -package mbts.ui; -option csharp_namespace="mbts.ui"; -//import "core/bts_sys/api/services/MarketDataService.proto"; -import "google/protobuf/descriptor.proto"; - - -// -// Custom Options -// -extend google.protobuf.MessageOptions { - string header = 10000; -} -message Validation { - string pattern = 1; - uint32 max_length = 2; - int64 min_value = 3; - int64 max_value = 4; -} -extend google.protobuf.FieldOptions { - string name = 20000; - string comment = 20001; - Validation validation = 30000; -} - -// -// Special settings objects -// -message SettingsFont { - string family = 1; - float size = 2 [(validation).min_value = 4, (validation).max_value=20]; - bool bold = 3; - bool italic = 4; - bool oblique = 5; - bool underline = 6; - bool strikeout = 7; - string script = 8; -} - -message SettingsColor { - uint32 A = 1; - uint32 R = 2; - uint32 G = 3; - uint32 B = 4; -} - -message CalculatorButtons { - string buttons = 1 [(validation).pattern = "^([0-9]+[ ,;]*)*$"]; -} - -// -// Global settings container. Put your application settings in here for them to be visible in the UI -// -message ApplicationSettings { - // oneof => radio button - // color,font => custom control - GeneralSettings general = 1; - map ladder_settings = 2; -} - -// -// General settings -// - -message GeneralSettings { - double tab_width = 1; - double tab_height = 2; -} - -// -// Ladder settings -// - -message LadderSettings { - option (header) = "Ladder Settings"; - double row_height = 1; - SettingsColor grid_line_color = 2; - CalculatorButtons calculator_buttons = 3; - bool show_scroll_bar = 4; - int32 ticks_until_recenter = 5 [(validation).min_value = 3, (validation).max_value=10]; - int32 seconds_until_recenter = 6 [(validation).min_value = 10, (validation).max_value=3600]; - string initial_algo = 7; - string initial_time_in_force = 8; - uint32 default_order_size = 9; - bool animate_recenter = 10; - - LadderColumnSettings orders_column = 50; - LadderColumnSettings bid_column = 51; - LadderColumnSettings ask_column = 52; - LadderColumnSettings price_column = 53; - LadderColumnSettings last_column = 54; - -} -message LadderColumnSettings { - bool show = 1; - uint32 width = 2; - SettingsColor background = 3; - SettingsColor foreground = 4; - SettingsFont font = 5; -} - -// -// OrderBook settings -// -message OrderBookSettings { - CalculatorButtons calculator_buttons = 1; - ColumnOrder column_visibility = 100; -} -message ColumnOrder { - bool security = 100; - bool time = 101; - bool user = 102; - bool account = 103; - bool exchange = 104; - bool orders = 105; - bool side = 106; - bool status = 107; - bool price = 108; - bool quantity = 109; - bool filled= 110; - bool average_price = 111; - bool flat_order_params = 112 [(name)="Misc"]; - bool bts_order = 113 [(name)="BTS Order"]; - bool exchange_order = 114; - bool details = 115; -} - +syntax="proto3"; +package mbts.ui; +option csharp_namespace="mbts.ui"; +//import "core/bts_sys/api/services/MarketDataService.proto"; +import "google/protobuf/descriptor.proto"; + + +// +// Custom Options +// +extend google.protobuf.MessageOptions { + string header = 10000; +} +message Validation { + string pattern = 1; + uint32 max_length = 2; + int64 min_value = 3; + int64 max_value = 4; +} +extend google.protobuf.FieldOptions { + string name = 20000; + string comment = 20001; + Validation validation = 30000; +} + +// +// Special settings objects +// +message SettingsFont { + string family = 1; + float size = 2 [(validation).min_value = 4, (validation).max_value=20]; + bool bold = 3; + bool italic = 4; + bool oblique = 5; + bool underline = 6; + bool strikeout = 7; + string script = 8; +} + +message SettingsColor { + uint32 A = 1; + uint32 R = 2; + uint32 G = 3; + uint32 B = 4; +} + +message CalculatorButtons { + string buttons = 1 [(validation).pattern = "^([0-9]+[ ,;]*)*$"]; +} + +// +// Global settings container. Put your application settings in here for them to be visible in the UI +// +message ApplicationSettings { + // oneof => radio button + // color,font => custom control + GeneralSettings general = 1; + map ladder_settings = 2; +} + +// +// General settings +// + +message GeneralSettings { + double tab_width = 1; + double tab_height = 2; +} + +// +// Ladder settings +// + +message LadderSettings { + option (header) = "Ladder Settings"; + double row_height = 1; + SettingsColor grid_line_color = 2; + CalculatorButtons calculator_buttons = 3; + bool show_scroll_bar = 4; + int32 ticks_until_recenter = 5 [(validation).min_value = 3, (validation).max_value=10]; + int32 seconds_until_recenter = 6 [(validation).min_value = 10, (validation).max_value=3600]; + string initial_algo = 7; + string initial_time_in_force = 8; + uint32 default_order_size = 9; + bool animate_recenter = 10; + + LadderColumnSettings orders_column = 50; + LadderColumnSettings bid_column = 51; + LadderColumnSettings ask_column = 52; + LadderColumnSettings price_column = 53; + LadderColumnSettings last_column = 54; + +} +message LadderColumnSettings { + bool show = 1; + uint32 width = 2; + SettingsColor background = 3; + SettingsColor foreground = 4; + SettingsFont font = 5; +} + +// +// OrderBook settings +// +message OrderBookSettings { + CalculatorButtons calculator_buttons = 1; + ColumnOrder column_visibility = 100; +} +message ColumnOrder { + bool security = 100; + bool time = 101; + bool user = 102; + bool account = 103; + bool exchange = 104; + bool orders = 105; + bool side = 106; + bool status = 107; + bool price = 108; + bool quantity = 109; + bool filled= 110; + bool average_price = 111; + bool flat_order_params = 112 [(name)="Misc"]; + bool bts_order = 113 [(name)="BTS Order"]; + bool exchange_order = 114; + bool details = 115; +} + diff --git a/src/client/spark/view/Controls/Algo/AbsolutePriceTriggerControl.xaml b/src/client/spark/view/Controls/Algo/AbsolutePriceTriggerControl.xaml new file mode 100644 index 000000000..c56f85d75 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/AbsolutePriceTriggerControl.xaml @@ -0,0 +1,47 @@ + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/AbsolutePriceTriggerControl.xaml.cs b/src/client/spark/view/Controls/Algo/AbsolutePriceTriggerControl.xaml.cs new file mode 100644 index 000000000..a68dd97e1 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/AbsolutePriceTriggerControl.xaml.cs @@ -0,0 +1,46 @@ +using bts.spark; +using mbts.spark; +using System.Windows; +using System.Windows.Controls; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for AbsolutePriceTriggerControl.xaml + /// + public class AbsolutePriceTriggerControl : UserControl + { + static AbsolutePriceTriggerControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(AbsolutePriceTriggerControl), new FrameworkPropertyMetadata(typeof(AbsolutePriceTriggerControl))); + } + + #region AbsoluteTrigger + public static readonly DependencyProperty AbsoluteTriggerProperty = DependencyProperty.Register("AbsoluteTrigger", typeof(AbsolutePriceTrigger), typeof(AbsolutePriceTriggerControl), new PropertyMetadata(null, OnAbsoluteTriggerChanged, CoerceAbsoluteTrigger)); + private static object CoerceAbsoluteTrigger(DependencyObject d, object baseValue) { return baseValue is AbsolutePriceTrigger ? baseValue : OrderHelper.Defaults.AbsolutePriceTrigger; } + private static void OnAbsoluteTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(AbsoluteTriggerVMPropertyKey, new AbsolutePriceTriggerVM((AbsolutePriceTrigger)e.NewValue)); } + public AbsolutePriceTrigger AbsoluteTrigger { get => GetValue(AbsoluteTriggerProperty) as AbsolutePriceTrigger; set => SetValue(AbsoluteTriggerProperty, value); } + #endregion + + #region AbsluteTriggerVM (ReadOnly) + private static readonly DependencyPropertyKey AbsoluteTriggerVMPropertyKey = DependencyProperty.RegisterReadOnly("AbsoluteTriggerVM", typeof(AbsolutePriceTriggerVM), typeof(AbsolutePriceTriggerControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty AbsoluteTriggerVMProperty = AbsoluteTriggerVMPropertyKey.DependencyProperty; + internal AbsolutePriceTriggerVM AbsoluteTriggerVM { get => GetValue(AbsoluteTriggerVMProperty) as AbsolutePriceTriggerVM; private set => SetValue(AbsoluteTriggerVMPropertyKey, value); } + #endregion + } + + internal class AbsolutePriceTriggerVM + { + public AbsolutePriceTriggerVM(AbsolutePriceTrigger model) { + _model = model; + } + + private readonly AbsolutePriceTrigger _model; + + public PriceType.Types.Status price_type { get => _model.PriceType.Status; set => _model.PriceType.Status = value; } + public double price { get => _model.TriggerPrice; set => _model.TriggerPrice = value; } + public QuantityTrigger quantity_trigger => _model.QuantityTrigger; + public QuantityMeasure quantity_measure => _model.QuantityTrigger.QuantityMeasure; + public QuantityTriggerVM quantity_trigger_vm => new QuantityTriggerVM(_model.QuantityTrigger); + public QuantityMeasureVM quantity_measure_vm => new QuantityMeasureVM(_model.QuantityTrigger.QuantityMeasure); + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Controls/AlgoTypeItem.xaml b/src/client/spark/view/Controls/Algo/AlgoTypeItem.xaml similarity index 97% rename from src/client/spark/mspark/Controls/AlgoTypeItem.xaml rename to src/client/spark/view/Controls/Algo/AlgoTypeItem.xaml index d8b3c2012..db54d216f 100644 --- a/src/client/spark/mspark/Controls/AlgoTypeItem.xaml +++ b/src/client/spark/view/Controls/Algo/AlgoTypeItem.xaml @@ -1,26 +1,26 @@ - - - - - + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Controls/AlgoTypeItem.xaml.cs b/src/client/spark/view/Controls/Algo/AlgoTypeItem.xaml.cs similarity index 100% rename from src/client/spark/mspark/Controls/AlgoTypeItem.xaml.cs rename to src/client/spark/view/Controls/Algo/AlgoTypeItem.xaml.cs diff --git a/src/client/spark/view/Controls/Algo/BTSIcebergOrderControl.xaml b/src/client/spark/view/Controls/Algo/BTSIcebergOrderControl.xaml new file mode 100644 index 000000000..22e2e7015 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/BTSIcebergOrderControl.xaml @@ -0,0 +1,122 @@ + + + + + + + + + + + 6.0 + 6.0 + + + + + + + + + + + + + + + + + + + + + ticks from prev fill + + + + + Optional... + + + + + + + + + + + + + + + + + + + Ticks + + Price Trigger + + Time Window + Start + + Stop + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/BTSIcebergOrderControl.xaml.cs b/src/client/spark/view/Controls/Algo/BTSIcebergOrderControl.xaml.cs new file mode 100644 index 000000000..305c4987f --- /dev/null +++ b/src/client/spark/view/Controls/Algo/BTSIcebergOrderControl.xaml.cs @@ -0,0 +1,101 @@ +using bts.spark; +using mbts.spark; +using mbts.ui.shell; +using System; +using System.ComponentModel; +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for BTSIcebergOrderControl.xaml + /// + public class BTSIcebergOrderControl : Control + { + static BTSIcebergOrderControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(BTSIcebergOrderControl), new FrameworkPropertyMetadata(typeof(BTSIcebergOrderControl))); + } + + #region Order + public static readonly DependencyProperty OrderProperty = DependencyProperty.Register("Order", typeof(BTSIcebergOrder), typeof(BTSIcebergOrderControl), new PropertyMetadata(null, OnOrderChanged, CoerceOrder)); + private static object CoerceOrder(DependencyObject d, object baseValue) { return baseValue is BTSIcebergOrder ? baseValue : OrderHelper.Defaults.BTSIcebergOrder; } + private static void OnOrderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(OrderVMPropertyKey, new BTSIcebergOrderVM((BTSIcebergOrder)e.NewValue)); } + public BTSIcebergOrder Order { get => GetValue(OrderProperty) as BTSIcebergOrder; set => SetValue(OrderProperty, value); } + #endregion + + #region OrderVM (ReadOnly) + private static readonly DependencyPropertyKey OrderVMPropertyKey = DependencyProperty.RegisterReadOnly("OrderVM", typeof(BTSIcebergOrderVM), typeof(BTSIcebergOrderControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty OrderVMProperty = OrderVMPropertyKey.DependencyProperty; + [EditorBrowsable(EditorBrowsableState.Never)] + internal BTSIcebergOrderVM OrderVM { get => GetValue(OrderVMProperty) as BTSIcebergOrderVM; private set => SetValue(OrderVMPropertyKey, value); } + #endregion + } + + internal class BTSIcebergOrderVM : ViewModelBase + { + public BTSIcebergOrderVM(BTSIcebergOrder model) { + _model = model; + _assign_template(); + } + + private readonly BTSIcebergOrder _model; + private double _diff_from_last_fill_template; + private PriceOffset _market_offset_template = OrderHelper.Defaults.PriceOffset; + + private void _assign_template() { + switch (_model.ChildOrderOffsetCase) { + case BTSIcebergOrder.ChildOrderOffsetOneofCase.DiffFromLastFill: _diff_from_last_fill_template = _model.DiffFromLastFill; break; + case BTSIcebergOrder.ChildOrderOffsetOneofCase.MarketOffset: _market_offset_template = new PriceOffset(_model.MarketOffset); break; + } + } + + public QuantityMeasure display_quantity => _model.DisplayQuantity; + public BTSIcebergOrder.ChildOrderOffsetOneofCase offset_case + { + get => _model.ChildOrderOffsetCase; + set + { + if (value != offset_case) { + _assign_template(); + switch (value) { + case BTSIcebergOrder.ChildOrderOffsetOneofCase.DiffFromLastFill: _model.DiffFromLastFill = _diff_from_last_fill_template; break; + case BTSIcebergOrder.ChildOrderOffsetOneofCase.MarketOffset: _model.MarketOffset = new PriceOffset(_market_offset_template); break; + case BTSIcebergOrder.ChildOrderOffsetOneofCase.None: _model.DiffFromLastFill = 0; _model.MarketOffset = null; break; + } + RaisePropertyChanged(nameof(offset_case), nameof(market_offset), nameof(diff_from_last_fill)); + } + } + } + public double diff_from_last_fill { get => _model.DiffFromLastFill; set => _model.DiffFromLastFill = value; } + public PriceOffset market_offset => _model.MarketOffset; + public BTSWithATickParameters withatick_parameters => _model.WithatickParameters; + public PriceTrigger price_trigger => _model.PriceTrigger; + + // exposing start_time and stop_time properties so the OrderTime [TimeCase]header ComboBox can be in the same ColumnDefinition SharedSizeGroup in the xaml. + // In the xaml 2 OrderTimeControls are used instead of 1 TimeWindowControl (with 2 OrderTimeControls inside)...it makes the layout geometry (lining up TextBlock/ComboBox headers) MUCH easier. + // public BTSTimedWindowParameters time_window => _model.TimedWindowParameters; + public OrderTime start_time => _model.TimedWindowParameters.StartTime; + public OrderTime stop_time => _model.TimedWindowParameters.StopTime; + } + + internal class ChildOrderOffsetDisplayTextConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (value is BTSIcebergOrder.ChildOrderOffsetOneofCase) { + switch ((BTSIcebergOrder.ChildOrderOffsetOneofCase)value) { + case BTSIcebergOrder.ChildOrderOffsetOneofCase.MarketOffset: return "Market"; + case BTSIcebergOrder.ChildOrderOffsetOneofCase.DiffFromLastFill: return "Prev Fill"; + default: return value.ToString(); + } + } + return string.Empty; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/OrderTimeControl.xaml b/src/client/spark/view/Controls/Algo/OrderTimeControl.xaml new file mode 100644 index 000000000..d49c90131 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/OrderTimeControl.xaml @@ -0,0 +1,81 @@ + + 6.0 + 6.0 + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/OrderTimeControl.xaml.cs b/src/client/spark/view/Controls/Algo/OrderTimeControl.xaml.cs new file mode 100644 index 000000000..a5c4151a0 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/OrderTimeControl.xaml.cs @@ -0,0 +1,134 @@ +using bts.spark; +using mbts.spark; +using mbts.ui.shell; +using mbts.ui.utility; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for OrderTimeControl.xaml + /// + public class OrderTimeControl : Control + { + static OrderTimeControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(OrderTimeControl), new FrameworkPropertyMetadata(typeof(OrderTimeControl))); + } + + public override void OnApplyTemplate() { + string hcn = HeaderColName; + if (hcn != null) { + var root = GetTemplateChild("Root") as Grid; + if (root != null) root.ColumnDefinitions[0].SharedSizeGroup = hcn; + } + } + + public static readonly DependencyProperty HeaderColNameProperty = DependencyProperty.Register("HeaderColName", typeof(string), typeof(OrderTimeControl)); + public string HeaderColName { get => GetValue(HeaderColNameProperty) as string; set => SetValue(HeaderColNameProperty, value); } + + #region IsStopTime + public static readonly DependencyProperty IsStopTimeProperty = DependencyProperty.Register("IsStopTime", typeof(bool), typeof(OrderTimeControl), new PropertyMetadata(false, OnIsStopTimeChanged)); + private static void OnIsStopTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(TimeCasesPropertyKey, _get_time_cases((bool)e.NewValue)); } + public bool IsStopTime { get => (bool)GetValue(IsStopTimeProperty); set => SetValue(IsStopTimeProperty, value); } + #endregion + + #region TimeCases (ReadOnly) + private static readonly DependencyPropertyKey TimeCasesPropertyKey = DependencyProperty.RegisterReadOnly("TimeCases", typeof(IEnumerable), typeof(OrderTimeControl), + new PropertyMetadata(_get_time_cases((bool)IsStopTimeProperty.DefaultMetadata.DefaultValue))); + internal static readonly DependencyProperty TimeCasesProperty = TimeCasesPropertyKey.DependencyProperty; + internal IEnumerable TimeCases { get => GetValue(TimeCasesProperty) as IEnumerable; private set => SetValue(TimeCasesPropertyKey, value); } + + private static IEnumerable _get_time_cases(bool is_stop_time) { + return EnumHelper.get_values_except(is_stop_time ? OrderTime.TimeOneofCase.Now : OrderTime.TimeOneofCase.None); + } + #endregion + + #region OrderTime + public static readonly DependencyProperty OrderTimeProperty = DependencyProperty.Register("OrderTime", typeof(OrderTime), typeof(OrderTimeControl), new PropertyMetadata(null, OnOrderTimeChanged, CoerceOrderTime)); + private static object CoerceOrderTime(DependencyObject d, object baseValue) { return baseValue is OrderTime ? baseValue : OrderHelper.Defaults.OrderTime; } + private static void OnOrderTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(OrderTimeVMPropertyKey, new OrderTimeVM((OrderTime)e.NewValue)); } + public OrderTime OrderTime { get => GetValue(OrderTimeProperty) as OrderTime; set => SetValue(OrderTimeProperty, value); } + #endregion + + #region OrderTimeVM (ReadOnly) + private static readonly DependencyPropertyKey OrderTimeVMPropertyKey = DependencyProperty.RegisterReadOnly("OrderTimeVM", typeof(OrderTimeVM), typeof(OrderTimeControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty OrderTimeVMProperty = OrderTimeVMPropertyKey.DependencyProperty; + internal OrderTimeVM OrderTimeVM { get => GetValue(OrderTimeVMProperty) as OrderTimeVM; private set => SetValue(OrderTimeVMPropertyKey, value); } + #endregion + } + + internal class OrderTimeVM : ViewModelBase + { + public OrderTimeVM(OrderTime model) { + _model = model; + _assign_template(); + } + + private readonly OrderTime _model; + private ulong _absolute_time_template = (ulong)DateTime.Now.Ticks, _offset_time_template; + + private void _assign_template() { + switch (_model.TimeCase) { + case OrderTime.TimeOneofCase.AbsoluteTime: _absolute_time_template = _model.AbsoluteTime; break; + case OrderTime.TimeOneofCase.OffsetFromNow: _offset_time_template = _model.OffsetFromNow; break; + } + } + + public OrderTime.TimeOneofCase time_case { + get => _model.TimeCase; + set { + if (value != _model.TimeCase) { + _assign_template(); + switch (value) { + case OrderTime.TimeOneofCase.Now: _model.Now = true; break; + case OrderTime.TimeOneofCase.AbsoluteTime: _model.AbsoluteTime = _absolute_time_template; break; + case OrderTime.TimeOneofCase.OffsetFromNow: _model.OffsetFromNow = _offset_time_template; break; + case OrderTime.TimeOneofCase.None: + _model.Now = false; + _model.AbsoluteTime = 0; + _model.OffsetFromNow = 0; + break; + } + RaisePropertyChanged(nameof(time_case), nameof(absolute_time), nameof(offset_time_mins)); + } + } + } + public DateTime absolute_time { + get => new DateTime((long)_model.AbsoluteTime); + set { + if (time_case == OrderTime.TimeOneofCase.AbsoluteTime) _model.AbsoluteTime = (ulong)value.Ticks; + else _absolute_time_template = (ulong)value.Ticks; + } + } + public double offset_time_mins { + get => TimeSpan.FromTicks((long)_model.OffsetFromNow).TotalMinutes; + set { + if (time_case == OrderTime.TimeOneofCase.OffsetFromNow) _model.OffsetFromNow = (ulong)TimeSpan.FromMinutes(value).Ticks; + else _offset_time_template = (ulong)TimeSpan.FromMinutes(value).Ticks; + } + } + } + + internal class OrderTimeCaseDisplayTextConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (value is OrderTime.TimeOneofCase) { + switch ((OrderTime.TimeOneofCase)value) { + case OrderTime.TimeOneofCase.AbsoluteTime: return "At"; + case OrderTime.TimeOneofCase.OffsetFromNow: return "In"; + default: return value.ToString(); + } + } + return string.Empty; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/PriceOffsetControl.xaml b/src/client/spark/view/Controls/Algo/PriceOffsetControl.xaml new file mode 100644 index 000000000..f8ea8f330 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/PriceOffsetControl.xaml @@ -0,0 +1,25 @@ + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/PriceOffsetControl.xaml.cs b/src/client/spark/view/Controls/Algo/PriceOffsetControl.xaml.cs new file mode 100644 index 000000000..879bbf83a --- /dev/null +++ b/src/client/spark/view/Controls/Algo/PriceOffsetControl.xaml.cs @@ -0,0 +1,42 @@ +using bts.spark; +using mbts.spark; +using System.Windows; +using System.Windows.Controls; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for PriceOffsetControl.xaml + /// + public class PriceOffsetControl : Control + { + static PriceOffsetControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(PriceOffsetControl), new FrameworkPropertyMetadata(typeof(PriceOffsetControl))); + } + + #region PriceOffset + public static readonly DependencyProperty PriceOffsetProperty = DependencyProperty.Register("PriceOffset", typeof(PriceOffset), typeof(PriceOffsetControl), new PropertyMetadata(null, OnPriceOffsetChanged, CoercePriceOffset)); + private static object CoercePriceOffset(DependencyObject d, object baseValue) { return baseValue is PriceOffset ? baseValue : OrderHelper.Defaults.PriceOffset; } + private static void OnPriceOffsetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(PriceOffsetVMPropertyKey, new PriceOffsetVM((PriceOffset)e.NewValue)); } + public PriceOffset PriceOffset { get => GetValue(PriceOffsetProperty) as PriceOffset; set => SetValue(PriceOffsetProperty, value); } + #endregion + + #region PriceOffsetVM (ReadOnly) + private static readonly DependencyPropertyKey PriceOffsetVMPropertyKey = DependencyProperty.RegisterReadOnly("PriceOffsetVM", typeof(PriceOffsetVM), typeof(PriceOffsetControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty PriceOffsetVMProperty = PriceOffsetVMPropertyKey.DependencyProperty; + internal PriceOffsetVM PriceOffsetVM { get => GetValue(PriceOffsetVMProperty) as PriceOffsetVM; private set => SetValue(PriceOffsetVMPropertyKey, value); } + #endregion + } + + public class PriceOffsetVM + { + public PriceOffsetVM(PriceOffset model) { + _model = model; + } + + private readonly PriceOffset _model; + + public int ticks { get => _model.OffsetInTicks; set => _model.OffsetInTicks = value; } + public PriceType.Types.Status price_type { get => _model.PriceType.Status; set => _model.PriceType.Status = value; } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/PriceTriggerControl.xaml b/src/client/spark/view/Controls/Algo/PriceTriggerControl.xaml new file mode 100644 index 000000000..0feda5023 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/PriceTriggerControl.xaml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/PriceTriggerControl.xaml.cs b/src/client/spark/view/Controls/Algo/PriceTriggerControl.xaml.cs new file mode 100644 index 000000000..3b2be3266 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/PriceTriggerControl.xaml.cs @@ -0,0 +1,99 @@ +using bts.spark; +using mbts.spark; +using mbts.ui.shell; +using System; +using System.Globalization; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for PriceTriggerControl.xaml + /// + public class PriceTriggerControl : UserControl + { + static PriceTriggerControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(PriceTriggerControl), new FrameworkPropertyMetadata(typeof(PriceTriggerControl))); + } + + public override void OnApplyTemplate() { + string hcn = HeaderColName; + if (hcn != null) { + var root = GetTemplateChild("Root") as Grid; + if (root != null) root.ColumnDefinitions[0].SharedSizeGroup = hcn; + } + } + + public static readonly DependencyProperty HeaderColNameProperty = DependencyProperty.Register("HeaderColName", typeof(string), typeof(PriceTriggerControl)); + public string HeaderColName { get => GetValue(HeaderColNameProperty) as string; set => SetValue(HeaderColNameProperty, value); } + + #region PriceTrigger + public static readonly DependencyProperty PriceTriggerProperty = DependencyProperty.Register("PriceTrigger", typeof(PriceTrigger), typeof(PriceTriggerControl), new PropertyMetadata(null, OnPriceTriggerChanged, CoercePriceTrigger)); + private static object CoercePriceTrigger(DependencyObject d, object baseValue) { return baseValue is PriceTrigger ? baseValue : OrderHelper.Defaults.PriceTrigger; } + private static void OnPriceTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(PriceTriggerVMPropertyKey, new PriceTriggerVM((PriceTrigger)e.NewValue)); } + public PriceTrigger PriceTrigger { get => GetValue(PriceTriggerProperty) as PriceTrigger; set => SetValue(PriceTriggerProperty, value); } + #endregion + + #region PriceTriggerVM (ReadOnly) + private static readonly DependencyPropertyKey PriceTriggerVMPropertyKey = DependencyProperty.RegisterReadOnly("PriceTriggerVM", typeof(PriceTriggerVM), typeof(PriceTriggerControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty PriceTriggerVMProperty = PriceTriggerVMPropertyKey.DependencyProperty; + internal PriceTriggerVM PriceTriggerVM { get => GetValue(PriceTriggerVMProperty) as PriceTriggerVM; private set => SetValue(PriceTriggerVMPropertyKey, value); } + #endregion + } + + internal class PriceTriggerVM : ViewModelBase + { + public PriceTriggerVM(PriceTrigger model) { + _model = model; + _assign_template(); + } + + private readonly PriceTrigger _model; + private AbsolutePriceTrigger _absolute_trigger_template = OrderHelper.Defaults.AbsolutePriceTrigger; + private TrailingTrigger _trailing_trigger_template = OrderHelper.Defaults.TrailingTrigger; + + private void _assign_template() { + switch(trigger_case) { + case PriceTrigger.TriggerOneofCase.AbsolutePriceTrigger: _absolute_trigger_template = new AbsolutePriceTrigger(_model.AbsolutePriceTrigger); break; + case PriceTrigger.TriggerOneofCase.TrailingTrigger: _trailing_trigger_template = new TrailingTrigger(_model.TrailingTrigger); break; + } + } + + public AbsolutePriceTrigger absolute_trigger => _model.AbsolutePriceTrigger; + public TrailingTrigger trailing_trigger => _model.TrailingTrigger; + public PriceTrigger.TriggerOneofCase trigger_case { + get => _model.TriggerCase; + set { + if (value != trigger_case) { + _assign_template(); + switch (value) { + case PriceTrigger.TriggerOneofCase.AbsolutePriceTrigger: _model.AbsolutePriceTrigger = new AbsolutePriceTrigger(_absolute_trigger_template); break; + case PriceTrigger.TriggerOneofCase.TrailingTrigger: _model.TrailingTrigger = new TrailingTrigger(_trailing_trigger_template); break; + case PriceTrigger.TriggerOneofCase.None: _model.AbsolutePriceTrigger = null; _model.TrailingTrigger = null; break; + } + RaisePropertyChanged(nameof(trigger_case), nameof(absolute_trigger), nameof(trailing_trigger)); + } + } + } + } + + internal class PriceTriggerDisplayTextConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (value is PriceTrigger.TriggerOneofCase) { + switch((PriceTrigger.TriggerOneofCase)value) { + case PriceTrigger.TriggerOneofCase.AbsolutePriceTrigger: return "Fixed"; + case PriceTrigger.TriggerOneofCase.TrailingTrigger: return "Trailing"; + default: return value.ToString(); + } + } + return string.Empty; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/QuantityMeasureControl.xaml b/src/client/spark/view/Controls/Algo/QuantityMeasureControl.xaml new file mode 100644 index 000000000..809db1e95 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/QuantityMeasureControl.xaml @@ -0,0 +1,38 @@ + + + + + + + + + + + + + + + + + + + + + + + : + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/QuantityMeasureControl.xaml.cs b/src/client/spark/view/Controls/Algo/QuantityMeasureControl.xaml.cs new file mode 100644 index 000000000..c0818578a --- /dev/null +++ b/src/client/spark/view/Controls/Algo/QuantityMeasureControl.xaml.cs @@ -0,0 +1,77 @@ +using bts.spark; +using mbts.spark; +using mbts.ui.shell; +using System.Windows; +using System.Windows.Controls; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for QuantityMeasure.xaml + /// + public class QuantityMeasureControl : Control + { + static QuantityMeasureControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(QuantityMeasureControl), new FrameworkPropertyMetadata(typeof(QuantityMeasureControl))); + } + + public override void OnApplyTemplate() { + string hcn = HeaderColName; + if (hcn != null) { + var root = GetTemplateChild("Root") as Grid; + if (root != null) root.ColumnDefinitions[0].SharedSizeGroup = hcn; + } + } + + public static readonly DependencyProperty HeaderColNameProperty = DependencyProperty.Register("HeaderColName", typeof(string), typeof(QuantityMeasureControl)); + public string HeaderColName { get => GetValue(HeaderColNameProperty) as string; set => SetValue(HeaderColNameProperty, value); } + + #region QuantityMeasure + public static readonly DependencyProperty QuantityMeasureProperty = DependencyProperty.Register("QuantityMeasure", typeof(QuantityMeasure), typeof(QuantityMeasureControl), new PropertyMetadata(null, OnQuantityMeasureChanged, CoerceQuantityMeasure)); + private static object CoerceQuantityMeasure(DependencyObject d, object baseValue) { return baseValue is QuantityMeasure ? baseValue : OrderHelper.Defaults.QuantityMeasure; } + private static void OnQuantityMeasureChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(QuantityMeasureVMPropertyKey, new QuantityMeasureVM((QuantityMeasure)e.NewValue)); } + public QuantityMeasure QuantityMeasure { get => GetValue(QuantityMeasureProperty) as QuantityMeasure; set => SetValue(QuantityMeasureProperty, value); } + #endregion + + #region QuantityMeasureVM (ReadOnly) + private static readonly DependencyPropertyKey QuantityMeasureVMPropertyKey = DependencyProperty.RegisterReadOnly("QuantityMeasureVM", typeof(QuantityMeasureVM), typeof(QuantityMeasureControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty QuantityMeasureVMProperty = QuantityMeasureVMPropertyKey.DependencyProperty; + internal QuantityMeasureVM QuantityMeasureVM { get => GetValue(QuantityMeasureVMProperty) as QuantityMeasureVM; private set => SetValue(QuantityMeasureVMPropertyKey, value); } + #endregion + } + + internal class QuantityMeasureVM : ViewModelBase + { + public QuantityMeasureVM(QuantityMeasure model) { + _model = model; + _assign_template(); + } + + private readonly QuantityMeasure _model; + private uint _absolute_template; + private double _ratio_template; + + private void _assign_template() { + switch(_model.QuantityCase) { + case QuantityMeasure.QuantityOneofCase.Absolute: _absolute_template = _model.Absolute; break; + case QuantityMeasure.QuantityOneofCase.Ratio: _ratio_template = _model.Ratio; break; + } + } + + public QuantityMeasure.QuantityOneofCase quantity_case { + get => _model.QuantityCase; + set { + if (value != quantity_case) { + _assign_template(); + switch (value) { + case QuantityMeasure.QuantityOneofCase.Absolute: _model.Absolute = _absolute_template; break; + case QuantityMeasure.QuantityOneofCase.Ratio: _model.Ratio = _ratio_template; break; + } + RaisePropertyChanged(nameof(quantity_case), nameof(absolute), nameof(ratio)); + } + } + } + public uint absolute { get => _model.Absolute; set => _model.Absolute = value; } + public double ratio { get => _model.Ratio; set => _model.Ratio = value; } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/QuantityTriggerControl.xaml b/src/client/spark/view/Controls/Algo/QuantityTriggerControl.xaml new file mode 100644 index 000000000..bc7b6570c --- /dev/null +++ b/src/client/spark/view/Controls/Algo/QuantityTriggerControl.xaml @@ -0,0 +1,37 @@ + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/QuantityTriggerControl.xaml.cs b/src/client/spark/view/Controls/Algo/QuantityTriggerControl.xaml.cs new file mode 100644 index 000000000..246a0e949 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/QuantityTriggerControl.xaml.cs @@ -0,0 +1,72 @@ +using bts.spark; +using mbts.spark; +using System; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; +using System.Globalization; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for QuantityTriggerControl.xaml + /// + public class QuantityTriggerControl : Control + { + static QuantityTriggerControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(QuantityTriggerControl), new FrameworkPropertyMetadata(typeof(QuantityTriggerControl))); + } + + #region QuantityTrigger + public static readonly DependencyProperty QuantityTriggerProperty = DependencyProperty.Register("QuantityTrigger", typeof(QuantityTrigger), typeof(QuantityTriggerControl), new PropertyMetadata(null, OnQuantityTriggerChanged, CoerceQuantityTrigger)); + private static object CoerceQuantityTrigger(DependencyObject d, object baseValue) { return baseValue is QuantityTrigger ? baseValue : OrderHelper.Defaults.QuantityTrigger; } + private static void OnQuantityTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(QuantityTriggerVMPropertyKey, new QuantityTriggerVM((QuantityTrigger)e.NewValue)); } + public QuantityTrigger QuantityTrigger { get => GetValue(QuantityTriggerProperty) as QuantityTrigger; set => SetValue(QuantityTriggerProperty, value); } + #endregion + + #region QuantityTriggerVM (ReadOnly) + private static readonly DependencyPropertyKey QuantityTriggerVMPropertyKey = DependencyProperty.RegisterReadOnly("QuantityTriggerVM", typeof(QuantityTriggerVM), typeof(QuantityTriggerControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty QuantityTriggerVMProperty = QuantityTriggerVMPropertyKey.DependencyProperty; + internal QuantityTriggerVM QuantityTriggerVM { get => GetValue(QuantityTriggerVMProperty) as QuantityTriggerVM; private set => SetValue(QuantityTriggerVMPropertyKey, value); } + #endregion + } + + internal class QuantityTriggerVM + { + public QuantityTriggerVM(QuantityTrigger model) { + _model = model; + } + + private readonly QuantityTrigger _model; + + public QuantityTrigger.RelationOneofCase relation { + get => _model.RelationCase; + set { + switch(value) { + case QuantityTrigger.RelationOneofCase.GreaterThanEqualto: _model.GreaterThanEqualto = true; break; + case QuantityTrigger.RelationOneofCase.LessThanEqualto: _model.LessThanEqualto = true; break; + } + } + } + public QuantityMeasure quantity_measure => _model.QuantityMeasure; + public uint threshold_quantity { get => _model.ThresholdQuantity; set => _model.ThresholdQuantity = value; } + } + + internal class QuantityTriggerRelationDisplayTextConverter : IValueConverter + { + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { + if (value is QuantityTrigger.RelationOneofCase) { + switch ((QuantityTrigger.RelationOneofCase)value) { + case QuantityTrigger.RelationOneofCase.GreaterThanEqualto: return "Minimum"; + case QuantityTrigger.RelationOneofCase.LessThanEqualto: return "Maximum"; + default: return value.ToString(); + } + } + return string.Empty; + } + + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { + throw new NotImplementedException(); + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/TimeWindowControl.xaml b/src/client/spark/view/Controls/Algo/TimeWindowControl.xaml new file mode 100644 index 000000000..179b17af0 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/TimeWindowControl.xaml @@ -0,0 +1,49 @@ + + + + + 6.0 + 6.0 + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/TimeWindowControl.xaml.cs b/src/client/spark/view/Controls/Algo/TimeWindowControl.xaml.cs new file mode 100644 index 000000000..134a107f7 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/TimeWindowControl.xaml.cs @@ -0,0 +1,43 @@ +using bts.spark; +using mbts.spark; +using mbts.ui.shell; +using System.Windows; +using System.Windows.Controls; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for TimeWindowControl.xaml + /// + public class TimeWindowControl : Control + { + static TimeWindowControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(TimeWindowControl), new FrameworkPropertyMetadata(typeof(TimeWindowControl))); + } + + #region TimeWindow + public static readonly DependencyProperty TimeWindowProperty = DependencyProperty.Register("TimeWindow", typeof(BTSTimedWindowParameters), typeof(TimeWindowControl), new PropertyMetadata(null, OnTimeWindowChanged, CoerceTimeWindow)); + private static object CoerceTimeWindow(DependencyObject d, object baseValue) { return baseValue is BTSTimedWindowParameters ? baseValue : OrderHelper.Defaults.TimeWindow; } + private static void OnTimeWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(TimeWindowVMPropertyKey, new TimeWindowVM((BTSTimedWindowParameters)e.NewValue)); } + public BTSTimedWindowParameters TimeWindow { get => GetValue(TimeWindowProperty) as BTSTimedWindowParameters; set => SetValue(TimeWindowProperty, value); } + #endregion + + #region TimeWindowVM (ReadOnly) + private static readonly DependencyPropertyKey TimeWindowVMPropertyKey = DependencyProperty.RegisterReadOnly("TimeWindowVM", typeof(TimeWindowVM), typeof(TimeWindowControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty TimeWindowVMProperty = TimeWindowVMPropertyKey.DependencyProperty; + internal TimeWindowVM TimeWindowVM { get => GetValue(TimeWindowVMProperty) as TimeWindowVM; private set => SetValue(TimeWindowVMPropertyKey, value); } + #endregion + } + + internal class TimeWindowVM : ViewModelBase + { + public TimeWindowVM(BTSTimedWindowParameters model) { + _model = model; + } + + private readonly BTSTimedWindowParameters _model; + + public OrderTime start_time => _model.StartTime; + public OrderTime stop_time => _model.StopTime; + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/TrailingPriceTriggerControl.xaml b/src/client/spark/view/Controls/Algo/TrailingPriceTriggerControl.xaml new file mode 100644 index 000000000..c6860dae3 --- /dev/null +++ b/src/client/spark/view/Controls/Algo/TrailingPriceTriggerControl.xaml @@ -0,0 +1,31 @@ + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Algo/TrailingPriceTriggerControl.xaml.cs b/src/client/spark/view/Controls/Algo/TrailingPriceTriggerControl.xaml.cs new file mode 100644 index 000000000..4ca6d13cf --- /dev/null +++ b/src/client/spark/view/Controls/Algo/TrailingPriceTriggerControl.xaml.cs @@ -0,0 +1,51 @@ +using bts.spark; +using mbts.spark; +using System.Windows; +using System.Windows.Controls; + +namespace mbts.ui.spark.algo +{ + /// + /// Interaction logic for TrailingPriceTriggerControl.xaml + /// + public class TrailingPriceTriggerControl : Control + { + static TrailingPriceTriggerControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(TrailingPriceTriggerControl), new FrameworkPropertyMetadata(typeof(TrailingPriceTriggerControl))); + } + + #region TrailingTrigger + public static readonly DependencyProperty TrailingTriggerProperty = DependencyProperty.Register("TrailingTrigger", typeof(TrailingTrigger), typeof(TrailingPriceTriggerControl), new PropertyMetadata(null, OnTrailingTriggerChanged, CoerceTrailingTrigger)); + private static object CoerceTrailingTrigger(DependencyObject d, object baseValue) { return baseValue is TrailingTrigger ? baseValue : OrderHelper.Defaults.TrailingTrigger; } + private static void OnTrailingTriggerChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(TrailingTriggerVMPropertyKey, new TrailingPriceTriggerVM((TrailingTrigger)e.NewValue)); } + public TrailingTrigger TrailingTrigger { get => GetValue(TrailingTriggerProperty) as TrailingTrigger; set => SetValue(TrailingTriggerProperty, value); } + #endregion + + #region TrailingTriggerVM (ReadOnly) + private static readonly DependencyPropertyKey TrailingTriggerVMPropertyKey = DependencyProperty.RegisterReadOnly("TrailingTriggerVM", typeof(TrailingPriceTriggerVM), typeof(TrailingPriceTriggerControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty TrailingTriggerVMProperty = TrailingTriggerVMPropertyKey.DependencyProperty; + internal TrailingPriceTriggerVM TrailingTriggerVM { get => GetValue(TrailingTriggerVMProperty) as TrailingPriceTriggerVM; private set => SetValue(TrailingTriggerVMPropertyKey, value); } + #endregion + } + + public class TrailingPriceTriggerVM + { + public TrailingPriceTriggerVM(TrailingTrigger model) { + _model = model; + } + + private readonly TrailingTrigger _model; + + public PriceType.Types.Status price_type { get => _model.PriceType.Status; set => _model.PriceType.Status = value; } + public int ticks { get => _model.NumberOfTicks; set => _model.NumberOfTicks = value; } + public TrailingTrigger.TriggerTypeOneofCase trigger_type { + get => _model.TriggerTypeCase; + set { + switch (value) { + case TrailingTrigger.TriggerTypeOneofCase.Stop: _model.Stop = true; break; + case TrailingTrigger.TriggerTypeOneofCase.InvserseStop: _model.InvserseStop = true; break; + } + } + } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Controls/NumberPad.xaml b/src/client/spark/view/Controls/NumberPad.xaml similarity index 98% rename from src/client/spark/mspark/Controls/NumberPad.xaml rename to src/client/spark/view/Controls/NumberPad.xaml index 90fcd8253..a4f9f78ab 100644 --- a/src/client/spark/mspark/Controls/NumberPad.xaml +++ b/src/client/spark/view/Controls/NumberPad.xaml @@ -1,83 +1,83 @@ - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Controls/NumberPad.xaml.cs b/src/client/spark/view/Controls/NumberPad.xaml.cs similarity index 100% rename from src/client/spark/mspark/Controls/NumberPad.xaml.cs rename to src/client/spark/view/Controls/NumberPad.xaml.cs diff --git a/src/client/spark/view/Controls/ObjectEditor/ObjectEditor.xaml b/src/client/spark/view/Controls/ObjectEditor/ObjectEditor.xaml index 869736702..052f248c8 100644 --- a/src/client/spark/view/Controls/ObjectEditor/ObjectEditor.xaml +++ b/src/client/spark/view/Controls/ObjectEditor/ObjectEditor.xaml @@ -1,88 +1,96 @@ - - - - + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/ObjectEditor/ObjectEditor.xaml.cs b/src/client/spark/view/Controls/ObjectEditor/ObjectEditor.xaml.cs index 816b2e19e..f7ed93763 100644 --- a/src/client/spark/view/Controls/ObjectEditor/ObjectEditor.xaml.cs +++ b/src/client/spark/view/Controls/ObjectEditor/ObjectEditor.xaml.cs @@ -26,6 +26,11 @@ namespace mbts.ui.controls public object EditableObject { get => GetValue(EditableObjectProperty); set => SetValue(EditableObjectProperty, value); } #endregion + #region CustomDataTemplates + public static readonly DependencyProperty CustomDataTemplatesProperty = DependencyProperty.Register("CustomDataTemplates", typeof(IList), typeof(ObjectEditor)); + public IList CustomDataTemplates { get => GetValue(CustomDataTemplatesProperty) as IList; set => SetValue(CustomDataTemplatesProperty, value); } + #endregion + #region DataTemplates public static readonly DependencyProperty DataTemplatesProperty = DependencyProperty.Register("DataTemplates", typeof(IList), typeof(ObjectEditor)); public IList DataTemplates { get => GetValue(DataTemplatesProperty) as IList; set => SetValue(DataTemplatesProperty, value); } @@ -41,6 +46,7 @@ namespace mbts.ui.controls public ObjectEditor() { PropertyItemTemplateSelector = new MyPropertyItemTemplateSelector(this); + CustomDataTemplates = new List(); } private abstract class PropertyEditorBase : ViewModelBase @@ -104,18 +110,21 @@ namespace mbts.ui.controls if (pe != null) { var override_template = _owner.TryFindResource(pe.PropertyType) as DataTemplate; if (override_template != null) return override_template; - var templates = _owner.DataTemplates.OfType().ToList(); - if (!string.IsNullOrEmpty(pe.TemplateKey)) { - var match = templates.FirstOrDefault(dt => pe.TemplateKey.Equals(dt.DataTemplateKey)); - if (match != null) return match; - } - var rule_templates = templates.OfType(); - var rule_match = rule_templates.FirstOrDefault(rt => rt.Rule.should_use_template(pe)); - if (rule_match != null) return rule_match; - else return templates.FirstOrDefault(dt => pe.PropertyType.Equals(dt.DataType as Type)) ?? templates.FirstOrDefault(dt => dt.DataType == null); + return _find_match(pe, (_owner.CustomDataTemplates ?? new List()).OfType().ToList()) ?? _find_match(pe, (_owner.DataTemplates ?? new List()).OfType()); } return null; } + + private DataTemplate _find_match(PropertyEditorBase pe, IEnumerable templates) { + if (!string.IsNullOrEmpty(pe.TemplateKey)) { + var match = templates.FirstOrDefault(dt => pe.TemplateKey.Equals(dt.DataTemplateKey)); + if (match != null) return match; + } + var rule_templates = templates.OfType(); + var rule_match = rule_templates.FirstOrDefault(rt => rt.Rule.should_use_template(pe)); + if (rule_match != null) return rule_match; + else return templates.FirstOrDefault(dt => pe.PropertyType.Equals(dt.DataType as Type)) ?? templates.FirstOrDefault(dt => dt.DataType == null); + } } private class PropertyItemsConverter : IValueConverter diff --git a/src/client/spark/view/Controls/Popup/PopupControl.xaml b/src/client/spark/view/Controls/Popup/PopupControl.xaml new file mode 100644 index 000000000..104ebca0d --- /dev/null +++ b/src/client/spark/view/Controls/Popup/PopupControl.xaml @@ -0,0 +1,63 @@ + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/Popup/PopupControl.xaml.cs b/src/client/spark/view/Controls/Popup/PopupControl.xaml.cs new file mode 100644 index 000000000..88c4eb23b --- /dev/null +++ b/src/client/spark/view/Controls/Popup/PopupControl.xaml.cs @@ -0,0 +1,79 @@ +using System; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Media; + +namespace mbts.ui.controls +{ + /// + /// Interaction logic for PopupControl.xaml + /// + public class PopupControl : HeaderedContentControl + { + static PopupControl() { + DefaultStyleKeyProperty.OverrideMetadata(typeof(PopupControl), new FrameworkPropertyMetadata(typeof(PopupControl))); + } + + enum PopupState { Opening, Open, Closing, Closed } + + #region PopupPlacement + public static readonly DependencyProperty PopupPlacementProperty = DependencyProperty.Register("PopupPlacement", typeof(PlacementMode), typeof(PopupControl), new PropertyMetadata(PlacementMode.Right, OnPopupPlacementChanged)); + private static void OnPopupPlacementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { d.SetValue(IsOpenTransformPropertyKey, _get_is_open_transform((PlacementMode)e.NewValue)); } + public PlacementMode PopupPlacement { get => (PlacementMode)GetValue(PopupPlacementProperty); set => SetValue(PopupPlacementProperty, value); } + #endregion + + public static readonly DependencyProperty PopupContainerStyleProperty = DependencyProperty.Register("PopupContainerStyle", typeof(Style), typeof(PopupControl)); + public Style PopupContainerStyle { get => GetValue(PopupContainerStyleProperty) as Style; set => SetValue(PopupContainerStyleProperty, value); } + + public static readonly DependencyProperty IsOpenProperty = DependencyProperty.Register("IsOpen", typeof(bool), typeof(PopupControl), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + public bool IsOpen { get => (bool)GetValue(IsOpenProperty); set => SetValue(IsOpenProperty, value); } + + #region IsOpenTransform (ReadOnly) + private static readonly DependencyPropertyKey IsOpenTransformPropertyKey = DependencyProperty.RegisterReadOnly("IsOpenTransform", typeof(ScaleTransform), typeof(PopupControl), + new PropertyMetadata(_get_is_open_transform((PlacementMode)PopupPlacementProperty.DefaultMetadata.DefaultValue))); + internal static readonly DependencyProperty IsOpenTransformProperty = IsOpenTransformPropertyKey.DependencyProperty; + public ScaleTransform IsOpenTransform { get => GetValue(IsOpenTransformProperty) as ScaleTransform; set => SetValue(IsOpenTransformPropertyKey, value); } + + private static ScaleTransform _get_is_open_transform(PlacementMode popup_placement) { + switch (popup_placement) { + case PlacementMode.Left: return new ScaleTransform(-1, 1, 1.75, 0); + case PlacementMode.Right: return new ScaleTransform(-1, 1, 1.75, 0); + case PlacementMode.Top: return new ScaleTransform(1, -1, 0, 1.75); + case PlacementMode.Bottom: return new ScaleTransform(1, -1, 0, 1.75); + default: return null; + } + } + #endregion + + #region TogglePopupCommand (ReadOnly) + private static readonly DependencyPropertyKey TogglePopupCommandPropertyKey = DependencyProperty.RegisterReadOnly("TogglePopupCommand", typeof(ICommand), typeof(PopupControl), new PropertyMetadata(null)); + internal static readonly DependencyProperty TogglePopupCommandProperty = TogglePopupCommandPropertyKey.DependencyProperty; + internal ICommand TogglePopupCommand { get => GetValue(TogglePopupCommandProperty) as ICommand; private set => SetValue(TogglePopupCommandPropertyKey, value); } + #endregion + + public PopupControl() { + TogglePopupCommand = new DelegateCommand(() => { + if (_ignore_open_command) _ignore_open_command = false; + else IsOpen = true; + }); + } + + private IDisposable _popup_hook; + private Button _button; + private bool _ignore_open_command; + + public override void OnApplyTemplate() { + Disposable.dispose(ref _popup_hook); + _button = (Button)GetTemplateChild("button"); + var popup = (Popup)GetTemplateChild("popup"); + popup.Closed += Popup_Closed; + _popup_hook = Disposable.Create(() => popup.Closed -= Popup_Closed); + } + + private void Popup_Closed(object sender, EventArgs e) { + if (_button.IsMouseOver) _ignore_open_command = true; + } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Controls/PriceEntryControl.xaml b/src/client/spark/view/Controls/PriceEntryControl.xaml index b35dac606..5e75dd2b7 100644 --- a/src/client/spark/view/Controls/PriceEntryControl.xaml +++ b/src/client/spark/view/Controls/PriceEntryControl.xaml @@ -1,108 +1,19 @@ - - - F1 M 0,0 L 2.667,2.66665 L 5.3334,0 L 5.3334,-1.78168 L 2.6667,0.88501 L0,-1.78168 L0,0 Z - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/view/Controls/PriceEntryControl.xaml.cs b/src/client/spark/view/Controls/PriceEntryControl.xaml.cs index 411bc1e0f..f4485445d 100644 --- a/src/client/spark/view/Controls/PriceEntryControl.xaml.cs +++ b/src/client/spark/view/Controls/PriceEntryControl.xaml.cs @@ -1,161 +1,73 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using bts.api; +using mbts.spark; +using mbts.ui.spark.converters; using System.Windows; using System.Windows.Controls; -using System.Windows.Controls.Primitives; using System.Windows.Input; -using System.Windows.Shapes; -namespace mbts.ui.controls +namespace mbts.ui.spark { - public class PriceEntryControl : Control + /// + /// Interaction logic for PriceEntryControl.xaml + /// + internal class PriceEntryControl : Control { - private Popup _popup; - static PriceEntryControl() { DefaultStyleKeyProperty.OverrideMetadata(typeof(PriceEntryControl), new FrameworkPropertyMetadata(typeof(PriceEntryControl))); } + #region Value + public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(PriceEntryControl), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)); + public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); } + #endregion + + #region TickUp + private static readonly DependencyPropertyKey TickUpCommandPropertyKey = DependencyProperty.RegisterReadOnly("TickUpCommand", typeof(ICommand), typeof(PriceEntryControl), new PropertyMetadata(null)); + public static readonly DependencyProperty TickUpCommandProperty = TickUpCommandPropertyKey.DependencyProperty; + public ICommand TickUpCommand { get => GetValue(TickUpCommandProperty) as ICommand; private set => SetValue(TickUpCommandPropertyKey, value); } + #endregion + + #region TickDown + private static readonly DependencyPropertyKey TickDownCommandPropertyKey = DependencyProperty.RegisterReadOnly("TickDownCommand", typeof(ICommand), typeof(PriceEntryControl), new PropertyMetadata(null)); + public static readonly DependencyProperty TickDownCommandProperty = TickDownCommandPropertyKey.DependencyProperty; + 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(ContractSpecification), typeof(PriceEntryControl), new PropertyMetadata(TickUtils.DefaultSpec, OnContractSpecChanged)); + private static void OnContractSpecChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((PriceEntryControl)d)._update_text_binding(); } + public ContractSpecification ContractSpec { get => GetValue(ContractSpecProperty) as ContractSpecification; set => SetValue(ContractSpecProperty, value); } + #endregion + public PriceEntryControl() { - this.Unloaded += PriceEntryControl_Unloaded; + TickUpCommand = new DelegateCommand(_tick_up); + TickDownCommand = new DelegateCommand(_tick_down); } - # region Make the popup track with the window when it moves - void PriceEntryControl_Unloaded(object sender, RoutedEventArgs e) { - if (_popup != null) { - var window = Window.GetWindow(this); - if (window != null) { - window.LocationChanged -= window_LocationChanged; + private TextBox _text; + + private void _tick_up() { SetCurrentValue(ValueProperty, ContractSpec.tickup(Value)); } + private void _tick_down() { SetCurrentValue(ValueProperty, ContractSpec.tickdown(Value)); } + + private void _update_text_binding() { + if (_text != null) { + var spec = ContractSpec; + if (spec != null) { + var be = _text.GetBindingExpression(TextBox.TextProperty); + if (be != null) { + var converter = be.ParentBinding.Converter as TickDisplayTwoWayConverter; + if (converter != null) { + converter.ContractSpec = spec; + be.UpdateTarget(); + } + } } } } public override void OnApplyTemplate() { - _popup = GetTemplateChild("_popup") as Popup; - if (_popup != null) { - var window = Window.GetWindow(this); - if (window != null) { - window.LocationChanged += window_LocationChanged; - } - } + _text = GetTemplateChild("_text") as TextBox; + _update_text_binding(); } - - void window_LocationChanged(object sender, EventArgs e) { - if (_popup != null) { - _popup.HorizontalOffset += 1; - _popup.HorizontalOffset -= 1; - } - } - #endregion - - - public string Price { - get { return (string)GetValue(PriceProperty); } - set { SetValue(PriceProperty, value); } - } - public static readonly DependencyProperty PriceProperty = - DependencyProperty.Register("Price", typeof(string), typeof(PriceEntryControl), - new PropertyMetadata("", new PropertyChangedCallback(OnPriceChanged), new CoerceValueCallback(OnCoercePrice))); - - private static void OnPriceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } - private static object OnCoercePrice(DependencyObject d, object baseValue) { - PriceEntryControl pe = (PriceEntryControl)d; - string value = baseValue.ToString(); - // Remove duplicate decimals - while (value.IndexOf(pe.DecimalSeparator) != value.LastIndexOf(pe.DecimalSeparator)) { - var index = value.LastIndexOf(pe.DecimalSeparator); - value = value.Substring(0, index) + value.Substring(index + pe.DecimalSeparator.Length); - } - // Remove non-numeric characters - StringBuilder sb = new StringBuilder(); - sb = value.Where(c => pe.DecimalSeparator.Contains(c) || char.IsNumber(c)).Aggregate(sb, (str, ch) => str.Append(ch)); - - return sb.ToString(); - } - - #region Price Changes - public ICommand TickUpCommand { - get { return (ICommand)GetValue(TickUpCommandProperty); } - set { SetValue(TickUpCommandProperty, value); } - } - public static readonly DependencyProperty TickUpCommandProperty = - DependencyProperty.Register("TickUpCommand", typeof(ICommand), typeof(PriceEntryControl), new PropertyMetadata(null)); - - public ICommand TickDownCommand { - get { return (ICommand)GetValue(TickDownCommandProperty); } - set { SetValue(TickDownCommandProperty, value); } - } - public static readonly DependencyProperty TickDownCommandProperty = - DependencyProperty.Register("TickDownCommand", typeof(ICommand), typeof(PriceEntryControl), new PropertyMetadata(null)); - - public ICommand ChangeSignCommand { - get { return (ICommand)GetValue(ChangeSignCommandProperty); } - set { SetValue(ChangeSignCommandProperty, value); } - } - public static readonly DependencyProperty ChangeSignCommandProperty = - DependencyProperty.Register("ChangeSignCommand", typeof(ICommand), typeof(PriceEntryControl), new PropertyMetadata(null)); - - public string DecimalSeparator { - get { return (string)GetValue(DecimalSeparatorProperty); } - set { SetValue(DecimalSeparatorProperty, value); } - } - public static readonly DependencyProperty DecimalSeparatorProperty = - DependencyProperty.Register("DecimalSeparator", typeof(string), typeof(PriceEntryControl), new PropertyMetadata(".")); - - #endregion - - } - - public class Calculator : Control - { - static Calculator() { - DefaultStyleKeyProperty.OverrideMetadata(typeof(Calculator), new FrameworkPropertyMetadata(typeof(Calculator))); - EventManager.RegisterClassHandler(typeof(Calculator), Button.ClickEvent, new RoutedEventHandler(OnButtonClick)); - } - public Calculator() { - - } - - private static void OnButtonClick(object sender, RoutedEventArgs args) { - var calculator = (Calculator)sender; - var button = args.OriginalSource as Button; - if (button != null) { - calculator.button_clicked(button); - } - } - - private void button_clicked(Button b) { - string content = b.Content.ToString(); - if (content == "CE") { - this.Price = string.Empty; - return; - } - this.Price += content; - } - - protected override void OnKeyDown(KeyEventArgs e) { - char c = (char)KeyInterop.VirtualKeyFromKey(e.Key); - if (char.IsNumber(c) || c.ToString() == this.DecimalSeparator) { - this.Price += c; - } - } - - public string Price { - get { return (string)GetValue(PriceProperty); } - set { SetValue(PriceProperty, value); } - } - - public static readonly DependencyProperty PriceProperty = PriceEntryControl.PriceProperty.AddOwner(typeof(Calculator)); - - public string DecimalSeparator { - get { return (string)GetValue(DecimalSeparatorProperty); } - set { SetValue(DecimalSeparatorProperty, value); } - } - public static readonly DependencyProperty DecimalSeparatorProperty = PriceEntryControl.DecimalSeparatorProperty.AddOwner(typeof(Calculator)); - - } } diff --git a/src/client/spark/mspark/Controls/SecuritySelectorControl/SecurityCollectionView.cs b/src/client/spark/view/Controls/SecuritySelectorControl/SecurityCollectionView.cs similarity index 100% rename from src/client/spark/mspark/Controls/SecuritySelectorControl/SecurityCollectionView.cs rename to src/client/spark/view/Controls/SecuritySelectorControl/SecurityCollectionView.cs diff --git a/src/client/spark/mspark/Controls/SecuritySelectorControl/SecurityItem.cs b/src/client/spark/view/Controls/SecuritySelectorControl/SecurityItem.cs similarity index 100% rename from src/client/spark/mspark/Controls/SecuritySelectorControl/SecurityItem.cs rename to src/client/spark/view/Controls/SecuritySelectorControl/SecurityItem.cs diff --git a/src/client/spark/mspark/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml b/src/client/spark/view/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml similarity index 97% rename from src/client/spark/mspark/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml rename to src/client/spark/view/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml index 11d2b6130..fba0f2d70 100644 --- a/src/client/spark/mspark/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml +++ b/src/client/spark/view/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml @@ -1,201 +1,201 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/client/spark/mspark/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml.cs b/src/client/spark/view/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml.cs similarity index 100% rename from src/client/spark/mspark/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml.cs rename to src/client/spark/view/Controls/SecuritySelectorControl/SecuritySelectorControl.xaml.cs diff --git a/src/client/spark/mspark/Utilities/Converters/AlgoTypeDisplayBrushConverter.cs b/src/client/spark/view/Converters/AlgoTypeDisplayBrushConverter.cs similarity index 100% rename from src/client/spark/mspark/Utilities/Converters/AlgoTypeDisplayBrushConverter.cs rename to src/client/spark/view/Converters/AlgoTypeDisplayBrushConverter.cs diff --git a/src/client/spark/mspark/Utilities/Converters/AlgoTypeDisplayTextConverter.cs b/src/client/spark/view/Converters/AlgoTypeDisplayTextConverter.cs similarity index 100% rename from src/client/spark/mspark/Utilities/Converters/AlgoTypeDisplayTextConverter.cs rename to src/client/spark/view/Converters/AlgoTypeDisplayTextConverter.cs diff --git a/src/client/spark/view/Converters/Boolean/DynamicValueEquals.cs b/src/client/spark/view/Converters/Boolean/DynamicValueEquals.cs new file mode 100644 index 000000000..112d4970e --- /dev/null +++ b/src/client/spark/view/Converters/Boolean/DynamicValueEquals.cs @@ -0,0 +1,25 @@ +using mbts.utils; +using System; +using System.Globalization; +using System.Windows.Data; + +namespace mbts.ui.converters +{ + public class DynamicValueEquals : IMultiValueConverter { + public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { + if (values.Length >= 2) { + object obj = values[0]; + for (int i = 1; i < values.Length; i++) if (!ValuesEqual(obj, values[i])) return false; + return true; + } + throw new ArgumentException("values"); + } + public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotImplementedException(); } + protected virtual bool ValuesEqual(object x, object y) { return object.Equals(x, y); } + } + + public class DynamicValueEquals : DynamicValueEquals { + protected override bool ValuesEqual(object x, object y) { return ObjectHelper.try_convert(x, out T tx) && ObjectHelper.try_convert(y, out T ty) && ValuesEqual(tx, ty); } + protected virtual bool ValuesEqual(T x, T y) { return CompareUtils.NullCheckEquals(x, y); } + } +} \ No newline at end of file diff --git a/src/client/spark/view/Converters/Boolean/StaticValueEqualsConverter.cs b/src/client/spark/view/Converters/Boolean/StaticValueEqualsConverter.cs new file mode 100644 index 000000000..97fde92b6 --- /dev/null +++ b/src/client/spark/view/Converters/Boolean/StaticValueEqualsConverter.cs @@ -0,0 +1,18 @@ +using System; +using System.Globalization; +using System.Windows.Data; + +namespace mbts.ui.converters +{ + public class StaticValueEqualsConverter : IValueConverter { + public object Value { get; set; } + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return ValueEquals(value); } + public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } + protected virtual bool ValueEquals(object value) { return object.Equals(Value, value); } + } + + public class StaticValueEqualsConverter : StaticValueEqualsConverter { + protected override bool ValueEquals(object value) { return ObjectHelper.try_convert(value, out T result) && ValueEquals(result); } + protected virtual bool ValueEquals(T value) { return base.ValueEquals(value); } + } +} \ No newline at end of file diff --git a/src/client/spark/mspark/Utilities/Converters/ImageSourceIconConverter.cs b/src/client/spark/view/Converters/ImageSourceIconConverter.cs similarity index 72% rename from src/client/spark/mspark/Utilities/Converters/ImageSourceIconConverter.cs rename to src/client/spark/view/Converters/ImageSourceIconConverter.cs index 5704878e5..cd4b259b8 100644 --- a/src/client/spark/mspark/Utilities/Converters/ImageSourceIconConverter.cs +++ b/src/client/spark/view/Converters/ImageSourceIconConverter.cs @@ -11,20 +11,21 @@ namespace mbts.ui.spark.converters internal class ImageSourceIconConverter : IValueConverter { public Thickness Margin { get; set; } = new Thickness(0); - public double Width { get; set; } = 19; - public double Height { get; set; } = 19; - public HorizontalAlignment HorizontalAlignment { get; set; } = HorizontalAlignment.Center; - public VerticalAlignment VerticalAlignment { get; set; } = VerticalAlignment.Center; + public double Width { get; set; } = double.NaN; + public double Height { get; set; } = double.NaN; + public HorizontalAlignment HorizontalAlignment { get; set; } = HorizontalAlignment.Stretch; + public VerticalAlignment VerticalAlignment { get; set; } = VerticalAlignment.Stretch; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - return new Image { + var icon = new Image { Margin = Margin, - Width = Width, - Height = Height, HorizontalAlignment = HorizontalAlignment, VerticalAlignment = VerticalAlignment, Source = value as ImageSource, }; + if (!double.IsNaN(Width)) icon.Width = Width; + if (!double.IsNaN(Height)) icon.Height = Height; + return icon; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { diff --git a/src/client/spark/mspark/Utilities/Converters/TickDisplayConverter.cs b/src/client/spark/view/Converters/TickDisplayConverter.cs similarity index 100% rename from src/client/spark/mspark/Utilities/Converters/TickDisplayConverter.cs rename to src/client/spark/view/Converters/TickDisplayConverter.cs diff --git a/src/client/spark/view/Extensions/MarkupExtensions/EnumBindingSourceExtension.cs b/src/client/spark/view/Extensions/MarkupExtensions/EnumBindingSourceExtension.cs index f14305a8c..4c394eeab 100644 --- a/src/client/spark/view/Extensions/MarkupExtensions/EnumBindingSourceExtension.cs +++ b/src/client/spark/view/Extensions/MarkupExtensions/EnumBindingSourceExtension.cs @@ -1,9 +1,6 @@ using mbts.ui.utility; using System; -using System.Collections.Generic; using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Controls.Primitives; using System.Windows.Markup; @@ -13,12 +10,16 @@ namespace mbts.ui { public EnumBindingSourceExtension() { } - public EnumBindingSourceExtension(Type Type) { + public EnumBindingSourceExtension(Type Type) : this(Type, null) { } + public EnumBindingSourceExtension(Type Type, string Except) { this.Type = Type; + this.Except = Except; } [ConstructorArgument("Type")] public Type Type { get; set; } + [ConstructorArgument("Except")] + public string Except { get; set; } public override object ProvideValue(IServiceProvider serviceProvider) { if (Type == null) { @@ -34,7 +35,14 @@ namespace mbts.ui }); } return Enumerable.Empty(); - } else return EnumHelper.get_values(Type); + } else { + var vals = EnumHelper.get_values(Type).Cast(); + if (!string.IsNullOrEmpty(Except)) { + var except_vals = Except.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + vals = vals.Where(v => !except_vals.Any(ev => string.Equals(ev, v.ToString(), StringComparison.CurrentCultureIgnoreCase))); + } + return vals.ToList(); + } } } -} +} \ No newline at end of file diff --git a/src/client/spark/view/Extensions/MarkupExtensions/NestedExtension.cs b/src/client/spark/view/Extensions/MarkupExtensions/NestedExtension.cs index ef1d6916d..74bc363df 100644 --- a/src/client/spark/view/Extensions/MarkupExtensions/NestedExtension.cs +++ b/src/client/spark/view/Extensions/MarkupExtensions/NestedExtension.cs @@ -27,7 +27,7 @@ namespace mbts.ui var split = Type.Split('.'); var type = xtr.Resolve(split[0]); for (int i = 1; i < split.Length; i++) - type = type.GetNestedType(split[1], BindingFlags.Public | BindingFlags.NonPublic); + type = type.GetNestedType(split[i], BindingFlags.Public | BindingFlags.NonPublic); return type; } } diff --git a/src/client/spark/view/Resources/WindowStyle.xaml b/src/client/spark/view/Resources/WindowStyle.xaml index 06c003543..aa6d2a8cb 100644 --- a/src/client/spark/view/Resources/WindowStyle.xaml +++ b/src/client/spark/view/Resources/WindowStyle.xaml @@ -1,25 +1,20 @@ - + - + - + @@ -125,7 +120,7 @@ - - - - - - - - - - - - - - - - - diff --git a/src/client/spark/view/Shell/ClickTrade/ClickTrade.xaml.cs b/src/client/spark/view/Shell/ClickTrade/ClickTrade.xaml.cs deleted file mode 100644 index d50a77b80..000000000 --- a/src/client/spark/view/Shell/ClickTrade/ClickTrade.xaml.cs +++ /dev/null @@ -1,26 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows; -using System.Windows.Controls; -using System.Windows.Data; -using System.Windows.Documents; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Imaging; -using System.Windows.Navigation; -using System.Windows.Shapes; -using bts.security_model; - -namespace mbts.ui.shell -{ - public partial class ClickTrade : UserControl - { - public ClickTrade() { - InitializeComponent(); - } - } - -} diff --git a/src/client/spark/view/Utility/DisplayNameHelper.cs b/src/client/spark/view/Utility/DisplayNameHelper.cs new file mode 100644 index 000000000..1d9ab0ae6 --- /dev/null +++ b/src/client/spark/view/Utility/DisplayNameHelper.cs @@ -0,0 +1,12 @@ +using System.Text.RegularExpressions; + +namespace mbts.ui.utilities +{ + public static class DisplayNameHelper + { + // Adds spaces to CamelCase => "Camel Case" + public static string camel_to_title_case(string name) { + return Regex.Replace(name, @"(?=\p{Lu}\p{Ll})|(?<=\p{Ll})(?=\p{Lu})", " ", RegexOptions.Compiled).Trim(); + } + } +} \ No newline at end of file diff --git a/src/client/spark_api/logging/Logger.cs b/src/client/spark_api/logging/Logger.cs index 57608ee64..b275f0b78 100644 --- a/src/client/spark_api/logging/Logger.cs +++ b/src/client/spark_api/logging/Logger.cs @@ -20,6 +20,7 @@ namespace bts.log { internal enum Subsystem { gen, Assert, + Engine, ui, Persist } diff --git a/src/client/spark_api/security/Security.cs b/src/client/spark_api/security/Security.cs index 62175b52d..752006442 100644 --- a/src/client/spark_api/security/Security.cs +++ b/src/client/spark_api/security/Security.cs @@ -166,5 +166,10 @@ namespace bts.api { public int CompareTo(Security other) { return SecurityComparer.Compare(this, other); } public int CompareTo(object obj) { return CompareTo(obj as Security); } + + public static readonly Security Empty = new Security { + Exchange = Venue.Bts, + ContractSpec = new ContractSpecification { CashPerPoint = double.NaN, HighTick = double.NaN, LowTick = double.NaN, PriceBreak = double.NaN, PriceMultiplier = double.NaN } + }; } -} +} \ No newline at end of file diff --git a/src/client/spark_api/security/SecurityHelper.cs b/src/client/spark_api/security/SecurityHelper.cs index a728f0a35..0b5f98395 100644 --- a/src/client/spark_api/security/SecurityHelper.cs +++ b/src/client/spark_api/security/SecurityHelper.cs @@ -1,11 +1,10 @@ -using bts.config; +//using bts.config; using Google.Protobuf.Collections; using mbts; using mbts.config; using System; using System.Collections.Generic; using System.Linq; -using bts.api; using static bts.api.Security; using FutureLeg = System.Tuple; using bts.log; @@ -14,16 +13,16 @@ namespace bts.api { internal static class SecurityHelper { - static SecurityHelper() { - try { - ExpirationDisplayOffset offset_list = Configuration.get(); - _offset_map = offset_list.entries.ToDictionary(e => e.security_name, e => e); - } - catch (Exception ex) { Logger.error(Subsystem.ui, $"Failed to get Configuration for type {typeof(ExpirationDisplayOffset)}: {ex}"); } - } + //static SecurityHelper() { + // try { + // ExpirationDisplayOffset offset_list = Configuration.get(); + // _offset_map = offset_list.entries.ToDictionary(e => e.security_name, e => e); + // } + // catch (Exception ex) { Logger.error(Subsystem.ui, $"Failed to get Configuration for type {typeof(ExpirationDisplayOffset)}: {ex}"); } + //} #region Private Members - private static readonly IDictionary _offset_map; + //private static readonly IDictionary _offset_map; private static IEnumerable _get_flat_future_legs(RepeatedField legs, int qty) { foreach (var l in legs) { @@ -47,19 +46,21 @@ namespace bts.api #region Extensions public static DateTime RawExpDate(this FutureContract future) { return new DateTime((int)future.ExpirationYear, (int)future.ExpirationMonth, (int)future.ExpirationDay); } + // probably do not need MappedExpDates in spark, leaving the method-infrastructure alone just in case public static DateTime MappedExpDate(this FutureContract future) { - ExpirationDisplayOffsetEntry offset_entry; - if (_offset_map.TryGetValue(future.Symbol, out offset_entry)) { - if (offset_entry.addition_type == ExpirationOffsetType.type.Month) return future.RawExpDate().AddMonths(offset_entry.addition_count); - else if (offset_entry.addition_type == ExpirationOffsetType.type.MonthMoveToStart) { - DateTime rv = future.RawExpDate().AddMonths(offset_entry.addition_count); - return new DateTime(rv.Year, rv.Month, 1); - } - } - return future.RawExpDate(); + return RawExpDate(future); + //ExpirationDisplayOffsetEntry offset_entry; + //if (_offset_map.TryGetValue(future.Symbol, out offset_entry)) { + // if (offset_entry.addition_type == ExpirationOffsetType.type.Month) return future.RawExpDate().AddMonths(offset_entry.addition_count); + // else if (offset_entry.addition_type == ExpirationOffsetType.type.MonthMoveToStart) { + // DateTime rv = future.RawExpDate().AddMonths(offset_entry.addition_count); + // return new DateTime(rv.Year, rv.Month, 1); + // } + //} + //return future.RawExpDate(); } public static int SignedQuantity(this ContractLeg leg) { return leg.Side == BuySell.Buy ? (int)leg.Quantity : -(int)leg.Quantity; } #endregion } -} \ No newline at end of file +} diff --git a/src/client/spark_core/core/AnonymousDisposable.cs b/src/client/spark_core/core/AnonymousDisposable.cs index 5ee1dd1ea..50ca185a4 100644 --- a/src/client/spark_core/core/AnonymousDisposable.cs +++ b/src/client/spark_core/core/AnonymousDisposable.cs @@ -59,24 +59,30 @@ namespace mbts public class DisposableSingle : IDisposable { + public DisposableSingle() : this((string)null, (IDisposable)null) { } public DisposableSingle(Action dispose) : this(null, dispose) { } public DisposableSingle(string name, params Action[] dispose) : this(name, Disposable.Create(dispose)) { } public DisposableSingle(params IDisposable[] dispose) : this(null, dispose) { } public DisposableSingle(string name, params IDisposable[] dispose) : this(name, Disposable.Create(dispose)) { } - private DisposableSingle(string name, IDisposable dispose) { - _dispose = dispose; + public DisposableSingle(string name, object lock_obj) : this(name, lock_obj, (IDisposable)null) { } + public DisposableSingle(string name, object lock_obj, params IDisposable[] dispose) : this(name, lock_obj, Disposable.Create(dispose)) { } + private DisposableSingle(string name, IDisposable dispose) : this(name, new object(), dispose) { } + private DisposableSingle(string name, object lock_obj, IDisposable dispose) { _name = name ?? GetType().FullName; + _lock = lock_obj; + _dispose = dispose; } private readonly string _name; + private readonly object _lock; private IDisposable _dispose; private bool _is_disposing, _is_disposed; - public bool is_disposed { get { lock(_name) return _is_disposing || _is_disposed; } } + public bool is_disposed { get { lock(_lock) return _is_disposing || _is_disposed; } } public void check_not_disposed() { if (is_disposed) throw new ObjectDisposedException(_name); } public void Dispose() { - lock(_name) { + lock(_lock) { if (_is_disposed) throw new ObjectDisposedException(_name); if (_is_disposing) return; _is_disposing = true; @@ -86,4 +92,4 @@ namespace mbts _is_disposing = false; } } -} +} \ No newline at end of file diff --git a/src/client/spark_core/core/GlobalExtensions.cs b/src/client/spark_core/core/GlobalExtensions.cs index 20cc5ce41..8c536ff75 100644 --- a/src/client/spark_core/core/GlobalExtensions.cs +++ b/src/client/spark_core/core/GlobalExtensions.cs @@ -7,7 +7,7 @@ namespace mbts { return string.Format(input, vals); } - [DllImport("sparklib")] + [DllImport("spark_lib")] private static extern void ll_to_parts(UInt64 ll_time, out int year, out int month, out int day, out int hour, out int minute, out int second, out int ms); public static DateTime lldatetime(this ulong ll) { diff --git a/src/lib/config/protos/expiration_display_offset.proto b/src/lib/config/protos/expiration_display_offset.proto index 9c22aa178..3c8ded3c7 100644 --- a/src/lib/config/protos/expiration_display_offset.proto +++ b/src/lib/config/protos/expiration_display_offset.proto @@ -1,4 +1,4 @@ -syntax='proto2'; +syntax='proto2'; package bts.config; message ExpirationOffsetType diff --git a/src/lib/sparkproto/SparkProtos.proto b/src/lib/sparkproto/SparkProtos.proto index 2b5f69b0b..82d8c631f 100644 --- a/src/lib/sparkproto/SparkProtos.proto +++ b/src/lib/sparkproto/SparkProtos.proto @@ -36,12 +36,692 @@ message Order { StopLimitOrder stop_limit_order = 130; IcebergOrder iceberg_order = 200; - CrossingHedgeOrder crossing_hedge_order = 700; - CustomOrder custom_order = 1000; + BTSIcebergOrder bts_iceberg_order = 300; + BTSStopOrder bts_stop_order = 400; + + CrossingHedgeOrder crossing_hedge_order = 50000; + SimpleHedgeOrder simple_hedge_order = 51000; + CustomOrder custom_order = 1000000; } ExecutionStrategy execution_strategy = 2000; + SimpleExecutionStrategy simple_execution_strategy = 2100; } +/***************************************Algo Order Support Data**********************************/ + +/********************* SIMPLE *********************************/ +message SimpleExecutionStrategy +{ + SimpleExecutionParams leg1 = 10; + SimpleExecutionParams leg2 = 20; +} +message SimpleExecutionParams +{ + bts.api.Security security = 10; + + int32 pre_hedge_payup_ticks = 100; + bool is_working = 110; + bool is_hedging = 120; + + QuoteMuteZone slop = 200; + PostHedgePriceBasedForcedCross post = 300; +} +message SimpleHedgeOrder +{ + PostHedgePriceBasedForcedCross post = 10; +} + +/********************* END SIMPLE *********************************/ + +/********** Fundamental Data **********/ + +message PriceType +{ + enum Status + { + BID = 0; + ASK = 1; + LTP = 2; + } + + Status status = 10; +} + +message PriceOffset +{ + PriceType price_type = 10; + int32 offset_in_ticks = 20; +} + +message QuantityMeasure +{ + oneof quantity + { + uint32 absolute = 10; + double ratio = 20; + } +} + +message OrderTime +{ + oneof Time + { + uint64 absolute_time = 10; + uint64 offset_from_now = 20; + bool now = 30; + } +} + +/********** Trigger Data **********/ + +message TrailingTrigger +{ + PriceType price_type = 10; + int32 number_of_ticks = 20; + oneof TriggerType + { + bool stop = 30; + bool invserse_stop = 40; + } +} + +message QuantityTrigger +{ + QuantityMeasure quantity_measure = 10; + oneof Relation + { + bool less_than_equalto = 20; + bool greater_than_equalto = 30; + } + uint32 threshold_quantity = 40; +} + +message AbsolutePriceTrigger +{ + PriceType price_type = 10; + double trigger_price = 20; + QuantityTrigger quantity_trigger = 30; +} + +message PriceTrigger +{ + oneof Trigger + { + TrailingTrigger trailing_trigger = 10; + AbsolutePriceTrigger absolute_price_trigger = 20; + } +} +/***************************************BTS ShootTillHit******************************************* +This is the equivelant of TT's Retry Order. This Order keeps submitting a child order at a specified +interval until it is either accepted or rejected a specified max number of times. This is used to get a +favorable position in queue before open. +Spreader: Not supported (legging risk of one leg getting accepted ?) +*/ + +message BTSShootTillHitParameters +{ + uint32 max_number_of_tries = 10; + uint32 time_between_retries_micro_seconds = 20; + /// This could be a specific time, now, or offset from now + OrderTime order_entry_time = 30; +} + +message BTSShootTillHitOrder +{ + /// Only support a limit or market as Retry's + /// We can make Retry a general parameter for + /// every order + oneof native_order_type + { + MarketOrder market_order = 10; + LimitOrder limit_order = 20; + } + BTSShootTillHitParameters shoot_till_hit_parameters = 30; +} + +/*************************************************************************************************/ + + +/****************************BTS With a Tick (general parameter)********************************** +This order wraps around a limit order that is automatically repriced one tick towards the inside market +i. When the best available price to trade is more than one tick away from the limit price +ii. When the best available price is one tick away and the size falls below a certain threshold +The idea is that instead of chasing the market (and cross it), you submit it away from the market and only +cross the market when the liquidity of the opposite side drops below a threshold. +*/ + +message BTSWithATickParameters +{ + QuantityMeasure quantity_threshold = 10; +} + +message BTSWithATickOrder +{ + BTSWithATickParameters order_parameters = 10; + oneof native_order_type + { + LimitOrder limit_order = 20; + } + /// The price can also be submitted as an offset from B/A/LTP + /// instead of an asbolute price + PriceOffset price_offset = 30; +} + +/*************************************************************************************************/ + +/***************************************BTS Timed Window(general parameters)*********************** +This order wraps a Limit or Market order in a Timed Window ie sends the order to the market +at the Start Time (absolute or relative). At the Stop Time, it performs the End Action for +which there is only one option, Cancel +*/ + +/// This can also be a general parameter +message BTSTimedWindowParameters +{ + OrderTime start_time = 10; + OrderTime stop_time = 20; + oneof EndAction + { + bool cancel = 30; + } +} + +message BTSTimedWindowOrder +{ + BTSTimedWindowParameters order_parameters = 10; + oneof native_order_type + { + MarketOrder market_order = 20; + LimitOrder limit_order = 30; + } + // The price can also be submitted as an offset from B/A/LTP + /// instead of an asbolute price + PriceOffset price_offset = 40; + BTSWithATickParameters withatick_parameters = 50; /// optional +} + +/*************************************************************************************************/ + +/***************************************BTS Trailing Limit**************************************** +Submits a limit order at a fixed distance from the market. It is repriced relative to the market. +Trailing orders are always set better than the current market (hence ticks can not be negative). So +for a bid order, it’s submitted a fixed number of ticks below the market. If the market goes up, +the order moves higher. If the market goes down the order price is not adjusted. +(However, when orders are submitted relative to LTP, they can better the market, and get filled +immediatly) +*/ + +message BTSTrailingLimitOrder +{ + PriceOffset price_offset = 10; + BTSTimedWindowParameters optional_timed_parameters = 20; +} + +/*************************************************************************************************/ + +/***************************************BTS Stop ************************************************* +Conditional order to buy when the price rises to a designated price level (or sell when it falls). +Buy stop orders are placed above the market and sells below. The trigger price (also called stop price) +can be an +i. Absolute price from where the user clicks on the ladder +ii. Trailing price that trails the market by a constant amount (for buy orders, trigger price goes down +as the market goes down, so the market penetrates the trigger price on its way up). +When the market penetrates the trigger price, a limit order is sent "payup" ticks away form B/A/LTP +*/ + +message BTSStopOrder +{ + PriceTrigger price_trigger = 10; + oneof native_trigger_order_type + { + MarketOrder market_order = 20; + LimitOrder limit_order = 30; + } + oneof trigger_order_price + { + PriceOffset payup = 40; + double price = 50; + } + BTSWithATickParameters optional_withatick_parameters = 60; + BTSTimedWindowParameters optional_timed_parameters = 70; +} + +/*************************************************************************************************/ + +/***************************************BTS IfTouched ******************************************** +Opposite of BTS Stop (Both in terms of where the order is placed, and how it trails the market +*/ + + +message BTSIfTouchedOrder +{ + PriceTrigger price_trigger = 10; + oneof native_trigger_order_type + { + MarketOrder market_order = 20; + LimitOrder limit_order = 30; + } + oneof order_price + { + PriceOffset payup = 40; + double price = 50; + } + BTSWithATickParameters optional_withatick_parameters = 60; + BTSTimedWindowParameters optional_timed_parameters = 70; +} + +/*************************************************************************************************/ + +/***************************************BTS Iceberg*********************************************** +Breaks a large order into smaller disclosed orders, each of which is sent after the +previous has been filled. +*/ + +message BTSIcebergOrder +{ + QuantityMeasure display_quantity = 10; + oneof child_order_offset + { + PriceOffset market_offset = 20; + double diff_from_last_fill = 30; + } + /// Optional Parameters + BTSWithATickParameters withatick_parameters = 40; + PriceTrigger price_trigger = 60; + BTSTimedWindowParameters timed_window_parameters = 70; +} + +/*************************************************************************************************/ + +/***************************************BTS TimeSlice*************************************/ + +message BTSTimeSliceOrder +{ + double interval = 10; + QuantityMeasure display_quantity = 20; + oneof child_order_type + { + MarketOrder market_order = 30; + LimitOrder limit_order = 40; + } + PriceOffset child_order_offset = 50; + /// the earlier order can either be left, or its + /// price moved toward the inside market by payup_ticks + oneof left_over_action + { + bool leave = 60; + double payup_ticks = 70; + } + /// Optional Parameters + BTSWithATickParameters withatick_parameters = 80; + BTSTimedWindowParameters timed_window_parameters = 90; + PriceTrigger price_trigger = 100; +} + +/*************************************************************************************************/ + +/***************************************BTS OCO*********************************************** +Sends a Stop-Loss and a Limit order of the same quantity at different price levels for the same +security. For buy's the Limit is sent at a lower price level. +i. A fill in the limit order decreases the size of the Stop Order. +ii. If the stop order is trigerred, the Limit order is cancelled +*/ + +message BTSOCOOrder +{ + PriceTrigger price_trigger = 10; + oneof native_trigger_order_type + { + MarketOrder market_order = 20; + LimitOrder limit_order = 30; + } + oneof order_price + { + PriceOffset payup = 40; + double price = 50; + } + BTSWithATickParameters optional_withatick_parameters = 60; + BTSTimedWindowParameters optional_timed_parameters = 70; + /// The price for the limit order is in the main order object +} + +/*************************************************************************************************/ +/*************************************************************************************************/ +/*************************************Spreader Parameters*****************************************/ +/*************************************************************************************************/ +/*************************************************************************************************/ + +message RulePriority +{ + bool is_active = 10; + int32 priority = 20; +} + +message LegSpreaderParams +{ + /// this is exclusively used for the price and not + /// for the qty, which is part of the spread def + double price_multiplier = 10; + /// Legs can be quoted actively, or sent in reponse + /// to fills + bool is_active_quoting = 20; + QuoteParams quote_params = 30; + PreHedgeParams pre_hedge_params = 40; + PostHedgeParams post_hedge_params = 50; +} + +/************************************************************************************************* + ******************************************Quote************************************************** + *************************************************************************************************/ + +/*************************************Quote MuteZone*********************************** +(TT Basic Slop) +This rule sets a band above and below the quoting order inside of which any price changes will be +ignored. Only once a price change will move the order outside the band will the change be allowed to +go through. This can help to reduce the amount of re-quoting that takes place + +f(new_price, curr_price, QuoteMuteZone) -> new_price + +for buy orders +IF (new_price > current_price && new_price <= current_price + inside_ticks * tick_size OR + new_price < current_price && new_price >= current_price - outside_ticks * tick_size) +THEN + new_price = current_price + +for sell orders +IF (new_price > current_price && new_price <= current_price + outside_ticks * tick_size || + new_price < current_price && new_price >= current_price - inside_ticks * tick_size) +THEN + new_price = current_price +*/ +message QuoteMuteZone +{ + uint32 outside_ticks = 10; + uint32 inside_ticks = 20; + RulePriority priority = 30; +} + +/*************************************Quote RepriceThrottle******************************* +(Stellar's sensitivity) +This parameter defines regions (wrt their distance from the inside market) +vs the price change in ticks thats needed for the leg to be requoted + +f(new_price, curr_price, market_bid, market_ask) -> new_price +*/ +message QuoteRepriceThrottle +{ + map ticks_away_to_sensitivity = 10; + RulePriority priority = 20; +} + + +/*************************************Quote InsideMarketDistance************************************ +(TT Inside Smart Quote) +Suppress changing the quote order if: +(1) Moving toward the inside market, and +(2) New order price is not sufficiently close to the inside market price + +f(new_price, current_price, market_bid, market_ask, QuoteInsideSmart) -> new_price, new_qty + +for buy orders +IF (new_price > current_price && new_price <= market_bid - ticks_from_inside * tick_size) +THEN +{ + new_price = current_price + new_qty = current_qty +} + +for sell orders +IF (new_price < current_price && new_price >= market_ask + ticks_from_inside * tick_size) +THEN +{ + new_price = current_price + new_qty = current_qty +} +*/ + +message QuoteInsideMarketDistance +{ + uint32 ticks_from_inside = 10; + RulePriority priority = 20; +} + +/******************************Quote InsideMarketDistanceWithTravel****************************** +(TT) Inside Smart Quote with LIMIT +[Pre-Quote] Suppress changing the quote order if: +(1) Moving toward the inside market, +(2) New order price is not sufficiently close to the inside market price +(3) New order price is not too far away from the current order price + +f(new_price, current_price, market_bid, market_ask, QuoteInsideSmartWithLimit) -> new_price, new_qty + +for buy orders +IF (new_price > current_price && new_price <= market_bid - ticks_from_inside * tick_size && + Abs (new_price - current_price) < limit * tick_size) +THEN +{ + new_price = current_price + new_qty = current_qty +} + +for sell orders +IF (new_price < current_price && new_price >= market_ask + ticks_from_inside * tick_size && + Abs (new_price - current_price) < limit * tick_size) +THEN +{ + new_price = current_price + new_qty = current_qty +} +*/ + +message QuoteInsideMarketDistanceWithTravel +{ + uint32 ticks_from_inside = 10; + uint32 limit = 20; + RulePriority priority = 30; +} + +/*************************************Quote MaxOrderMove***************************************** +(TT) Max Order Move +[Pre-Quote] This rule sets a restriction on how far a quoting order can move in one action. If triggered, +it will pull the working order until the next order action comes back into range, where the valid range +is specified by 'MaxOrderMoveThreshold'. +This is different from the other PreQuoting rules since it doesnt merely govern if the price should +move or not, but it sets the quantity to 0, hence removing the order + +f (new_price, current_price) -> new_qty + +IF (Abs (new_price - current_price) > tick_size * max_order_move_threshold) +THEN new_qty = 0; +Also note, that once the order is pulled out, its "current_price" or last working price has to be +rememberred in order to put it back in +*/ + +message QuoteMaxOrderMove +{ + uint32 max_order_move_threshold = 10; +} + + +/************************************************************************************************* + ******************************************PreHedge*********************************************** + *************************************************************************************************/ +message PreHedgeParams +{ + PreHedgeMaxPriceFromInsideMarket max_price_from_inside_market = 10; + PreHedgeSendHedgeAsMarketOrder send_hedge_as_market_order = 20; + PreHedgeQuantityBasedPayupTicks quantity_based_payup_ticks = 30; + PreHedgeQuantityBasedPayLessTicks quantity_based_payless_ticks = 40; +} + +/***********************************PreHedge HedgePriceLimit************************************** +(TT) Hedge Price Limit +[Pre-Hedge] If the calculated hedge order price is greater than the user-defined number of ticks +through the opposite inside market, submit the hedge order at the user-defined limit. This rule is +designed for spreads with unequal multipliers to ensure that hedge orders are not rejected by +exchange price bands. 'TicksLimit' is the maximum number of ticks the hedge order can be submitted +through the opposite inside market. + +f (calculated_hedge_price, market_bid_price, market_ask_price, PreHedgeMaxPriceFromInsideMarket) -> calculated_hedge_price + +For buy hedge orders +IF (calculated_hedge_price > market_ask_price + tick_size * hedge_tick_limit) +THEN calculated_hedge_price = market_ask_price + tick_size * hedge_tick_limit + +For sell hedge orders +IF (calculated_hedge_price < market_bid_price - tick_size * hedge_tick_limit) +THEN calculated_hedge_price = market_bid_price - tick_size * hedge_tick_limit +(The above is not accounting for -ve priced markets, which could be the case if legs are spreads themslves) +*/ + +message PreHedgeMaxPriceFromInsideMarket +{ + uint32 hedge_tick_limit = 10; +} + +/***********************************PreHedge LiquidityBasedPayless********************************** +(TT) Liquidity Based Backoff Tick +[Pre-Hedge] If the opposite inside market quantity of the hedge order is greater than or equal to +'QtyThreshold', then back off one tick from the calculated hedge price. Commonly used in conjunction +with the [Post-Hedge] Rule "(TT) Liquidity Based Payup Tick". + +f (calculated_hedge_order_price, market_bid_qty, market_ask_qty) -> calculated_hedge_order_price + +for buy hedge orders +IF (market_ask_qty >= opposite_inside_market_threshold) +THEN hedge_order_price = calculated_hedge_order_price - tick_size + +for sell hedge orders +IF (market_bid_qty >= opposite_inside_market_threshold) +THEN hedge_order_price = calculated_hedge_order_price + tick_price +*/ + +message PreHedgeLiquidityBasedPayless +{ + uint32 opposite_inside_market_threshold = 10; +} + +/*******************************PreHedge SendHedgeAsMarketOrder************************************* +(TT) Send Hedge as Market Order +[Pre-Hedge] This rule simply converts all hedge orders to market orders. This can be useful to help +prevent against ever missing a hedge ("getting legged"). + +f () -> order_type + +IF (TRUE) + order_type = MARKET + +*/ + +message PreHedgeSendHedgeAsMarketOrder +{ + bool send_hedge_as_market_order = 10; +} + +/*******************************PreHedge QuantityBasedPayupTicks************************************* +[Pre-Hedge] +If the quantity at the calculated hedge price is less than the quantity_threshold +then pay up by payup_ticks ticks + +f (calculated_hedge_order_price, depth, PreHedgeQuantityBasedPayupTicks) -> calculated_hedge_order_price + +for buy orders +if (quantity_at_price (calculated_hedge_order_price) < quantity_threshold) + calculated_hedge_order_price = calculated_hedge_order_price + payup_ticks * tick_size +for sell orders +if (quantity_at_price (calculated_hedge_order_price) < quantity_threshold) + calculated_hedge_order_price = calculated_hedge_order_price - payup_ticks * tick_size +*/ + +message PreHedgeQuantityBasedPayupTicks +{ + QuantityMeasure quantity_threshold = 10; + uint32 payup_ticks = 20; +} + +/*******************************PreHedge QuantityBasedPayLessTicks************************************* +[Pre-Hedge] +If the quantity at the calculated hedge price is greater than the quantity_threshold +then pay less by payup_ticks ticks + +f (calculated_hedge_order_price, depth, PreHedgeQuantityBasedPayupTicks) -> calculated_hedge_order_price + +for buy orders +if (quantity_at_price (calculated_hedge_order_price) > quantity_threshold) + calculated_hedge_order_price = calculated_hedge_order_price - payup_ticks * tick_size +for sell orders +if (quantity_at_price (calculated_hedge_order_price) > quantity_threshold) + calculated_hedge_order_price = calculated_hedge_order_price + payup_ticks * tick_size +*/ + +message PreHedgeQuantityBasedPayLessTicks +{ + QuantityMeasure quantity_threshold = 10; + uint32 payless_ticks = 20; +} + + +/************************************************************************************************* + ******************************************PostHedge*********************************************** + *************************************************************************************************/ + +message PostHedgeParams +{ + PostHedgeTimeBasedForcedCross time_based_forced_cross = 10; + PostHedgePriceBasedForcedCross price_based_cross = 20; +} + +/**********************************PostHedge TimeBasedForcedCross************************************* +(TT) Time Based Go To Market +[Post-Hedge] If the working hedge order is legged for more than the user-defined time, then change the +hedge order to cross the market. 'TimeInMS' is the number of milliseconds the legged hedge order is +allowed to work before crossing the market. 'MarketTicks' is how many ticks into the opposite market +to price the hedge order. A market update must occur for the rule to be evaluated (ie it does not +check the clock) + +f (time_since_order, market_bid, market_ask, PostHedgeTimeBasedForcedCross) -> hedge_order_price + +for buy hedge orders +IF (time_since_order) > time_in_ms_threshold +THEN hedge_order_price = market_ask + tick_size * market_cross_ticks + +for sell hedge orders +IF (time_since_order) > time_in_ms_threshold +THEN hedge_order_price = market_buy - tick_size * market_cross_ticks +*/ + +message PostHedgeTimeBasedForcedCross +{ + uint32 time_in_ms_threshold = 10; + uint32 market_cross_ticks = 20; +} + +/**********************************PostHedge PriceBasedForcedCross************************************* +(TT) Ticks Away Based Go To Market +[Post-Hedge] If the working hedge order price exceeds the user-defined ticks away from the opposite +inside market, then change the hedge order to cross the market. 'TicksAway' is the number of ticks the +hedge order is allowed to work before crossing the market. 'MarketTicks' is how many ticks into the opposite +market to price the hedge order. + +f (hedge_order_price, market_bid, market_ask, PostHedgeTicksBasedForcedCross) -> hedge_order_price + +for buy hedge orders +IF (hedge_order_price < market_ask - tick_size * ticks_threshold) +THEN hedge_order_price = market_ask + tick_size * market_cross_ticks + +for sell hedge orders +IF (hedge_order_price > market_bid + tick_size * ticks_threshold) + hedge_order_price = market_bid - tick_size * market_cross_ticks +*/ + +message PostHedgePriceBasedForcedCross +{ + uint32 ticks_threshold = 10; + uint32 market_cross_ticks = 20; +} + +/*************************************************************************************************/ + message OrderMetadata { uint32 color = 10; string key_binding = 11; @@ -107,9 +787,10 @@ message IcebergOrder { uint32 show_quantity = 20; } //This is the order type used to encapsulate (and localize) the post hedge rules; it should be called 'With A Tick' -message CrossingHedgeOrder { +message CrossingHedgeOrder { + uint32 ticks_better_threshold = 5; uint32 cross_size_threshold = 10; - double cross_ratio_threshold = 20; + double cross_ratio_threshold = 20; } //Nice place to use the server API @@ -118,39 +799,56 @@ message CustomOrder { map custom_parameters = 30; } - -message ExecutionStrategy { +message ExecutionStrategy +{ map security_id_to_params = 10; + map leg_params_map = 20; } -message SyntheticLegExecutionParams { + +message SyntheticLegExecutionParams +{ QuoteParams quote_params = 10; HedgeParams hedge_params = 20; } -message QuoteParams { +message QuoteParams +{ + // If it's working, an order is sent immediatly. Else the order is sent based on a fill of the other leg + // TODO:retire since its available in LegSpreaderParams bool is_working = 10; - //Defines how much volume required to price off of a hedge leg level, as a percentage of working leg size. - //E.g. If you are working a 2 by 3 spread, you will work the 2 lot at a price determined by the price - //level at which you can sell 3*hedge_ratio. Default 100% (1.0) - double hedge_ratio = 20; + // Defines how much volume required to price off of a hedge leg level, as a ratio of working leg size. + // e.g. If you are working N lots of 2 (leg_1) by 3 spread, you will work leg_1 at a price determined by + // the price level at which you can sell N*3*lean_quantity_ratio. + double lean_quantity_ratio = 20; + // This tells whether to use the volume weighted average price or the worst price for the other legs, + // when computing the price of this active quoting leg bool pessimistic_hedge_pricing = 30; - - oneof quote_rules { + // TODO:retire since its a Parameter + oneof quote_rules + { TickRangeRequoteRules tick_range_requote_rules = 60; CustomRequoteRules custom_requote_rules = 100; } + QuoteMuteZone quote_mute_zone = 1000; + QuoteRepriceThrottle quote_reprice_throttle = 1010; + QuoteInsideMarketDistance quote_inside_market_distance = 1020; + QuoteInsideMarketDistanceWithTravel quote_inside_market_distance_with_travel = 1030; + QuoteMaxOrderMove quote_max_order_move = 1040; } -message TickRangeRequoteRules { + +message TickRangeRequoteRules +{ //From zero to map[0].key ticks to inside market requote the working leg every map[0].value //From map[0].key to map[1].key distance to inside market requote the working leg every map[1].value map ticks_away_to_sensitivity = 10; } -message CustomRequoteRules { + +message CustomRequoteRules +{ string requote_rule_type = 10; map custom_parameters = 20; } - message HedgeParams { PayupHedgeRules payup_hedge_rules = 10; PaylessHedgeRules payless_hedge_rules = 20; @@ -201,8 +899,6 @@ message SyntheticExecutionStrategy { ExecutionStrategy execution_strategy = 20; } - - message RiskLimit { uint32 max_order_size = 10;