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