Merge branch 'fia' of bitbucket.org:bluetradesys/spark
This commit is contained in:
commit
5a33d98c48
98 files changed
+786
-451
No files matched your search
Vendored
+1
-1
@@ -16,7 +16,7 @@
|
||||
"name": "Client Attach",
|
||||
"type": "clr",
|
||||
"request": "attach",
|
||||
"processName": "${command:pickProcess}"
|
||||
"processId":"${command:pickProcess}"
|
||||
},
|
||||
{
|
||||
"name": "Docker Launch",
|
||||
|
||||
Vendored
+5
-2
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"files.associations": {
|
||||
"utility": "cpp",
|
||||
"initializer_list": "cpp",
|
||||
"list": "cpp",
|
||||
@@ -7,7 +7,10 @@
|
||||
"vector": "cpp",
|
||||
"xhash": "cpp",
|
||||
"xstring": "cpp",
|
||||
"system_error": "cpp",
|
||||
"array": "cpp",
|
||||
"string_view": "cpp"
|
||||
"xutility": "cpp",
|
||||
"*.ipp": "cpp"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,13 +90,13 @@ namespace mbts.ui.shell
|
||||
else {
|
||||
// Second instance. Activate the main window and return
|
||||
NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, (WM)NativeMethods.WM_SHOWME, IntPtr.Zero, IntPtr.Zero);
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Starting a second shell is not allowed. Attempting to bring the original shell to the foreground.");
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Starting a second shell is not allowed. Attempting to bring the original shell to the foreground.");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
catch (AbandonedMutexException ame) {
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Shell mutex was abandoned. Releasing the mutex and trying again. \n" + ame.ToString());
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "Shell mutex was abandoned. Releasing the mutex and trying again. \n" + ame.ToString());
|
||||
_mutex.ReleaseMutex();
|
||||
// Try agai until stack overflow
|
||||
return Run();
|
||||
|
||||
@@ -22,7 +22,6 @@
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="../spark_api/spark_api.csproj" />
|
||||
<ProjectReference Include="../spark_core/spark_core.csproj" />
|
||||
<!-- <Reference Include="..\..\..\build\Debug\bin\netstandard2.0\spark_api.dll" /> -->
|
||||
<Reference Include="PresentationCore" />
|
||||
<Reference Include="PresentationFramework" />
|
||||
<Reference Include="PresentationFramework.Aero" />
|
||||
|
||||
@@ -208,7 +208,7 @@ namespace mbts
|
||||
// Some defenses against crashing when the source collection is
|
||||
if (!src.is_distinct(comp)) {
|
||||
Logger.assert_d(false);
|
||||
Logger.error(bts.log.Subsystem.ui, "sync_with requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name));
|
||||
Logger.error(bts.log.Subsystem.Ui, "sync_with requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name));
|
||||
}
|
||||
|
||||
// First remove anything not in the destination
|
||||
@@ -235,7 +235,7 @@ namespace mbts
|
||||
++d;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Logger.error(bts.log.Subsystem.ui, "sync_with error (Element T is {0}): {1}".fmt(typeof(T), ex));
|
||||
Logger.error(bts.log.Subsystem.Ui, "sync_with error (Element T is {0}): {1}".fmt(typeof(T), ex));
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
@@ -244,7 +244,7 @@ namespace mbts
|
||||
public static bool sync_with_setwise<T>(this ObservableCollection<T> dest, IEnumerable<T> src, IEqualityComparer<T> comp) {
|
||||
if (!src.is_distinct(comp)) {
|
||||
Logger.assert_d(false);
|
||||
Logger.error(bts.log.Subsystem.ui, "sync_with_setwise requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name));
|
||||
Logger.error(bts.log.Subsystem.Ui, "sync_with_setwise requires input to be distinct. Error in input of type {0}.".fmt(typeof(T).Name));
|
||||
}
|
||||
IEnumerable<T> added, removed;
|
||||
dest.difference(src, out added, out removed, comp);
|
||||
|
||||
@@ -44,11 +44,13 @@ namespace mbts
|
||||
|
||||
public static double tickup(this RegionalTickFactors regional_tick, double input) { return regional_tick.tickup(input, 1); }
|
||||
public static double tickup(this RegionalTickFactors regional_tick, double input, uint count) {
|
||||
if (DoubleHelper.IsNaNOrInfinity(input)) return input;
|
||||
if (DoubleHelper.IsNaNOrInfinity(input) || count == 0) return input;
|
||||
double val, tuf;
|
||||
if (input < regional_tick.low_tick_inclusive_end) {
|
||||
tuf = regional_tick.low_tick.tick_unit_frac();
|
||||
input -= input % tuf;
|
||||
double ieeer = Math.IEEERemainder(input, tuf);
|
||||
input -= ieeer;
|
||||
if (ieeer < -_precision_const) count--;
|
||||
val = input + tuf * count;
|
||||
if (val > regional_tick.low_tick_inclusive_end) {
|
||||
count -= (uint)Math.Ceiling((regional_tick.low_tick_inclusive_end - input) / tuf);
|
||||
@@ -57,12 +59,15 @@ namespace mbts
|
||||
}
|
||||
} else {
|
||||
tuf = regional_tick.high_tick.tick_unit_frac();
|
||||
input -= input % tuf;
|
||||
double ieeer = Math.IEEERemainder(input, tuf);
|
||||
if (Math.Abs(ieeer) <= _precision_const) input -= ieeer;
|
||||
val = input + tuf * count;
|
||||
}
|
||||
return _round_tick(tuf, val);
|
||||
}
|
||||
|
||||
private const double _precision_const = 0.000000001;
|
||||
|
||||
public static double tickdown(this TickFactors tick, double input) { return tick.tickdown(input, 1); }
|
||||
public static double tickdown(this TickFactors tick, double input, uint count) {
|
||||
if (DoubleHelper.IsNaNOrInfinity(input)) return input;
|
||||
@@ -75,24 +80,33 @@ namespace mbts
|
||||
|
||||
public static double tickdown(this RegionalTickFactors regional_tick, double input) { return regional_tick.tickdown(input, 1); }
|
||||
public static double tickdown(this RegionalTickFactors regional_tick, double input, uint count) {
|
||||
if (DoubleHelper.IsNaNOrInfinity(input)) return input;
|
||||
if (DoubleHelper.IsNaNOrInfinity(input) || count == 0) return input;
|
||||
double val, tuf;
|
||||
if (input > regional_tick.low_tick_inclusive_end) {
|
||||
tuf = regional_tick.high_tick.tick_unit_frac();
|
||||
double remainder = input % tuf;
|
||||
if (remainder > 0) input += tuf - remainder;
|
||||
double ieeer = Math.IEEERemainder(input, tuf);
|
||||
input -= ieeer;
|
||||
if (ieeer > _precision_const) count--;
|
||||
val = input - count * tuf;
|
||||
if (val < regional_tick.low_tick_inclusive_end) {
|
||||
count -= (uint)Math.Ceiling((input - regional_tick.low_tick_inclusive_end) / tuf);
|
||||
tuf = regional_tick.low_tick.tick_unit_frac();
|
||||
return regional_tick.low_tick_inclusive_end - tuf * count;
|
||||
val = regional_tick.low_tick_inclusive_end - tuf * count;
|
||||
}
|
||||
} else {
|
||||
tuf = regional_tick.low_tick.tick_unit_frac();
|
||||
double ieeer = Math.IEEERemainder(input, tuf);
|
||||
if (Math.Abs(ieeer) <= _precision_const) input -= ieeer;
|
||||
val = input - tuf * count;
|
||||
}
|
||||
return _round_tick(tuf, val);
|
||||
}
|
||||
|
||||
public static double round(this TickFactors tick, double input) { return _round_tick(tick.tick_unit_frac(), input); }
|
||||
public static double round(this RegionalTickFactors regional_tick, double input) {
|
||||
if (DoubleHelper.IsNaNOrInfinity(input)) return input;
|
||||
return input <= regional_tick.low_tick_inclusive_end ? regional_tick.low_tick.round(input) : regional_tick.high_tick.round(input);
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Private Members
|
||||
@@ -175,7 +189,7 @@ namespace mbts
|
||||
}
|
||||
|
||||
private static double _round_tick(double tick_unit_frac, double input) {
|
||||
return input + Math.IEEERemainder(input, tick_unit_frac);
|
||||
return input - Math.IEEERemainder(input, tick_unit_frac);
|
||||
}
|
||||
|
||||
private static int _n_display_digits(double tick_base) {
|
||||
|
||||
@@ -9,7 +9,12 @@ using bts.spark;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
class ActorFabric : IActorFabric
|
||||
|
||||
interface IParentSearch
|
||||
{
|
||||
OrderID find_parent_id(OrderID oid);
|
||||
}
|
||||
class ActorFabric : IActorFabric, IParentSearch
|
||||
{
|
||||
readonly static Lazy<ActorFabric> _instance = new Lazy<ActorFabric>(() => new ActorFabric(), true);
|
||||
public static ActorFabric instance { get { return _instance.Value; } }
|
||||
@@ -38,6 +43,20 @@ namespace mbts.spark
|
||||
});
|
||||
}
|
||||
|
||||
public OrderID find_parent_id(OrderID oid)
|
||||
{
|
||||
foreach(var actor in _actors.Values)
|
||||
{
|
||||
if(actor is IParentSearch)
|
||||
{
|
||||
var res = (actor as IParentSearch).find_parent_id(oid);
|
||||
if(res != null)
|
||||
return res;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void install_pollster(IPollable poll)
|
||||
{
|
||||
_polls[Guid.NewGuid()] = poll;
|
||||
|
||||
@@ -30,6 +30,8 @@ namespace mbts.spark
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Dictionary<string, string> _unique_fills = new Dictionary<string, string>();
|
||||
Task<IOrderHandle> IAlgoClient.send(Order order)
|
||||
{
|
||||
return Task.Run<IOrderHandle>(() =>
|
||||
@@ -38,7 +40,15 @@ namespace mbts.spark
|
||||
if(ActorMapping.order_actor_mapping.TryGetValue(order.AlgoOrderTypeCase, out t))
|
||||
{
|
||||
IOrderHandle actor = _fabric.create(t, order);
|
||||
actor.fills.Subscribe(x => _fills.OnNext(x));
|
||||
actor.fills.Subscribe(x =>
|
||||
{
|
||||
string dum;
|
||||
if(!_unique_fills.TryGetValue(x.Id.Id, out dum))
|
||||
{
|
||||
_unique_fills[x.Id.Id] = string.Empty;
|
||||
_fills.OnNext(x);
|
||||
}
|
||||
});
|
||||
actor.order_status.Subscribe(x => _order_status.OnNext(x));
|
||||
_orders[order.Id] = actor;
|
||||
actor.spawn();
|
||||
|
||||
@@ -14,17 +14,15 @@ namespace mbts.spark.orders
|
||||
class CrossingHedgeOrderActor : OrderActorBase, ICancelable, IModifiable
|
||||
{
|
||||
readonly IMarketDataSource _md;
|
||||
readonly IExchangeGateway _exchange;
|
||||
readonly IDropCopy _dc;
|
||||
OrderStatus _status;
|
||||
IOrderHandle _handle;
|
||||
public CrossingHedgeOrderActor(IActorFabric fabric, Order order) : base(fabric, order)
|
||||
{
|
||||
//TODO Multi exchange
|
||||
fabric.find_wellknown_service<IMarketDataSource>(order.Security.Exchange, out _md);
|
||||
fabric.find_wellknown_service<IExchangeGateway>(order.Security.Exchange, out _exchange);
|
||||
fabric.find_wellknown_service<IDropCopy>(order.Security.Exchange, out _dc);
|
||||
}
|
||||
|
||||
|
||||
public override void on_spawn()
|
||||
{
|
||||
_disposables.Add(_md.subscribe_bbo(_order.Security).Subscribe(x =>
|
||||
@@ -32,29 +30,27 @@ namespace mbts.spark.orders
|
||||
if(x != null)
|
||||
watch_hedges(x);
|
||||
}));
|
||||
_disposables.Add(_dc.subscribe_fills(new Predicate<Fill>(x => _order.Id.Equals(x.Order.Id))).Subscribe(x =>
|
||||
{
|
||||
_fills_sink.OnNext(x);
|
||||
}));
|
||||
_disposables.Add(_dc.subscribe_status(new Predicate<OrderStatus>(x => _order.Id.Equals(x.Order.Id))).Subscribe(x =>
|
||||
{
|
||||
_status = x;
|
||||
_status_sink.OnNext(x);
|
||||
if(is_done_state(x.Status))
|
||||
exit();
|
||||
}));
|
||||
|
||||
var clone = _order.Clone();
|
||||
clone.LimitOrder = new LimitOrder();
|
||||
_exchange.send_order(clone);
|
||||
//_handle = spawn_limit_order(_order.Security, _order.Size, _order.Price, _order.Side, _order.TimeInForce);
|
||||
_handle = create_order<LimitOrder>(_order.Security, _order.Size, _order.Price, _order.Side,
|
||||
_order.TimeInForce, new LimitOrder(), _order.CrossingHedgeOrder.PreAssignedId);
|
||||
track_child(_handle);
|
||||
_handle.spawn();
|
||||
}
|
||||
|
||||
override protected void on_child_status(OrderStatus child_status, ref OrderStatus merged_status)
|
||||
{
|
||||
base.on_child_status(child_status, ref merged_status);
|
||||
_status = child_status;
|
||||
}
|
||||
|
||||
|
||||
void watch_hedges(BBOType bbo)
|
||||
{
|
||||
if(_status != null)
|
||||
if(_status != null && !is_final_state(_status.Status))
|
||||
{
|
||||
PriceSize bid_or_ask;
|
||||
if(_status.Order.Side == Side.Buy)
|
||||
if(_order.Side == Side.Buy)
|
||||
bid_or_ask = bbo.Item2;
|
||||
else
|
||||
bid_or_ask = bbo.Item1;
|
||||
@@ -62,25 +58,25 @@ namespace mbts.spark.orders
|
||||
uint distance = Convert.ToUInt32(Math.Abs(bid_or_ask.price - _status.Order.Price) / compute_tick(_order.Security));
|
||||
double tick = (_order.Side == Side.Buy ? 1.0 : -1.0) * compute_tick(_order.Security);
|
||||
if(distance > _order.CrossingHedgeOrder.TicksThreshold)
|
||||
_exchange.modify_price(_order.Id, _status.Order.Price + _order.CrossingHedgeOrder.MarketCrossTicks * tick);
|
||||
_handle.modify_price(_status.Order.Price + _order.CrossingHedgeOrder.MarketCrossTicks * tick);
|
||||
}
|
||||
}
|
||||
|
||||
bool ICancelable.on_cancel()
|
||||
{
|
||||
_exchange.cancel_order(_order.Id);
|
||||
_handle.cancel();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IModifiable.on_modify_price(double new_price)
|
||||
{
|
||||
_exchange.modify_price(_order.Id, new_price);
|
||||
_handle.modify_price( new_price);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool IModifiable.on_modify_size(uint new_size)
|
||||
{
|
||||
_exchange.modify_size(_order.Id, new_size);
|
||||
_handle.modify_size(new_size);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,10 +50,7 @@ namespace mbts.spark.orders
|
||||
else
|
||||
{
|
||||
if(current_order == null) //no current order, send one
|
||||
{
|
||||
var ord = spawn_limit_order(sec, size, price, side, _order.TimeInForce);
|
||||
track_child(ord);
|
||||
}
|
||||
spawn_limit_order(sec, size, price, side, _order.TimeInForce);
|
||||
else
|
||||
update_existing_order(current_order, price, size, side, this_leg_book, param, bypass_quote_rules);
|
||||
}
|
||||
@@ -194,6 +191,11 @@ namespace mbts.spark.orders
|
||||
return true;
|
||||
}
|
||||
|
||||
protected override void on_child_status(OrderStatus child_status, ref OrderStatus merged_status)
|
||||
{
|
||||
merged_status.Order.Price = _order_price;
|
||||
merged_status.Order.Size = _order_size;;
|
||||
}
|
||||
bool IModifiable.on_modify_price(double new_price)
|
||||
{
|
||||
_order_price = new_price;
|
||||
@@ -231,11 +233,24 @@ namespace mbts.spark.orders
|
||||
|
||||
void IPollable.on_poll() { }
|
||||
|
||||
public override void on_spawn()
|
||||
{
|
||||
base.on_spawn();
|
||||
OrderStatus merged = new OrderStatus();
|
||||
merged.Order = _order.Clone();
|
||||
merged.Status = OrderStatus.Types.Status.New;
|
||||
_status_sink.OnNext(merged);
|
||||
}
|
||||
|
||||
public override void on_destroy()
|
||||
{
|
||||
_paused = true;
|
||||
lock(_destroy_lock)
|
||||
{
|
||||
OrderStatus merged = new OrderStatus();
|
||||
merged.Order = _order.Clone();
|
||||
merged.Status = OrderStatus.Types.Status.Done;
|
||||
_status_sink.OnNext(merged);
|
||||
base.on_destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ using BookType = System.Tuple<mbts.co2.PriceSize[], mbts.co2.PriceSize[]>;
|
||||
|
||||
namespace mbts.spark.orders
|
||||
{
|
||||
abstract class SyntheticOrderBase : OrderActorBase
|
||||
abstract class SyntheticOrderBase : OrderActorBase, IParentSearch
|
||||
{
|
||||
readonly protected object _destroy_lock = new object();
|
||||
readonly protected IMarketDataSource _md;
|
||||
@@ -27,6 +27,14 @@ namespace mbts.spark.orders
|
||||
foreach(var ven in _leg_ratios.Keys) //TODO: Multi exchange
|
||||
fabric.find_wellknown_service<IMarketDataSource>(ven.Exchange, out _md);
|
||||
}
|
||||
|
||||
public OrderID find_parent_id(OrderID oid)
|
||||
{
|
||||
if(_children.ContainsKey(oid))
|
||||
return this._order.Id;
|
||||
else
|
||||
return null;
|
||||
}
|
||||
|
||||
protected class HedgeInfo
|
||||
{
|
||||
@@ -79,12 +87,9 @@ namespace mbts.spark.orders
|
||||
|
||||
async Task reduce_and_hedge(Fill fill)
|
||||
{
|
||||
//if this fill was not because of a hedge, fire a hedge
|
||||
if(!_hedges.Contains(fill.Order.Id))
|
||||
{
|
||||
//send a hedge
|
||||
await hedge_working_order(fill);
|
||||
//await reduce_working(fill.Order.Security, fill.Size, fill.Side, fill.Order.Id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,6 +98,7 @@ namespace mbts.spark.orders
|
||||
bool gotone = false;
|
||||
var existing = _child_status.Where(x => x.Value.Order.Security.Equals(sec) &&
|
||||
x.Value.Order.Side == side &&
|
||||
!is_final_state(x.Value.Status) &&
|
||||
!_hedges.Contains(x.Key) );
|
||||
foreach(var x in existing)
|
||||
{
|
||||
@@ -100,8 +106,7 @@ namespace mbts.spark.orders
|
||||
{
|
||||
IOrderHandle existing_working;
|
||||
if(_children.TryGetValue(x.Key, out existing_working))
|
||||
{
|
||||
gotone = true;
|
||||
{
|
||||
if(all || size >= x.Value.Order.Size)
|
||||
await existing_working.cancel();
|
||||
else
|
||||
@@ -109,6 +114,8 @@ namespace mbts.spark.orders
|
||||
UInt32 new_size = x.Value.Order.Size - size;
|
||||
await existing_working.modify_size(new_size);
|
||||
}
|
||||
gotone = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,6 +123,7 @@ namespace mbts.spark.orders
|
||||
}
|
||||
|
||||
|
||||
readonly ConcurrentBag<IDisposable> _hedge_disposables = new ConcurrentBag<IDisposable>();
|
||||
async Task hedge_working_order(Fill fill)
|
||||
{
|
||||
if(_order.Security.Equals(fill.Order.Security))
|
||||
@@ -131,41 +139,41 @@ namespace mbts.spark.orders
|
||||
double hedge_price = kv.Value.price;
|
||||
hedge_price = compute_hedge_price(kv.Value.leg, hedge_side, hedge_size, kv.Value.leg_params, hedge_price);
|
||||
|
||||
//look for existing
|
||||
//var existing = _child_status.Where(x => x.Value.Order.Security.Equals(kv.Key) &&
|
||||
// x.Value.Order.Side == hedge_side &&
|
||||
// x.Value.Order.Price == hedge_price);
|
||||
|
||||
//if(existing.Any())
|
||||
//{
|
||||
// var existing_status = existing.First();
|
||||
// IOrderHandle existing_order;
|
||||
// if(_children.TryGetValue(existing_status.Key, out existing_order))
|
||||
// {
|
||||
// var res = await existing_order.modify_size(existing_status.Value.Order.Size + hedge_size);
|
||||
// if(res.result)
|
||||
// continue;
|
||||
// }
|
||||
//}
|
||||
|
||||
double tick = compute_tick(kv.Key);
|
||||
PostHedgePriceBasedForcedCross post = null;
|
||||
if(post.Priority.IsActive)
|
||||
post = kv.Value.leg_params.PostHedgeParams.PriceBasedCross;
|
||||
PostHedgePriceBasedForcedCross post = kv.Value?.leg_params?.PostHedgeParams?.PriceBasedCross;
|
||||
var active = post?.Priority?.IsActive;
|
||||
var cross = new CrossingHedgeOrder
|
||||
{
|
||||
TicksThreshold = (post == null) ? 1000 : post.TicksThreshold,
|
||||
MarketCrossTicks = (post == null) ? 0 : post.MarketCrossTicks,
|
||||
TicksThreshold = (active.HasValue && active.Value) ? post.TicksThreshold : 1000,
|
||||
MarketCrossTicks = (active.HasValue && active.Value) ? post.MarketCrossTicks : 0
|
||||
};
|
||||
cross.PreAssignedId = generate_order_id();
|
||||
_hedges.Add(cross.PreAssignedId);
|
||||
|
||||
var hedge = create_order<CrossingHedgeOrder>(kv.Value.leg, hedge_size, hedge_price,
|
||||
hedge_side, Order.Types.TimeInForce.Day, cross);
|
||||
_hedges.Add(hedge.order_id);
|
||||
track_child(hedge);
|
||||
await hedge.spawn();
|
||||
//there is a race here. the working leg comes back as filled, and the other working leg was cancelled before the hedge was sent
|
||||
//this puts the parent order in a terminal state, no longer listening to fills, etc. This has the unintended side effect of
|
||||
//'eating' the hedge leg fills
|
||||
//track_child(hedge);
|
||||
_children[hedge.order_id] = hedge;
|
||||
_hedge_disposables.Add(hedge.order_status.Subscribe(x =>
|
||||
{
|
||||
_child_status[x.Order.Id] = x;
|
||||
compute_status_internal(x);
|
||||
}));
|
||||
_hedge_disposables.Add(hedge.fills.Subscribe(x =>
|
||||
{
|
||||
_child_fills.Add(x);
|
||||
compute_fill_internal(x);
|
||||
}));
|
||||
|
||||
//reduce any working quantity by the amount of the hedge
|
||||
//initially I meant to reduce working on hedge fills, but now that I see it in action, there's too many orders out if we do it that way
|
||||
await reduce_working(kv.Value.leg, hedge_size, hedge_side);
|
||||
|
||||
await hedge.spawn();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace mbts.spark.orders
|
||||
if(order.ExecutionStrategy != null && order.ExecutionStrategy.LegParamsMap != null)
|
||||
order.ExecutionStrategy.LegParamsMap.ForEach(x => _execution_strategy.TryAdd(x.Key, x.Value));
|
||||
}
|
||||
|
||||
|
||||
protected IOrderHandle spawn_limit_order(Security sec, uint size, double price, Side side,
|
||||
Order.Types.TimeInForce tif = Order.Types.TimeInForce.Day)
|
||||
{
|
||||
@@ -123,8 +123,6 @@ namespace mbts.spark.orders
|
||||
if(_children.TryRemove(child_status.Order.Id, out handle))
|
||||
_ex_children.TryAdd(child_status.Order.Id, handle);
|
||||
}
|
||||
merged_status.Children.AddRange(_children.Select(x => x.Key));
|
||||
merged_status.Children.AddRange(_ex_children.Select(x => x.Key));
|
||||
}
|
||||
|
||||
override protected void track_child(IOrderHandle algo)
|
||||
|
||||
@@ -82,10 +82,10 @@ namespace mbts.spark.orders
|
||||
|
||||
protected IOrderHandle create_order<T>(Security sec, uint size, double price, Side side,
|
||||
Order.Types.TimeInForce tif = Order.Types.TimeInForce.Day,
|
||||
T algo_order_params = default(T)) where T : new()
|
||||
T algo_order_params = default(T), OrderID id = null) where T : new()
|
||||
{
|
||||
Order ord = ActorMapping.create_order_of_type<T>(algo_order_params);
|
||||
ord.Id = generate_order_id();
|
||||
ord.Id = id ?? generate_order_id();
|
||||
ord.Security = sec;
|
||||
ord.Price = price;
|
||||
ord.Size = size;
|
||||
|
||||
@@ -7,21 +7,23 @@ using System.ComponentModel.Composition;
|
||||
using mbts.ui.shell;
|
||||
using bts.api;
|
||||
using mbts;
|
||||
using System.Reactive.Linq;
|
||||
using security_key = System.UInt32;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
[Export(typeof(IInitializable))]
|
||||
class MDSource : IObserver<List<SecurityAndHandle>>, IInitializable
|
||||
{
|
||||
private readonly bts.api.IBus _bus;
|
||||
private readonly IBus _bus;
|
||||
private readonly MDConsumer _consumer;
|
||||
private List<IDisposable> _disp_list = new List<IDisposable> ();
|
||||
private IDictionary<security_key, SecurityMD> _exchange_sec_map = new Dictionary<security_key, SecurityMD> (),
|
||||
_synthetic_sec_map = new Dictionary<security_key, SecurityMD> ();
|
||||
|
||||
[ImportingConstructor]
|
||||
public MDSource(bts.api.IBus bus, [Import("username")] string username)
|
||||
public MDSource(IBus bus, [Import("username")] string username)
|
||||
{
|
||||
_bus = bus;
|
||||
_consumer = Co2RelayControl.instance.consumer;
|
||||
@@ -37,12 +39,14 @@ namespace mbts.spark
|
||||
|
||||
public void OnNext(List<SecurityAndHandle> values)
|
||||
{
|
||||
foreach (var v in values) {
|
||||
_exchange_sec_map.Add(v.security.Id, new SecurityMD(new bts.api.Security(v.security), v.handle));
|
||||
if (values.Count > 0) {
|
||||
var temp = new Dictionary<security_key, SecurityMD>(_exchange_sec_map);
|
||||
foreach (var v in values) {
|
||||
temp.Add(v.security.Id, new SecurityMD(v.security, v.handle));
|
||||
}
|
||||
_exchange_sec_map = temp;
|
||||
//_publish_securities();
|
||||
}
|
||||
//Logger.info(bts.log.Subsystem.MarketData, $"Publishing {_security_state.Count} securities.");
|
||||
_publish_securities();
|
||||
//_bus.post(SparkTags.SecuritiesTag, new Dictionary<security_key, SecurityMD>(_exchange_sec_map));
|
||||
}
|
||||
|
||||
public int priority { get { return 0; } }
|
||||
@@ -52,6 +56,26 @@ namespace mbts.spark
|
||||
_disp_list.Add (_consumer.on_security.Subscribe(this));
|
||||
_disp_list.Add (_bus.subscribe<SparkBusData.SyntheticSecuritiesMessage> (SparkTags.SyntheticSecuritiesTag).Subscribe (i => _on_synthetic_securities (i)));
|
||||
new DataPersistor(_bus);
|
||||
Task.Run(run);
|
||||
}
|
||||
|
||||
async Task run() {
|
||||
int count = 0;
|
||||
while (true) {
|
||||
var exch = _exchange_sec_map;
|
||||
var synth = _synthetic_sec_map;
|
||||
var newcount = exch.Count + synth.Count;
|
||||
if (newcount > count) {
|
||||
count = newcount;
|
||||
try {
|
||||
_publish_securities();
|
||||
}
|
||||
catch (Exception e) {
|
||||
Logger.error(bts.log.Subsystem.MarketData, $"Error in publish_securities: {e}");
|
||||
}
|
||||
}
|
||||
await Task.Delay(TimeSpan.FromSeconds(1));
|
||||
}
|
||||
}
|
||||
|
||||
private void _on_synthetic_securities(SparkBusData.SyntheticSecuritiesMessage synth_secs)
|
||||
@@ -59,7 +83,7 @@ namespace mbts.spark
|
||||
if (synth_secs != null && synth_secs.data != null)
|
||||
{
|
||||
_synthetic_sec_map = synth_secs.data.ToDictionaryDupes(s => s.Key, s => new SecurityMD(s.Value.Security, new SyntheticSecurityMDHandle(s.Value.Security, _exchange_sec_map)));
|
||||
_publish_securities();
|
||||
//_publish_securities();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,7 +95,7 @@ namespace mbts.spark
|
||||
Security sec = kv.Value.security;
|
||||
rv.Add(sec.Id, new SecurityMD(sec, new SyntheticSecurityMDHandle(sec, _exchange_sec_map)));
|
||||
}
|
||||
mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, String.Format("MDSource publishing {0} securities", rv.Count));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, String.Format("MDSource publishing {0} securities", rv.Count));
|
||||
_bus.post(SparkTags.SecuritiesTag, rv);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,10 +35,10 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
|
||||
public static double tickup(this ContractSpecification contract, double value) { return _get_regional_ticks(contract).tickup(value); }
|
||||
public static double tickup(this ContractSpecification contract, double value, int count) { return _get_regional_ticks(contract).tickup(value, (uint)count); }
|
||||
public static double tickdown(this ContractSpecification contract, double value) { return _get_regional_ticks(contract).tickdown(value); }
|
||||
public static double tickdown(this ContractSpecification contract, double value, int count) { return _get_regional_ticks(contract).tickdown(value, (uint)count); }
|
||||
public static double tickup(this ContractSpecification contract, double value) { return get_regional_ticks(contract).tickup(value); }
|
||||
public static double tickup(this ContractSpecification contract, double value, int count) { return get_regional_ticks(contract).tickup(value, (uint)count); }
|
||||
public static double tickdown(this ContractSpecification contract, double value) { return get_regional_ticks(contract).tickdown(value); }
|
||||
public static double tickdown(this ContractSpecification contract, double value, int count) { return get_regional_ticks(contract).tickdown(value, (uint)count); }
|
||||
|
||||
public static double round_to_tick(this ContractSpecification spec, double value) {
|
||||
double intpart = (long)value;
|
||||
@@ -52,7 +52,7 @@ namespace mbts.spark {
|
||||
double low = Math.Min(a, b);
|
||||
double high = Math.Max(a, b);
|
||||
int count = 0;
|
||||
while (a < b) {
|
||||
while (a < b && count < 1000000) {
|
||||
++count;
|
||||
a = tickup(spec, a);
|
||||
}
|
||||
@@ -62,7 +62,7 @@ namespace mbts.spark {
|
||||
public static int[] get_tick_jump_quantities(ContractSpecification spec) {
|
||||
return _ticks_cache.TryGetValue(spec.LowTick, out (TickFactors tf, int[] jumps) result) ? result.jumps : new[] { 1, 5, 10, 25, 50, 100 };
|
||||
}
|
||||
public static RegionalTickFactors _get_regional_ticks(ContractSpecification spec) {
|
||||
public static RegionalTickFactors get_regional_ticks(ContractSpecification spec) {
|
||||
return _regional_ticks_cache.GetOrAdd((spec.LowTick, spec.HighTick, spec.PriceBreak), _create_regional_ticks);
|
||||
}
|
||||
private static RegionalTickFactors _create_regional_ticks((double low_tick, double high_tick, double price_break) def) {
|
||||
|
||||
@@ -29,7 +29,7 @@ namespace mbts.spark {
|
||||
|
||||
public void cancel_orders(CancelType ct) {
|
||||
order_gateway.cancel_security_orders (new uint[] {security.Id}, ct == CancelType.Bids || ct == CancelType.All, ct == CancelType.Asks || ct == CancelType.All);
|
||||
Logger.info(bts.log.Subsystem.ui, $"Cancel {ct}");
|
||||
Logger.info(bts.log.Subsystem.Ui, $"Cancel {ct}");
|
||||
}
|
||||
|
||||
public OrdersModel order_gateway => _order_gateway;
|
||||
|
||||
@@ -51,14 +51,15 @@ namespace mbts.spark {
|
||||
panel.Children.Add(mkbadge(order));
|
||||
}
|
||||
}
|
||||
public void remove_order(OrderVM order) {
|
||||
_orders.Remove(order);
|
||||
public bool remove_order(OrderVM order) {
|
||||
bool result = _orders.Remove(order);
|
||||
foreach (var panel in _stacks.Values) {
|
||||
var todelete = panel.Children.OfType<Badge>().Where(b => b.DataContext == order).ToList();
|
||||
foreach (var item in todelete) {
|
||||
panel.Children.Remove(item);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public void clear_orders() {
|
||||
@@ -109,11 +110,12 @@ namespace mbts.spark {
|
||||
if (e.Data.GetDataPresent(typeof(OrderVM))) {
|
||||
OrderVM vm = e.Data.GetData(typeof(OrderVM)) as OrderVM;
|
||||
if (vm != null && vm.security_key == security_key) {
|
||||
Logger.info(bts.log.Subsystem.ui, "Drop - " + vm.summary);
|
||||
Logger.info(bts.log.Subsystem.Ui, "Drop - " + vm.summary);
|
||||
double price = _parent.price_for_point(e.GetPosition(_parent));
|
||||
if (vm.try_change_price(price)) {
|
||||
remove_order(vm);
|
||||
add_order(vm);
|
||||
if (remove_order(vm)) {
|
||||
add_order(vm);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace mbts.spark {
|
||||
|
||||
public bool scroll_bar_visible { get; set; }
|
||||
public int ticks_to_recenter { get; set; } = 3;
|
||||
public int seconds_to_recenter { get; set; } = 300;
|
||||
public int seconds_to_recenter { get; set; } = 30;
|
||||
|
||||
public string SelectedAlgo { get; set; } = "LimitOrder";
|
||||
public string DefaultTimeInForce { get; set; } = "Day";
|
||||
|
||||
@@ -71,6 +71,8 @@ namespace mbts.spark {
|
||||
public Security security => _model.security;
|
||||
public IMDHandle md => _model.md;
|
||||
|
||||
public bool is_synthetic => _model.security.ContractCase == Security.ContractOneofCase.Synthetic;
|
||||
|
||||
private void tick(object sender, EventArgs e) {
|
||||
update_header();
|
||||
on_tick?.Invoke();
|
||||
@@ -99,7 +101,15 @@ namespace mbts.spark {
|
||||
_open.set(spec.format(md.open_price));
|
||||
ulong unused = 0;
|
||||
md.get_last_trade(ref unused, out NativePriceSize last, out DateTime time, out ulong volume);
|
||||
_change.set(spec.format(last.price - md.settlement_price));
|
||||
if (!double.IsNaN(last.price)) {
|
||||
_change.set(spec.format(last.price - md.settlement_price));
|
||||
}
|
||||
else {
|
||||
unused = 0;
|
||||
_model.md.get_bbo(ref unused, out NativePriceSize bid, out NativePriceSize ask);
|
||||
double mid = TickUtils.mid_tick(spec, bid.price, ask.price);
|
||||
_change.set(spec.format(mid - md.settlement_price));
|
||||
}
|
||||
_volume.set(volume);
|
||||
}
|
||||
}
|
||||
@@ -205,7 +215,7 @@ namespace mbts.spark {
|
||||
//Logger.notnull(i);
|
||||
if (i == null) {
|
||||
var msg = String.Join(" ",my_orders.Select(m => m.ID().Id));
|
||||
Logger.error(bts.log.Subsystem.ui, $"Equality problem in order {o.id} should be in {msg}.");
|
||||
Logger.error(bts.log.Subsystem.Ui, $"Equality problem in order {o.id} should be in {msg}.");
|
||||
}
|
||||
if (i != null) {
|
||||
o.update(i);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
xmlns:usp="clr-namespace:mbts.ui.spark"
|
||||
xmlns:uag="clr-namespace:mbts.ui.spark.algo"
|
||||
xmlns:sys="clr-namespace:System;assembly=mscorlib"
|
||||
xmlns:converters="clr-namespace:mbts.ui.converters"
|
||||
Height="600"
|
||||
Width="400"
|
||||
TextElement.FontSize="11">
|
||||
@@ -15,6 +16,15 @@
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="/view/Controls/Algo/AlgoDetailsPopupControl.xaml"/>
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
<converters:BooleanToVisibilityConverter x:Key="BoolToInVisibility" VisibilityForTrue="Collapsed" VisibilityForFalse="Visible" />
|
||||
<converters:BooleanToObjectConverter x:Key="bool_to_margin">
|
||||
<converters:BooleanToObjectConverter.ValueForTrue>
|
||||
<Thickness />
|
||||
</converters:BooleanToObjectConverter.ValueForTrue>
|
||||
<converters:BooleanToObjectConverter.ValueForFalse>
|
||||
<Thickness Top="32" />
|
||||
</converters:BooleanToObjectConverter.ValueForFalse>
|
||||
</converters:BooleanToObjectConverter>
|
||||
</ResourceDictionary>
|
||||
</UserControl.Resources>
|
||||
<Grid>
|
||||
@@ -32,15 +42,10 @@
|
||||
<ComboBox Grid.ColumnSpan="2" Margin="2" ItemsSource="{Binding accounts}" SelectedItem="{Binding account}"/>
|
||||
<ComboBox ItemsSource="{Binding order_types}" SelectedItem="{Binding selected_order_type}" Margin="2" />
|
||||
<uag:AlgoDetailsPopupControl ItemsSource="{Binding algo_types}" SelectedItem="{Binding selected_algo_type}" Margin="2" ExpandDirection="Left"/>
|
||||
<StackPanel Margin="0,0,0,5">
|
||||
<Button Height="30" Margin="2" Command="{Binding cancel_command}" CommandParameter="All">Cxl All</Button>
|
||||
<Button Margin="2" Command="{Binding cancel_command}" CommandParameter="Bids" Background="{mbts:BTSColor MarketData.bid}" Foreground="White">Cxl Bids</Button>
|
||||
<Button Margin="2" Command="{Binding cancel_command}" CommandParameter="Asks" Background="{mbts:BTSColor MarketData.ask}" Foreground="White">Cxl Asks</Button>
|
||||
</StackPanel>
|
||||
<!-- reset to defaults after order -->
|
||||
<CheckBox IsChecked="{Binding revert}">Revert</CheckBox>
|
||||
|
||||
<TextBox HorizontalContentAlignment="Right" Text="{Binding calculator.value}" Margin="2" />
|
||||
<TextBox HorizontalContentAlignment="Right" Text="{Binding calculator.value}" Margin="2,15,2,0" />
|
||||
<ItemsControl ItemsSource="{Binding calculator.buttons}" Focusable="False">
|
||||
<ItemsControl.ItemsPanel>
|
||||
<ItemsPanelTemplate>
|
||||
@@ -54,10 +59,16 @@
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
<Button Margin="2" HorizontalAlignment="Stretch" Command="{Binding calculator.click}" CommandParameter="0">Clear</Button>
|
||||
<StackPanel Margin="0,15,0,5">
|
||||
<Button Height="30" Margin="2" Command="{Binding cancel_command}" CommandParameter="All">Cxl All</Button>
|
||||
<Button Margin="2" Command="{Binding cancel_command}" CommandParameter="Bids" Background="{mbts:BTSColor MarketData.bid}" Foreground="White">Cxl Bids</Button>
|
||||
<Button Margin="2" Command="{Binding cancel_command}" CommandParameter="Asks" Background="{mbts:BTSColor MarketData.ask}" Foreground="White">Cxl Asks</Button>
|
||||
</StackPanel>
|
||||
</StackPanel>
|
||||
<Button Margin="5,0,5,5" VerticalAlignment="Bottom" HorizontalAlignment="Stretch" Command="{Binding show_ticket_command}">Ticket</Button>
|
||||
|
||||
<Grid Grid.Column="1" Margin="4" Height="24" VerticalAlignment="Top" TextBlock.FontSize="9">
|
||||
<Grid Grid.Column="1" Margin="4" Height="24" VerticalAlignment="Top" TextBlock.FontSize="9"
|
||||
Visibility="{Binding is_synthetic,Converter={StaticResource BoolToInVisibility}}">
|
||||
<Grid.Resources>
|
||||
<Thickness x:Key="text_margin" Right="2" />
|
||||
</Grid.Resources>
|
||||
@@ -81,23 +92,27 @@
|
||||
<TextBlock Grid.Column="4" Grid.Row="0" Text="{Binding open, Mode=OneWay}" FontWeight="Bold" />
|
||||
<TextBlock Grid.Column="4" Grid.Row="1" Text="{Binding volume, Mode=OneWay}" FontWeight="Bold" />
|
||||
|
||||
<spark:RecenterCountdown Grid.Column="2" Grid.RowSpan="3"
|
||||
Width="18" Height="18" Margin="4"
|
||||
<spark:RecenterCountdown Grid.Column="5" Grid.RowSpan="2"
|
||||
Width="16" Height="16" Margin="2"
|
||||
Command="{Binding RecenterCommand, ElementName=_ladder}"
|
||||
Foreground="Black" Background="Transparent" BorderBrush="Transparent" BorderThickness="0"
|
||||
PieBackground="Black" SliceBackground="White" />
|
||||
</Grid>
|
||||
<spark:LadderGridHost x:Name="_ladder" Grid.Column="1" Margin="0,32,0,0" Command="{Binding send_order_command}" Orders="{Binding orders}">
|
||||
<spark:LadderGridHost x:Name="_ladder" Grid.Column="1" Margin="{Binding Path=is_synthetic, Converter={StaticResource bool_to_margin}}" Command="{Binding send_order_command}" Orders="{Binding orders}">
|
||||
<spark:LadderGridHost.Resources>
|
||||
<Style TargetType="controls:Badge">
|
||||
<Setter Property="Background" Value="{Binding background}" />
|
||||
<Setter Property="BorderBrush" Value="{Binding border}" />
|
||||
<Setter Property="Text" Value="{Binding text}" />
|
||||
<Setter Property="Foreground" Value="Black" />
|
||||
<Setter Property="TopText" Value="{Binding line1}" />
|
||||
<Setter Property="BottomText" Value="{Binding line2}" />
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Setter Property="Width" Value="14" />
|
||||
<Setter Property="Height" Value="8" />
|
||||
<Setter Property="Margin" Value="1" />
|
||||
<Setter Property="Margin" Value="0" />
|
||||
<Setter Property="ToolTip" Value="{Binding summary}" />
|
||||
<Setter Property="CornerRadius" Value="1" />
|
||||
<Setter Property="Opacity" Value="{Binding opacity}" />
|
||||
<Setter Property="ContextMenu">
|
||||
<Setter.Value>
|
||||
<ContextMenu>
|
||||
|
||||
@@ -9,6 +9,7 @@ using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using System.Windows.Input;
|
||||
using security_key = System.UInt32;
|
||||
using bts.api;
|
||||
|
||||
namespace mbts.spark {
|
||||
class OrderVM : ViewModelBase, IEquatable<OrderVM> {
|
||||
@@ -28,8 +29,7 @@ namespace mbts.spark {
|
||||
var fill_ratio = OrderUtils.fill_ratio(status);
|
||||
background = mkbrush(_color, _colorbg, fill_ratio);
|
||||
hoverbackground = mkbrush(_dark, _darkbg, fill_ratio);
|
||||
|
||||
border = parentmeta == null ? Brushes.Black : new SolidColorBrush(parentmeta.Color.rgb_color());
|
||||
border = _order.order().Side == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask;
|
||||
}
|
||||
|
||||
Brush mkbrush(Color color, Color endcolor, double pct_complete) {
|
||||
@@ -60,13 +60,12 @@ namespace mbts.spark {
|
||||
public double price => _order.order().Price;
|
||||
|
||||
public string text => "";
|
||||
//public string text {
|
||||
// get {
|
||||
// var fills = OrderUtils.filled(_order);
|
||||
// var remaining = _order.order().Size - fills;
|
||||
// return $"{fills}\r\n{remaining}";
|
||||
// }
|
||||
//}
|
||||
|
||||
private string buy_sell_indicator => _order.order().Side == Side.Buy ? "B" : "S";
|
||||
|
||||
public string line1 => $"{buy_sell_indicator}:{OrderUtils.filled(_order)}";
|
||||
public string line2 => $"W:{_order.order().Size - OrderUtils.filled(_order)}";
|
||||
|
||||
public string summary => OrderUtils.order_summary(_order);
|
||||
|
||||
string generate_desc() {
|
||||
@@ -81,6 +80,7 @@ namespace mbts.spark {
|
||||
|
||||
public string description => generate_desc();
|
||||
|
||||
// == is_child
|
||||
public bool has_parent => _order.parent_id() != null;
|
||||
|
||||
public ICommand shatter_command => new DelegateCommand(_ => model.order_gateway.shatter(_order.order().Id), _ => !has_parent);
|
||||
@@ -90,7 +90,9 @@ namespace mbts.spark {
|
||||
public Brush foreground => Brushes.Black;
|
||||
public Brush background { get; private set; }
|
||||
public Brush hoverbackground { get; private set; }
|
||||
public Brush header_brush => _order.order().Side == bts.api.Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask;
|
||||
public Brush header_brush => _order.order().Side == Side.Buy ? BTSColors.MarketData.bid : BTSColors.MarketData.ask;
|
||||
|
||||
public double opacity => has_parent ? 0.5 : 1.0;
|
||||
|
||||
public Brush border { get; }
|
||||
|
||||
|
||||
@@ -6,7 +6,6 @@ using mbts.spark.utilities;
|
||||
using mbts.ui;
|
||||
using mbts.ui.controls;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utilities;
|
||||
using mbts.ui.utility;
|
||||
using ProtoBuf;
|
||||
|
||||
@@ -6,6 +6,7 @@ using System.Threading.Tasks;
|
||||
using bts.api;
|
||||
using bts.spark;
|
||||
using mbts;
|
||||
using mbts.utils;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
@@ -37,6 +38,7 @@ namespace mbts.spark
|
||||
{
|
||||
m.data.order.Id = new OrderID() { Id = Guid.NewGuid().ToString() };
|
||||
m.data.order.User = _user;
|
||||
m.data.order.Timestamp = LLDateTime.now().value;
|
||||
on_new_order(m.data);
|
||||
}));
|
||||
_disps.Add(_bus.subscribe<SparkBusData.ChangeOrderPriceMessage>(SparkTags.ChangeOrderPriceTag).Subscribe(m => on_price_change(m.data)));
|
||||
|
||||
@@ -10,6 +10,7 @@ using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
using mbts.ui;
|
||||
using Google.Protobuf;
|
||||
using mbts.utils;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
@@ -71,7 +72,7 @@ namespace mbts.spark
|
||||
|
||||
public bool change_price(OrderID order_id, double new_price)
|
||||
{
|
||||
Logger.info(bts.log.Subsystem.ui, $"Change {order_id} price to {new_price}");
|
||||
Logger.info(bts.log.Subsystem.Ui, $"Change {order_id} price to {new_price}");
|
||||
_bus.post (SparkTags.ChangeOrderPriceTag, new SparkBusData.ChangeOrderPriceMessage (new OrderUserActions.ChangeOrderPrice (order_id, new_price)));
|
||||
return true;
|
||||
}
|
||||
@@ -115,15 +116,15 @@ namespace mbts.spark
|
||||
public OrderMetadata get_metadata(Order.AlgoOrderTypeOneofCase order_type) {
|
||||
switch (order_type) {
|
||||
case Order.AlgoOrderTypeOneofCase.MarketOrder:
|
||||
return new OrderMetadata() { KeyBinding = "M", Color = BTSColors.module_colors[0].rgb_color() };
|
||||
return new OrderMetadata() { KeyBinding = "M", Color = BTSColors.yellow.rgb_color(), NoProps = true };
|
||||
case Order.AlgoOrderTypeOneofCase.LimitOrder:
|
||||
return new OrderMetadata() { KeyBinding = "L", Color = BTSColors.module_colors[1].rgb_color() };
|
||||
return new OrderMetadata() { KeyBinding = "L", Color = BTSColors.green.rgb_color(), NoProps = true };
|
||||
case Order.AlgoOrderTypeOneofCase.StopMarketOrder:
|
||||
return new OrderMetadata() { KeyBinding = "SM", Color = BTSColors.module_colors[2].rgb_color() };
|
||||
return new OrderMetadata() { KeyBinding = "SM", Color = BTSColors.orange.rgb_color() };
|
||||
case Order.AlgoOrderTypeOneofCase.StopLimitOrder:
|
||||
return new OrderMetadata() { KeyBinding = "SL", Color = BTSColors.module_colors[3].rgb_color() };
|
||||
return new OrderMetadata() { KeyBinding = "SL", Color = BTSColors.pale_green.rgb_color() };
|
||||
case Order.AlgoOrderTypeOneofCase.IcebergOrder:
|
||||
return new OrderMetadata() { KeyBinding = "I", Color = BTSColors.module_colors[4].rgb_color() };
|
||||
return new OrderMetadata() { KeyBinding = "I", Color = BTSColors.pale_blue.rgb_color() };
|
||||
case Order.AlgoOrderTypeOneofCase.CrossingHedgeOrder:
|
||||
default:
|
||||
case Order.AlgoOrderTypeOneofCase.None:
|
||||
|
||||
@@ -46,7 +46,14 @@ namespace mbts.spark
|
||||
new_fill_size = filled + new_fill_size <= qty ? new_fill_size : qty - filled;
|
||||
if (new_fill_size + filled >= qty)
|
||||
o.OrderStatus.Status = OrderStatus.Types.Status.Filled;
|
||||
o.Fills.Add(new Fill() { Id = new FillID { Id = Guid.NewGuid().ToString() }, Order = o.order(), Side = o.order().Side, Size = (uint)new_fill_size, Price = o.order().Price });
|
||||
o.Fills.Add(
|
||||
new Fill() {
|
||||
Id = new FillID { Id = Guid.NewGuid().ToString() },
|
||||
Timestamp = utils.LLDateTime.now().value,
|
||||
Order = o.order(),
|
||||
Side = o.order().Side,
|
||||
Size = (uint)new_fill_size,
|
||||
Price = o.order().Price });
|
||||
}
|
||||
}
|
||||
_hub.update_orderbook(_orderbook);
|
||||
|
||||
@@ -3,6 +3,7 @@ using mbts.ui.utility;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Threading;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
@@ -12,11 +13,11 @@ namespace mbts.spark
|
||||
public SecuritySelectorVM(IReadOnlyCollection<Security> preselected_securities) : this(preselected_securities, SecuritySource.GetObservable()) { }
|
||||
public SecuritySelectorVM(IReadOnlyCollection<Security> preselected_securities, IObservable<Security[]> securities_stream) {
|
||||
selected_securities = new ObservableCollection<Security>(preselected_securities);
|
||||
securities = new RXObservableCollection<Security>(securities_stream);
|
||||
securities = new RXObservableCollection<Security>(securities_stream, SynchronizationContext.Current, TimeSpan.FromSeconds(1), SecurityHelper.IDEqualityComparer);
|
||||
}
|
||||
|
||||
public RXObservableCollection<Security> securities { get; private set; }
|
||||
public ObservableCollection<Security> selected_securities { get; private set; }
|
||||
public RXObservableCollection<Security> securities { get; }
|
||||
public ObservableCollection<Security> selected_securities { get; }
|
||||
|
||||
protected virtual void OnDispose() { }
|
||||
public void Dispose() { securities.Dispose(); }
|
||||
|
||||
@@ -62,7 +62,7 @@ namespace mbts.spark
|
||||
|
||||
editor_dialog.CommittedValues.Subscribe(
|
||||
x => BTSMessageBox.Show("Write this down: {0}".fmt(x.ToString())),
|
||||
ex => Logger.error(bts.log.Subsystem.ui, "Error: {0}".fmt(ex.Message), "DefaultOrderParametersMenu.cs")
|
||||
ex => Logger.error(bts.log.Subsystem.Ui, "Error: {0}".fmt(ex.Message), "DefaultOrderParametersMenu.cs")
|
||||
);
|
||||
})
|
||||
});
|
||||
|
||||
@@ -27,7 +27,7 @@ namespace mbts.spark
|
||||
public FillsVM(IBus bus, OrdersModel model, IReadOnlyCollection<Security> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria = null) {
|
||||
_bus = bus;
|
||||
_model = model;
|
||||
_securities = new HashSet<Security>(securities);
|
||||
_securities = new HashSet<Security>(securities ?? Enumerable.Empty<Security>());
|
||||
_rows = new ObservableAutoWrapper<Row, FillTuple>(_fills, f => new Row(f, _model));
|
||||
rows_view = CollectionViewSource.GetDefaultView(_rows);
|
||||
if (sorting_criteria != null) rows_view.SortDescriptions.AddRange(sorting_criteria.Select(sc => sc.to_sort_description()));
|
||||
|
||||
@@ -48,7 +48,7 @@
|
||||
<DataGridTextColumn Header="User" CellStyle="{StaticResource RowHeaderCell}" Binding="{Binding user}"/>
|
||||
<DataGridTextColumn Header="Account" CellStyle="{StaticResource RowHeaderCell}" Binding="{Binding account}"/>
|
||||
<DataGridTextColumn Header="Exchange" CellStyle="{StaticResource RowHeaderCell}" Binding="{Binding exchange}"/>
|
||||
<DataGridTextColumn Header="Security" CellStyle="{StaticResource RowHeaderCell}" Binding="{Binding security, StringFormat='q/n:./m:c'}"/>
|
||||
<DataGridTextColumn Header="Security" CellStyle="{StaticResource RowHeaderCell}" Binding="{Binding security}"/>
|
||||
<DataGridTextColumn Header="TIF" Binding="{Binding time_in_force}"/>
|
||||
<usp:DataGridAlgoTypeColumn Header="Algo" ElementStyle="{StaticResource AlgoTypeElement}" SortMemberPath="algo_type"/>
|
||||
<DataGridTextColumn Header="B/S" ElementStyle="{StaticResource SideColorCodedTextElement}" Binding="{Binding side}" />
|
||||
|
||||
@@ -168,7 +168,7 @@ namespace mbts.spark
|
||||
if (msg.data.ContractCase != Security.ContractOneofCase.Synthetic) show_synthetic_editor_warning($"{msg.data} is not a synthetic security.");
|
||||
else if (!_synthetic_strategy_map.TryGetValue(msg.data.Id, out SyntheticExecutionStrategy ses)) {
|
||||
string warn_msg = $"Did not find execution strategy for {msg.data}";
|
||||
Logger.warn(bts.log.Subsystem.ui, warn_msg);
|
||||
Logger.warn(bts.log.Subsystem.Ui, warn_msg);
|
||||
show_synthetic_editor_warning(warn_msg);
|
||||
} else show_synthetic_editor(msg.data, ses.ExecutionStrategy);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ namespace mbts.spark.menu_items
|
||||
|
||||
private readonly IBus _bus;
|
||||
|
||||
public string display_name => "Create Synthetic...";
|
||||
public string display_name => "Create Synthetic Spread...";
|
||||
public int priority => 2;
|
||||
public ImageSource icon => Icons.Tetris;
|
||||
public string sectional_id => MenuItemSections.SecurityWindow;
|
||||
|
||||
@@ -17,7 +17,7 @@ namespace mbts.spark.menu_items
|
||||
|
||||
private readonly IBus _bus;
|
||||
|
||||
public string display_name => "Execution Strategy...";
|
||||
public string display_name => "Edit Synthetic Spread...";
|
||||
public int priority => 1;
|
||||
public ImageSource icon => Icons.Knight;
|
||||
public string sectional_id => MenuItemSections.SecurityWindow;
|
||||
|
||||
@@ -72,7 +72,7 @@ namespace mbts.spark
|
||||
set => ignore();
|
||||
}
|
||||
public string exchange {
|
||||
get => string.Empty;
|
||||
get => "GLBX";
|
||||
set => ignore();
|
||||
}
|
||||
public Order.AlgoOrderTypeOneofCase algo_type {
|
||||
|
||||
@@ -59,7 +59,8 @@ namespace mbts.spark {
|
||||
ObservableCollection<OrderBookEntry> _order_books;
|
||||
OrderIDComparer _order_cmp = new OrderIDComparer();
|
||||
void orders_updated(IOrderBook order_book) {
|
||||
var all = order_book.get_all_orders();
|
||||
// HACK: .Distinct() should not be necessary
|
||||
var all = order_book.get_all_orders().Distinct(_order_cmp);
|
||||
_order_books.sync_with(all, _order_cmp);
|
||||
foreach (var (vm,obj) in orders.Zip(all, (vm,ob)=>(vm,ob))) {
|
||||
vm.update(obj);
|
||||
|
||||
@@ -251,10 +251,10 @@
|
||||
<DataGridTextColumn Header="Filled%" Binding="{Binding percent_filled, StringFormat=P1}" />
|
||||
<DataGridTextColumn Header="Avg Filled" Binding="{Binding average_price}" />
|
||||
<DataGridTextColumn Header="O/C" Binding="{Binding oc}" />
|
||||
<DataGridTextColumn Header="Modifier" Binding="{Binding modifier}" />
|
||||
<!--<DataGridTextColumn Header="Modifier" Binding="{Binding modifier}" />-->
|
||||
<DataGridTextColumn Header="Status" Binding="{Binding status}" />
|
||||
<DataGridTextColumn Header="Algo Params" Binding="{Binding algo_params}" />
|
||||
<DataGridTextColumn Header="BTS Order" Binding="{Binding order_id.Id}" />
|
||||
<!--<DataGridTextColumn Header="BTS Order" Binding="{Binding order_id.Id}" />-->
|
||||
<DataGridTextColumn Header="Exchange Order" Binding="{Binding exchange_id}" />
|
||||
<DataGridTextColumn Header="Broker" Binding="{Binding broker}" />
|
||||
<DataGridTextColumn Header="# Children" Binding="{Binding num_children}" IsReadOnly="true" />
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:sp="clr-namespace:bts.spark;assembly=spark_api"
|
||||
xmlns:u="clr-namespace:mbts.ui"
|
||||
xmlns:c="clr-namespace:mbts.ui.controls"
|
||||
xmlns:cv="clr-namespace:mbts.ui.converters"
|
||||
xmlns:usp="clr-namespace:mbts.ui.spark">
|
||||
<ResourceDictionary.MergedDictionaries>
|
||||
<ResourceDictionary Source="/view/Resources/DataGrid.xaml"/>
|
||||
<ResourceDictionary Source="/view/Resources/DataTemplates.xaml"/>
|
||||
<ResourceDictionary Source="/view/Resources/Converters.xaml"/>
|
||||
</ResourceDictionary.MergedDictionaries>
|
||||
<cv:SyntheticPriceCalcDisplayTextConverter x:Key="SyntheticPriceCalcDisplayConverter"/>
|
||||
<usp:RowHeaderGroupIndentConverter x:Key="RowHeaderGroupIndentConverter" Indent="18"/>
|
||||
<usp:RowHeaderGroupIndentConverter x:Key="ReverseRowHeaderGroupIndentConverter" Indent="-18"/>
|
||||
<usp:DataGridParameterCellTemplateConverter x:Key="ParameterCellTemplateConverter">
|
||||
@@ -30,6 +34,34 @@
|
||||
<TextBlock Text="{Binding value}"/>
|
||||
</DataTemplate>
|
||||
</usp:DataGridParameterCellTemplateConverter.UIntTemplate>
|
||||
<usp:DataGridParameterCellTemplateConverter.QuantityMeasureTemplate>
|
||||
<DataTemplate>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="3*"/>
|
||||
<ColumnDefinition Width="2*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<TextBlock x:Name="AbsoluteLabel" Text="{x:Static cv:QuantityMeasureCaseDisplayTextConverter.ABSOLUTE_TEXT}" FontSize="10" FontStyle="Italic"/>
|
||||
<TextBlock x:Name="RatioLabel" Text="{x:Static cv:QuantityMeasureCaseDisplayTextConverter.RATIO_TEXT}" FontSize="10" FontStyle="Italic"/>
|
||||
<TextBlock x:Name="AbsoluteValue" Grid.Column="1" HorizontalAlignment="Left" Text="{Binding absolute}"/>
|
||||
<TextBlock x:Name="RatioValue" Grid.Column="1" HorizontalAlignment="Left" Text="{Binding ratio}"/>
|
||||
</Grid>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding quantity_case}" Value="{u:Enum absolute, Type={u:Nested sp:QuantityMeasure.QuantityOneofCase}}">
|
||||
<Setter Property="Visibility" TargetName="AbsoluteLabel" Value="Visible"/>
|
||||
<Setter Property="Visibility" TargetName="AbsoluteValue" Value="Visible"/>
|
||||
<Setter Property="Visibility" TargetName="RatioLabel" Value="Collapsed"/>
|
||||
<Setter Property="Visibility" TargetName="RatioValue" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding quantity_case}" Value="{u:Enum Ratio, Type={u:Nested sp:QuantityMeasure.QuantityOneofCase}}">
|
||||
<Setter Property="Visibility" TargetName="RatioLabel" Value="Visible"/>
|
||||
<Setter Property="Visibility" TargetName="RatioValue" Value="Visible"/>
|
||||
<Setter Property="Visibility" TargetName="AbsoluteLabel" Value="Collapsed"/>
|
||||
<Setter Property="Visibility" TargetName="AbsoluteValue" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</usp:DataGridParameterCellTemplateConverter.QuantityMeasureTemplate>
|
||||
</usp:DataGridParameterCellTemplateConverter>
|
||||
<usp:DataGridParameterCellTemplateConverter x:Key="ParameterCellEditingTemplateConverter">
|
||||
<usp:DataGridParameterCellTemplateConverter.BooleanTemplate>
|
||||
@@ -52,6 +84,35 @@
|
||||
<c:TickUpDownUInt Value="{Binding value}"/>
|
||||
</DataTemplate>
|
||||
</usp:DataGridParameterCellTemplateConverter.UIntTemplate>
|
||||
<usp:DataGridParameterCellTemplateConverter.QuantityMeasureTemplate>
|
||||
<DataTemplate>
|
||||
<Grid>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="3*"/>
|
||||
<ColumnDefinition Width="2*"/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<ComboBox VerticalAlignment="Center" Margin="-2,0,0,0" Padding="3,3,0,3" ItemsSource="{u:EnumBindingSource {u:Nested sp:QuantityMeasure.QuantityOneofCase}, Except=None}" SelectedItem="{Binding quantity_case}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Converter={StaticResource QuantityMeasureCaseDisplayConverter}}" FontSize="10" FontStyle="Italic"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<c:TickUpDownDouble x:Name="AbsoluteTickUpDown" Grid.Column="1" HorizontalAlignment="Stretch" Margin="0,0,-2,0" Value="{Binding absolute}"/>
|
||||
<c:TickUpDownDouble x:Name="RatioTickUpDown" Grid.Column="1" HorizontalAlignment="Stretch" Value="{Binding ratio}"/>
|
||||
</Grid>
|
||||
<DataTemplate.Triggers>
|
||||
<DataTrigger Binding="{Binding quantity_case}" Value="{u:Enum absolute, Type={u:Nested sp:QuantityMeasure.QuantityOneofCase}}">
|
||||
<Setter Property="Visibility" TargetName="AbsoluteTickUpDown" Value="Visible"/>
|
||||
<Setter Property="Visibility" TargetName="RatioTickUpDown" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding quantity_case}" Value="{u:Enum Ratio, Type={u:Nested sp:QuantityMeasure.QuantityOneofCase}}">
|
||||
<Setter Property="Visibility" TargetName="RatioTickUpDown" Value="Visible"/>
|
||||
<Setter Property="Visibility" TargetName="AbsoluteTickUpDown" Value="Collapsed"/>
|
||||
</DataTrigger>
|
||||
</DataTemplate.Triggers>
|
||||
</DataTemplate>
|
||||
</usp:DataGridParameterCellTemplateConverter.QuantityMeasureTemplate>
|
||||
</usp:DataGridParameterCellTemplateConverter>
|
||||
<Style x:Key="ExpanderToggleButton" TargetType="ToggleButton">
|
||||
<Setter Property="Template">
|
||||
@@ -165,7 +226,13 @@
|
||||
<TextBlock VerticalAlignment="Center">Name</TextBlock>
|
||||
<TextBox Grid.Column="1" Margin="6,0,0,0" HorizontalAlignment="Stretch" Text="{Binding SyntheticName, RelativeSource={RelativeSource TemplatedParent}}"/>
|
||||
<TextBlock Grid.Column="2" VerticalAlignment="Center" Margin="6,0,0,0">Pricing</TextBlock>
|
||||
<ComboBox Grid.Column="3" Margin="6,0,0,0" ItemsSource="{x:Static usp:SyntheticEditor.PriceCalcItems}" SelectedItem="{Binding PriceCalc, RelativeSource={RelativeSource TemplatedParent}}" ItemTemplate="{StaticResource EnumDescriptionTemplate}"/>
|
||||
<ComboBox Grid.Column="3" Margin="6,0,0,0" ItemsSource="{x:Static usp:SyntheticEditor.PriceCalcItems}" SelectedItem="{Binding PriceCalc, RelativeSource={RelativeSource TemplatedParent}}">
|
||||
<ComboBox.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Converter={StaticResource SyntheticPriceCalcDisplayConverter}}"/>
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<c:HelpButton Grid.Column="4" Margin="3,0,0,0"/>
|
||||
</Grid>
|
||||
<c:DataGridEx x:Name="PART_DataGrid"
|
||||
@@ -177,7 +244,7 @@
|
||||
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
|
||||
VerticalAlignment="{TemplateBinding VerticalAlignment}"
|
||||
HeadersVisibility="All"
|
||||
RowHeaderWidth="250"
|
||||
RowHeaderWidth="265"
|
||||
RowStyle="{StaticResource DataGridRowStyle}"
|
||||
ItemsSource="{Binding ParameterRowsView, RelativeSource={RelativeSource TemplatedParent}}">
|
||||
<DataGrid.Resources>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using bts.api;
|
||||
using bts.spark;
|
||||
using mbts.ui.controls;
|
||||
using mbts.ui.utility;
|
||||
using System;
|
||||
@@ -106,7 +107,7 @@ namespace mbts.ui.spark
|
||||
var dg = (DataGridEx)GetTemplateChild("PART_DataGrid");
|
||||
if (dg != null) {
|
||||
dg.Columns.SetItems(LegTuples.Select(l => {
|
||||
var col = new DataGridColumnInternal(l.leg.Security, ParameterCellTemplateConverter, ParameterCellEditingTemplateConverter) { Width = 60 };
|
||||
var col = new DataGridColumnInternal(l.leg.Security, ParameterCellTemplateConverter, ParameterCellEditingTemplateConverter) { Width = 75 };
|
||||
DataGridEx.SetRightBorder(col, new DataGridExVerticalLine(false, true, System.Windows.Media.Colors.DarkGray, 1));
|
||||
return col;
|
||||
}));
|
||||
@@ -159,6 +160,7 @@ namespace mbts.ui.spark
|
||||
public DataTemplate BooleanTemplate { get; set; }
|
||||
public DataTemplate IntTemplate { get; set; }
|
||||
public DataTemplate UIntTemplate { get; set; }
|
||||
public DataTemplate QuantityMeasureTemplate { get; set; }
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
Type t = (Type)value;
|
||||
@@ -166,6 +168,7 @@ namespace mbts.ui.spark
|
||||
else if (t == typeof(bool)) return BooleanTemplate;
|
||||
else if (t == typeof(int)) return IntTemplate;
|
||||
else if (t == typeof(uint)) return UIntTemplate;
|
||||
else if (t == typeof(QuantityMeasure)) return QuantityMeasureTemplate;
|
||||
else return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
xmlns:u="clr-namespace:mbts.ui"
|
||||
xmlns:c="clr-namespace:mbts.ui.controls"
|
||||
xmlns:usp="clr-namespace:mbts.ui.spark"
|
||||
u:WindowStyle.TitleContent="{Binding}"
|
||||
u:WindowStyle.SizeToContent="WidthAndHeight"
|
||||
Style="{StaticResource BTSDialogTitleTemplate}">
|
||||
<Window.Resources>
|
||||
@@ -24,8 +25,8 @@
|
||||
<u:WindowStyle.TitleContentTemplate>
|
||||
<DataTemplate>
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<Image Margin="3,1" Source="{x:Static u:Icons.Tetris}"/>
|
||||
<TextBlock>Synthetic Editor</TextBlock>
|
||||
<Image Margin="3,1" Source="{Binding icon}"/>
|
||||
<TextBlock Text="{Binding title}"/>
|
||||
</StackPanel>
|
||||
</DataTemplate>
|
||||
</u:WindowStyle.TitleContentTemplate>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using mbts.ui.shell;
|
||||
using bts.spark;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.spark;
|
||||
using System;
|
||||
|
||||
@@ -33,5 +34,49 @@ namespace mbts.spark
|
||||
public override Type data_type => _data_type.Value;
|
||||
public void Dispose() { _sub.Dispose(); }
|
||||
}
|
||||
|
||||
internal class QuantityMeasureCell : ViewModelBase, ICell {
|
||||
public QuantityMeasureCell(RowModelBase<QuantityMeasure> model, LegSpreaderParamsTuple leg_tup) {
|
||||
_model = model;
|
||||
_leg_tup = leg_tup;
|
||||
}
|
||||
private readonly RowModelBase<QuantityMeasure> _model;
|
||||
private readonly LegSpreaderParamsTuple _leg_tup;
|
||||
private uint _absolute;
|
||||
private double _ratio;
|
||||
public Type data_type { get; } = typeof(QuantityMeasure);
|
||||
public event Action value_changed;
|
||||
public double ratio {
|
||||
get => _get_qm().Ratio;
|
||||
set {
|
||||
_get_qm().Ratio = value;
|
||||
_on_value_changed(nameof(ratio));
|
||||
}
|
||||
}
|
||||
public uint absolute {
|
||||
get => _get_qm().Absolute;
|
||||
set {
|
||||
_get_qm().Absolute = value;
|
||||
_on_value_changed(nameof(absolute));
|
||||
}
|
||||
}
|
||||
public QuantityMeasure.QuantityOneofCase quantity_case {
|
||||
get => _get_qm().QuantityCase;
|
||||
set {
|
||||
var qm = _get_qm();
|
||||
if (qm.QuantityCase != value) {
|
||||
switch(value) {
|
||||
case QuantityMeasure.QuantityOneofCase.Absolute: _ratio = qm.Ratio; qm.Absolute = _absolute; _on_value_changed(nameof(absolute)); break;
|
||||
case QuantityMeasure.QuantityOneofCase.Ratio: _absolute = qm.Absolute; qm.Ratio = _ratio; _on_value_changed(nameof(ratio)); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
private QuantityMeasure _get_qm() { return _model.get_value(_leg_tup); }
|
||||
private void _on_value_changed(params string[] props) {
|
||||
RaisePropertyChanged(props);
|
||||
value_changed?.Invoke();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
using bts.api;
|
||||
using bts.spark;
|
||||
using mbts.ui.spark;
|
||||
using mbts.utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -32,8 +31,8 @@ namespace mbts.spark
|
||||
private static class SubsectionNames {
|
||||
public const string
|
||||
Mute = "Mute",
|
||||
InsideMarketDistance = "Mute Inside Mkt Distance",
|
||||
InsideMarketDistanceWithTravel = "Mute Inside Mkt Distance & Move",
|
||||
InsideMarketDistance = "Mute Inside Market Distance",
|
||||
InsideMarketDistanceWithTravel = "Mute Inside Market Distance & Move",
|
||||
Payless = "Pay Less",
|
||||
Payup = "Pay up",
|
||||
OrderType = "Order Type",
|
||||
@@ -86,7 +85,7 @@ namespace mbts.spark
|
||||
internal class IsQuoteModel : RowModelBase<bool> {
|
||||
public override bool get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.IsActiveQuoting; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, bool value) { leg_tup.leg_params.IsActiveQuoting = value; }
|
||||
public override string display_name { get; } = "Is Active Quote";
|
||||
public override string display_name { get; } = "Enable Quoting";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.LegDef };
|
||||
public override bool has_errors(IReadOnlyCollection<LegSpreaderParamsTuple> leg_tups) { return !leg_tups.Any(lt => lt.leg_params.IsActiveQuoting); }
|
||||
}
|
||||
@@ -151,148 +150,34 @@ namespace mbts.spark
|
||||
#endregion
|
||||
|
||||
#region PreHedge
|
||||
internal class PayupRowGroup {
|
||||
public PayupRowGroup() {
|
||||
var is_ratio_model = new ThresholdIsRatioModel();
|
||||
threshold_model = new ThresholdModel(is_ratio_model);
|
||||
this.is_ratio_model = is_ratio_model;
|
||||
}
|
||||
|
||||
public readonly IRowModel is_ratio_model, threshold_model, ticks_model = new TicksModel();
|
||||
|
||||
internal class TicksModel : RowModelBase<uint> {
|
||||
public override string display_name { get; } = "Payup";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payup };
|
||||
public override uint get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.PayupTicks; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, uint value) { leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.PayupTicks = value; }
|
||||
}
|
||||
|
||||
internal class ThresholdIsRatioModel : RowModelBase<bool> {
|
||||
private uint _absolute;
|
||||
private double _ratio;
|
||||
private readonly ObservableDemuxer<Security, QuantityMeasure.QuantityOneofCase> _quantity_case_demuxer = new ObservableDemuxer<Security, QuantityMeasure.QuantityOneofCase>();
|
||||
public override string display_name { get; } = "Is Ratio";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payup };
|
||||
public override bool get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.QuantityCase == QuantityMeasure.QuantityOneofCase.Ratio; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, bool is_ratio) {
|
||||
if (is_ratio) {
|
||||
_absolute = leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.Absolute;
|
||||
leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.Ratio = _ratio;
|
||||
_quantity_case_demuxer.push_data(leg_tup.leg.Security, QuantityMeasure.QuantityOneofCase.Ratio);
|
||||
} else {
|
||||
_ratio = leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.Ratio;
|
||||
leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.Absolute = _absolute;
|
||||
_quantity_case_demuxer.push_data(leg_tup.leg.Security, QuantityMeasure.QuantityOneofCase.Absolute);
|
||||
}
|
||||
}
|
||||
public IObservable<QuantityMeasure.QuantityOneofCase> quantity_case(LegSpreaderParamsTuple leg_tup) {
|
||||
return _quantity_case_demuxer.subscribe(leg_tup.leg.Security).StartWith(leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.QuantityCase);
|
||||
}
|
||||
}
|
||||
|
||||
internal class ThresholdModel : DynamicTypeRowModelBase {
|
||||
public ThresholdModel(ThresholdIsRatioModel is_ratio_model) {
|
||||
_is_ratio_model = is_ratio_model;
|
||||
}
|
||||
private readonly ThresholdIsRatioModel _is_ratio_model;
|
||||
public override string display_name { get; } = "Quantity";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payup };
|
||||
public override object get_value(LegSpreaderParamsTuple leg_tup) {
|
||||
switch (leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.QuantityCase) {
|
||||
case QuantityMeasure.QuantityOneofCase.Absolute: return leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.Absolute;
|
||||
case QuantityMeasure.QuantityOneofCase.Ratio: return leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.Ratio;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, object value) {
|
||||
switch (leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.QuantityCase) {
|
||||
case QuantityMeasure.QuantityOneofCase.Absolute: leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.Absolute = (uint)value; return;
|
||||
case QuantityMeasure.QuantityOneofCase.Ratio: leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold.Ratio = (double)value; return;
|
||||
default: return;
|
||||
}
|
||||
}
|
||||
public override IObservable<Type> data_type(LegSpreaderParamsTuple leg_tup) {
|
||||
return _is_ratio_model.quantity_case(leg_tup).Select(qc => {
|
||||
switch(qc) {
|
||||
case QuantityMeasure.QuantityOneofCase.Absolute: return typeof(uint);
|
||||
case QuantityMeasure.QuantityOneofCase.Ratio: return typeof(double);
|
||||
default: return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
internal class PayupTicksModel : RowModelBase<uint> {
|
||||
public override string display_name { get; } = "Payup";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payup };
|
||||
public override uint get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.PayupTicks; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, uint value) { leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.PayupTicks = value; }
|
||||
}
|
||||
|
||||
internal class PaylessRowGroup {
|
||||
public PaylessRowGroup() {
|
||||
var is_ratio_model = new ThresholdIsRatioModel();
|
||||
threshold_model = new ThresholdModel(is_ratio_model);
|
||||
this.is_ratio_model = is_ratio_model;
|
||||
}
|
||||
internal class PayupThresholdModel : RowModelBase<QuantityMeasure> {
|
||||
public override string display_name { get; } = "Quantity";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payup };
|
||||
public override QuantityMeasure get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, QuantityMeasure value) { leg_tup.leg_params.PreHedgeParams.QuantityBasedPayupTicks.QuantityThreshold = value; }
|
||||
public override ICell create_cell(LegSpreaderParamsTuple leg_tup) { return new QuantityMeasureCell(this, leg_tup); }
|
||||
}
|
||||
|
||||
public readonly IRowModel is_ratio_model, threshold_model, ticks_model = new TicksModel();
|
||||
internal class PaylessTicksModel : RowModelBase<uint> {
|
||||
public override string display_name { get; } = "Payless";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payless };
|
||||
public override uint get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.PaylessTicks; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, uint value) { leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.PaylessTicks = value; }
|
||||
}
|
||||
|
||||
internal class TicksModel : RowModelBase<uint> {
|
||||
public override string display_name { get; } = "Payless";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payless };
|
||||
public override uint get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.PaylessTicks; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, uint value) { leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.PaylessTicks = value; }
|
||||
}
|
||||
|
||||
internal class ThresholdIsRatioModel : RowModelBase<bool> {
|
||||
private uint _absolute;
|
||||
private double _ratio;
|
||||
private readonly ObservableDemuxer<Security, QuantityMeasure.QuantityOneofCase> _quantity_case_demuxer = new ObservableDemuxer<Security, QuantityMeasure.QuantityOneofCase>();
|
||||
public override string display_name { get; } = "Is Ratio";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payless };
|
||||
public override bool get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.QuantityCase == QuantityMeasure.QuantityOneofCase.Ratio; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, bool is_ratio) {
|
||||
if (is_ratio) {
|
||||
_absolute = leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.Absolute;
|
||||
leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.Ratio = _ratio;
|
||||
_quantity_case_demuxer.push_data(leg_tup.leg.Security, QuantityMeasure.QuantityOneofCase.Ratio);
|
||||
} else {
|
||||
_ratio = leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.Ratio;
|
||||
leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.Absolute = _absolute;
|
||||
_quantity_case_demuxer.push_data(leg_tup.leg.Security, QuantityMeasure.QuantityOneofCase.Absolute);
|
||||
}
|
||||
}
|
||||
public IObservable<QuantityMeasure.QuantityOneofCase> quantity_case(LegSpreaderParamsTuple leg_tup) {
|
||||
return _quantity_case_demuxer.subscribe(leg_tup.leg.Security).StartWith(leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.QuantityCase);
|
||||
}
|
||||
}
|
||||
|
||||
internal class ThresholdModel : DynamicTypeRowModelBase {
|
||||
public ThresholdModel(ThresholdIsRatioModel is_ratio_model) {
|
||||
_is_ratio_model = is_ratio_model;
|
||||
}
|
||||
private readonly ThresholdIsRatioModel _is_ratio_model;
|
||||
public override string display_name { get; } = "Quantity";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payless };
|
||||
public override object get_value(LegSpreaderParamsTuple leg_tup) {
|
||||
switch (leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.QuantityCase) {
|
||||
case QuantityMeasure.QuantityOneofCase.Absolute: return leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.Absolute;
|
||||
case QuantityMeasure.QuantityOneofCase.Ratio: return leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.Ratio;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, object value) {
|
||||
switch (leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.QuantityCase) {
|
||||
case QuantityMeasure.QuantityOneofCase.Absolute: leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.Absolute = (uint)value; return;
|
||||
case QuantityMeasure.QuantityOneofCase.Ratio: leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold.Ratio = (double)value; return;
|
||||
default: return;
|
||||
}
|
||||
}
|
||||
public override IObservable<Type> data_type(LegSpreaderParamsTuple leg_tup) {
|
||||
return _is_ratio_model.quantity_case(leg_tup).Select(qc => {
|
||||
switch (qc) {
|
||||
case QuantityMeasure.QuantityOneofCase.Absolute: return typeof(uint);
|
||||
case QuantityMeasure.QuantityOneofCase.Ratio: return typeof(double);
|
||||
default: return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
internal class PaylessThresholdModel : RowModelBase<QuantityMeasure> {
|
||||
public override string display_name { get; } = "Quantity";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.Payless };
|
||||
public override QuantityMeasure get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, QuantityMeasure value) { leg_tup.leg_params.PreHedgeParams.QuantityBasedPaylessTicks.QuantityThreshold = value; }
|
||||
public override ICell create_cell(LegSpreaderParamsTuple leg_tup) { return new QuantityMeasureCell(this, leg_tup); }
|
||||
}
|
||||
|
||||
internal class MaxTicksInsideMarketModel : RowModelBase<uint> {
|
||||
@@ -303,7 +188,7 @@ namespace mbts.spark
|
||||
}
|
||||
|
||||
internal class SendHedgeAsMarketOrderModel : RowModelBase<bool> {
|
||||
public override string display_name { get; } = "Mkt Order Hedge";
|
||||
public override string display_name { get; } = "Market Order Hedge";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PreHedge, SubsectionNames.OrderType };
|
||||
public override bool get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PreHedgeParams.SendHedgeAsMarketOrder.SendHedgeAsMarketOrder; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, bool value) { leg_tup.leg_params.PreHedgeParams.SendHedgeAsMarketOrder.SendHedgeAsMarketOrder = value; }
|
||||
@@ -319,7 +204,7 @@ namespace mbts.spark
|
||||
}
|
||||
|
||||
internal class PostHedgePriceBasedCrossMarketTicks : RowModelBase<uint> {
|
||||
public override string display_name { get; } = "Opposite Mkt Cross Ticks";
|
||||
public override string display_name { get; } = "Opposite Market Cross Ticks";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PostHedge, SubsectionNames.MarketForcedCross };
|
||||
public override uint get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PostHedgeParams.PriceBasedCross.MarketCrossTicks; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, uint value) { leg_tup.leg_params.PostHedgeParams.PriceBasedCross.MarketCrossTicks = value; }
|
||||
@@ -333,7 +218,7 @@ namespace mbts.spark
|
||||
}
|
||||
|
||||
internal class PostHedgeTimeBasedCrossMarketTicks : RowModelBase<uint> {
|
||||
public override string display_name { get; } = "Opposite Mkt Cross Ticks";
|
||||
public override string display_name { get; } = "Opposite Market Cross Ticks";
|
||||
public override string[] section_path { get; } = new[] { SectionNames.PostHedge, SubsectionNames.TimeForcedCross };
|
||||
public override uint get_value(LegSpreaderParamsTuple leg_tup) { return leg_tup.leg_params.PostHedgeParams.TimeBasedForcedCross.MarketCrossTicks; }
|
||||
public override void set_value(LegSpreaderParamsTuple leg_tup, uint value) { leg_tup.leg_params.PostHedgeParams.TimeBasedForcedCross.MarketCrossTicks = value; }
|
||||
|
||||
@@ -6,6 +6,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
@@ -22,27 +23,31 @@ namespace mbts.spark
|
||||
public SyntheticEditorVM(IBus bus, Security synthetic, ExecutionStrategy strategy) {
|
||||
_synthetic = synthetic;
|
||||
leg_tuples = _synthetic.Synthetic.Legs.Select(l => new LegSpreaderParamsTuple(l, strategy.LegParamsMap[l.Security.Id])).ToList();
|
||||
var payless = new PaylessRowGroup();
|
||||
var payup = new PayupRowGroup();
|
||||
rows = new [] {
|
||||
new SizeModel(synthetic.Id != 0),
|
||||
bool is_new = synthetic.Id == 0;
|
||||
if (is_new) {
|
||||
title = "Create Synthetic Spread";
|
||||
icon = Icons.Tetris;
|
||||
} else {
|
||||
title = $"Edit '{synthetic.Synthetic.Name}'";
|
||||
icon = Icons.Knight;
|
||||
}
|
||||
rows = new IRowModel [] {
|
||||
new SizeModel(!is_new),
|
||||
new PriceMultiplierModel(),
|
||||
new IsQuoteModel(),
|
||||
new EnableHedgingModel(),
|
||||
//new MaxOrderMoveModel(),
|
||||
new LeanRatioModel(),
|
||||
new QuoteMuteZoneInsideTicksModel(),
|
||||
new QuoteMuteZoneOutsideTicksModel(),
|
||||
new QuoteInsideMarketDistanceTicksModel(),
|
||||
new QuoteInsideMarketDistanceWithTravelTicksModel(),
|
||||
new QuoteInsideMarketDistanceWithTravelLimitModel(),
|
||||
new LeanRatioModel(),
|
||||
new MaxTicksInsideMarketModel(),
|
||||
payless.is_ratio_model,
|
||||
payless.threshold_model,
|
||||
payless.ticks_model,
|
||||
payup.is_ratio_model,
|
||||
payup.threshold_model,
|
||||
payup.ticks_model,
|
||||
new PaylessThresholdModel(),
|
||||
new PaylessTicksModel(),
|
||||
new PayupThresholdModel(),
|
||||
new PayupTicksModel(),
|
||||
new SendHedgeAsMarketOrderModel(),
|
||||
new PostHedgePriceBasedCrossTicks(),
|
||||
new PostHedgePriceBasedCrossMarketTicks(),
|
||||
@@ -54,6 +59,8 @@ namespace mbts.spark
|
||||
|
||||
private readonly Security _synthetic;
|
||||
|
||||
public string title { get; }
|
||||
public ImageSource icon { get; }
|
||||
public string name { get => _synthetic.Synthetic.Name; set => _synthetic.Synthetic.Name = value; }
|
||||
public SyntheticContract.Types.PriceCalc price_calc { get => _synthetic.Synthetic.PriceCalc; set => _synthetic.Synthetic.PriceCalc = value; }
|
||||
public IReadOnlyCollection<LegSpreaderParamsTuple> leg_tuples { get; }
|
||||
|
||||
@@ -29,14 +29,22 @@ namespace mbts.spark
|
||||
if (ts.Count > 0) _trades.OnNext(ts);
|
||||
}
|
||||
|
||||
private static IEnumerable<Security> _get_real_securities(Security security) {
|
||||
if (security.ContractCase == Security.ContractOneofCase.Synthetic)
|
||||
foreach (var s in security.Synthetic.Legs.Select(l => l.Security).SelectMany(_get_real_securities)) yield return s;
|
||||
else yield return security;
|
||||
}
|
||||
|
||||
public IObservable<IReadOnlyList<Tuple<Security, TradeMessage>>> trades => _trades.AsObservable();
|
||||
public IReadOnlyCollection<Security> securities => _channels.Keys;
|
||||
public OrdersModel orders_model => _orders_model;
|
||||
|
||||
public void set_securities(IEnumerable<Security> securities) {
|
||||
foreach (var r in _channels.Keys.Except(securities).ToList()) _channels.Remove(r);
|
||||
foreach (var a in securities.Except(_channels.Keys).ToList())
|
||||
var real_secs = securities.SelectMany(_get_real_securities);
|
||||
foreach (var r in _channels.Keys.Except(real_secs).ToList()) _channels.Remove(r);
|
||||
foreach (var a in real_secs.Except(_channels.Keys).ToList()) {
|
||||
_channels.Add(a, Co2RelayControl.instance.consumer.get_channel(a.Symbol, a.security_type(), a.Exchange));
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() { _work_loop.Dispose(); }
|
||||
|
||||
@@ -68,7 +68,7 @@ namespace mbts.spark
|
||||
return ShellWindow.create(this, "Order Book", view, vm.get_state);
|
||||
}
|
||||
|
||||
private IShellWindow create_fills_window(FillsVM.StartupData startup_data) { return create_fills_window(startup_data.securities.Select(deserialize<Security>).ToList(), startup_data.sorting_criteria); }
|
||||
private IShellWindow create_fills_window(FillsVM.StartupData startup_data) { return create_fills_window(startup_data.securities?.Select(deserialize<Security>).ToList(), startup_data.sorting_criteria); }
|
||||
private IShellWindow create_fills_window(IReadOnlyCollection<Security> securities) { return create_fills_window(securities, null); }
|
||||
private IShellWindow create_fills_window(IReadOnlyCollection<Security> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria) {
|
||||
var vm = new FillsVM(_bus, new OrdersModel(_bus), securities, sorting_criteria);
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace mbts.ui
|
||||
}
|
||||
|
||||
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
|
||||
Logger.log(Level.Error, Subsystem.ui, "Unhandled Exception: " + e.ExceptionObject.ToString());
|
||||
Logger.log(Level.Error, Subsystem.Ui, "Unhandled Exception: " + e.ExceptionObject.ToString());
|
||||
if (e.IsTerminating) {
|
||||
Logger.system_is_crashing("Unhandled exception", e.ExceptionObject);
|
||||
}
|
||||
|
||||
@@ -211,7 +211,7 @@ namespace mbts.ui.native
|
||||
// Since we want to do that during shutdown this could cause a long delay.
|
||||
bool result = SetWorkArea_SystemParametersInfo(SPI.SETWORKAREA, 1, rect, SPIF_UPDATEINIFILE);
|
||||
if (!result) {
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Failed to set work area. {0} - {1}".fmt(Marshal.GetLastWin32Error(), new System.ComponentModel.Win32Exception().Message));
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui, "Failed to set work area. {0} - {1}".fmt(Marshal.GetLastWin32Error(), new System.ComponentModel.Win32Exception().Message));
|
||||
}
|
||||
SendNotifyMessage(HWND_BROADCAST, WM.SETTINGCHANGE, (Int64)SPI.SETWORKAREA, 0);
|
||||
}
|
||||
|
||||
@@ -64,7 +64,7 @@ namespace mbts.ui.settings
|
||||
private async Task<IShellWindow> restore(string owner_name, byte[] state, WindowPosition windowPosition) {
|
||||
IShellModule owner = _modules.SingleOrDefault(m => m.key() == owner_name);
|
||||
if (owner == null) {
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Could not locate module '{0}'".fmt(owner_name));
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "Could not locate module '{0}'".fmt(owner_name));
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -74,13 +74,13 @@ namespace mbts.ui.settings
|
||||
IShellWindow window = await task;
|
||||
if (window != null) {
|
||||
window.set_start_position(windowPosition);
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Restoring window {0} - {1}".fmt(owner_name, window.Title));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Restoring window {0} - {1}".fmt(owner_name, window.Title));
|
||||
}
|
||||
return window;
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui,
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui,
|
||||
"Failure to re-create window for module {0}. Error: {1}".fmt(owner_name, e.Message));
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -79,7 +79,7 @@ namespace mbts.ui.settings
|
||||
return state;
|
||||
}
|
||||
catch (Exception e) {
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Error saving window state for type {0}.\n {1}".fmt(window.GetType(), e.Message));
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui, "Error saving window state for type {0}.\n {1}".fmt(window.GetType(), e.Message));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -43,6 +43,7 @@ namespace mbts.ui {
|
||||
LastColumn.Background = grayish;
|
||||
|
||||
InitialAlgo = "LimitOrder";
|
||||
SecondsUntilRecenter = 30;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -56,7 +57,7 @@ namespace mbts.ui {
|
||||
|
||||
partial class OrderBookSettings {
|
||||
partial void OnConstruction() {
|
||||
CalculatorButtons = new CalculatorButtons() { Buttons = "1 1 2 3 5 9" };
|
||||
CalculatorButtons = new CalculatorButtons() { Buttons = "1 5 10 25 50 100" };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace mbts.ui
|
||||
|
||||
private void PerformMEFComposition() {
|
||||
// Initialize MEF to populate Modules and windows
|
||||
Logger.log(Level.Info, Subsystem.ui, "Beginning bts_shell module composition.");
|
||||
Logger.log(Level.Info, Subsystem.Ui, "Beginning bts_shell module composition.");
|
||||
|
||||
// Add specific instances
|
||||
Container.ComposeExportedValue<ShellModel>(this);
|
||||
@@ -92,7 +92,7 @@ namespace mbts.ui
|
||||
|
||||
private void InitInitializers() {
|
||||
foreach (IInitializable i in _initializers.OrderBy(i => i.priority)) {
|
||||
Logger.log(Level.Info, Subsystem.ui, "Initializing {0} prority {1}".fmt(i.GetType().ToString(), i.priority));
|
||||
Logger.log(Level.Info, Subsystem.Ui, "Initializing {0} prority {1}".fmt(i.GetType().ToString(), i.priority));
|
||||
i.initialize();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ namespace mbts.ui
|
||||
_undo();
|
||||
}
|
||||
catch (Exception e) {
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Failed to undo : {0} - {1}".fmt(Name, e.ToString()));
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui, "Failed to undo : {0} - {1}".fmt(Name, e.ToString()));
|
||||
throw;
|
||||
}
|
||||
finally {
|
||||
|
||||
@@ -36,12 +36,12 @@ namespace mbts.ui.shell
|
||||
|
||||
private object create_view<T>(T viewmodel) {
|
||||
string type_name = typeof(T).Name;
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Creating view for {0}".fmt(type_name));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Creating view for {0}".fmt(type_name));
|
||||
|
||||
// Check for an override
|
||||
Func<object> factory;
|
||||
if (_overrides.TryGetValue(typeof(T), out factory)) {
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Found OVERRIDE view for {0}".fmt(type_name));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Found OVERRIDE view for {0}".fmt(type_name));
|
||||
var result = factory();
|
||||
set_datacontext(viewmodel, result);
|
||||
return result;
|
||||
@@ -50,13 +50,13 @@ namespace mbts.ui.shell
|
||||
foreach (var view in Views) {
|
||||
if (view.Metadata.Model.Contains(typeof(T))) {
|
||||
var result = view.CreateExport().Value;
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Found {0} to view {1}".fmt(result.GetType(), type_name));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Found {0} to view {1}".fmt(result.GetType(), type_name));
|
||||
result.DataContext = viewmodel;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Failed to find view for {0}".fmt(type_name));
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "Failed to find view for {0}".fmt(type_name));
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -65,20 +65,20 @@ namespace mbts.ui.shell
|
||||
if (initial_workspace == ACTIVE_WORKSPACE_NAME) {
|
||||
var localws = load_local_workspace();
|
||||
if (localws != null) {
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Loading workspace from disk");
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Loading workspace from disk");
|
||||
await load_workspace(localws, position_shell: true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (to_load != null) {
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Loading initial workspace '{0}'".fmt(to_load.key));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Loading initial workspace '{0}'".fmt(to_load.key));
|
||||
// Only load the launcher position if this is a private workspace
|
||||
await load_workspace(to_load.value, to_load.key, undo:false, position_shell: !to_load.value.is_shared);
|
||||
}
|
||||
else {
|
||||
// Show launcher at default position
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Showing launcher without loading initial workspace.");
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Showing launcher without loading initial workspace.");
|
||||
_launcher.set_position(null);
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,7 @@ namespace mbts.ui.shell
|
||||
_wm.Windows.Clear();
|
||||
task.Wait(TimeSpan.FromSeconds(90));
|
||||
if (!task.IsCompleted) {
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Failed to save workspace during UI shutdown");
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui, "Failed to save workspace during UI shutdown");
|
||||
// The server is gone! Save the state to the local disk.
|
||||
save_workspace_locally(workspace);
|
||||
}
|
||||
@@ -122,7 +122,7 @@ namespace mbts.ui.shell
|
||||
}
|
||||
}
|
||||
catch {
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "The settings server is gone and I can't write to disk either. Shell is not having a good day.");
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui, "The settings server is gone and I can't write to disk either. Shell is not having a good day.");
|
||||
}
|
||||
}
|
||||
private static WorkspaceDefinition load_local_workspace() {
|
||||
|
||||
@@ -83,7 +83,7 @@ namespace mbts.ui.utility
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, String.Format("Exception message = {0}", ex.Message));
|
||||
mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui, String.Format("Exception message = {0}", ex.Message));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
<Grid x:Name="Root">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition/>
|
||||
<ColumnDefinition Width="4"/>
|
||||
<ColumnDefinition Width="0"/>
|
||||
<ColumnDefinition/>
|
||||
</Grid.ColumnDefinitions>
|
||||
<ComboBox x:Name="PART_AlgoTypeComboBox" ItemsSource="{TemplateBinding ItemsView}" SelectedItem="{Binding SelectedItem, RelativeSource={RelativeSource TemplatedParent}}" HorizontalAlignment="Stretch">
|
||||
@@ -53,7 +53,9 @@
|
||||
</DataTemplate>
|
||||
</ComboBox.ItemTemplate>
|
||||
</ComboBox>
|
||||
<c:PopupControl x:Name="PART_AlgoDetailsPopup" Grid.Column="2" Content="{Binding SelectedItem.order_details, RelativeSource={RelativeSource TemplatedParent}}">
|
||||
<c:PopupControl x:Name="PART_AlgoDetailsPopup" Grid.Column="2"
|
||||
Content="{Binding SelectedItem.order_details, RelativeSource={RelativeSource TemplatedParent}}"
|
||||
Visibility="{TemplateBinding HasEditableProperties, Converter={StaticResource BoolToVisibility}}">
|
||||
<c:PopupControl.ContentTemplateSelector>
|
||||
<usp:OrderModificationTemplateSelector>
|
||||
<usp:OrderModificationTemplateSelector.StopLimitOrderTemplate>
|
||||
@@ -135,11 +137,13 @@
|
||||
<ControlTemplate.Triggers>
|
||||
<Trigger Property="ExpandDirection" Value="Left">
|
||||
<Setter Property="PopupPlacement" TargetName="PART_AlgoDetailsPopup" Value="Left"/>
|
||||
<Setter Property="Margin" TargetName="PART_AlgoDetailsPopup" Value="0,0,2,0" />
|
||||
<Setter Property="Grid.Column" TargetName="PART_AlgoDetailsPopup" Value="0"/>
|
||||
<Setter Property="Grid.Column" TargetName="PART_AlgoTypeComboBox" Value="2"/>
|
||||
</Trigger>
|
||||
<Trigger Property="ExpandDirection" Value="Right">
|
||||
<Setter Property="PopupPlacement" TargetName="PART_AlgoDetailsPopup" Value="Right"/>
|
||||
<Setter Property="Margin" TargetName="PART_AlgoDetailsPopup" Value="2,0,0,0" />
|
||||
<Setter Property="Grid.Column" TargetName="PART_AlgoDetailsPopup" Value="2"/>
|
||||
<Setter Property="Grid.Column" TargetName="PART_AlgoTypeComboBox" Value="0"/>
|
||||
</Trigger>
|
||||
|
||||
@@ -72,8 +72,28 @@ namespace mbts.ui.spark.algo
|
||||
internal ICollectionView ItemsView { get => GetValue(ItemsViewProperty) as ICollectionView; private set => SetValue(ItemsViewPropertyKey, value); }
|
||||
#endregion
|
||||
|
||||
|
||||
#region HasEditableProperties
|
||||
|
||||
public bool HasEditableProperties {
|
||||
get { return (bool)GetValue(HasEditablePropertiesProperty.DependencyProperty); }
|
||||
set { SetValue(HasEditablePropertiesProperty, value); }
|
||||
}
|
||||
|
||||
public static readonly DependencyPropertyKey HasEditablePropertiesProperty =
|
||||
DependencyProperty.RegisterReadOnly("HasEditableProperties", typeof(bool), typeof(AlgoDetailsPopupControl), new PropertyMetadata(true));
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(nameof(SelectedItem), typeof(IAlgoTypeVM), typeof(AlgoDetailsPopupControl),
|
||||
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
|
||||
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, SelectedItemChanged));
|
||||
|
||||
private static void SelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs baseValue) {
|
||||
var item = ((AlgoDetailsPopupControl)d).SelectedItem;
|
||||
d.SetValue(HasEditablePropertiesProperty, !item.meta.NoProps);
|
||||
}
|
||||
|
||||
public IAlgoTypeVM SelectedItem { get => GetValue(SelectedItemProperty) as IAlgoTypeVM; set => SetValue(SelectedItemProperty, value); }
|
||||
|
||||
private void TrySetGridColumnWidths() {
|
||||
|
||||
@@ -14,16 +14,19 @@ namespace mbts.ui.controls {
|
||||
readonly static double _dpi = get<bts.config.System>().dpi_ratio;
|
||||
|
||||
Typeface _face;
|
||||
FormattedText _ft;
|
||||
FormattedText _center_text;
|
||||
FormattedText _top_text;
|
||||
FormattedText _bottom_text;
|
||||
static Badge() {
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(typeof(Badge)));
|
||||
WidthProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(15.0));
|
||||
HeightProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(10.0));
|
||||
FontSizeProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(8.0, FrameworkPropertyMetadataOptions.AffectsRender, changed));
|
||||
ForegroundProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.White, changed));
|
||||
FontSizeProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(4.0, FrameworkPropertyMetadataOptions.AffectsRender, update_text));
|
||||
ForegroundProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.White, update_text));
|
||||
BackgroundProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender));
|
||||
BorderThicknessProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(new Thickness(1)));
|
||||
BorderBrushProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(Brushes.Black));
|
||||
FontFamilyProperty.OverrideMetadata(typeof(Badge), new FrameworkPropertyMetadata(new FontFamily("Consolas")));
|
||||
}
|
||||
|
||||
public Badge() {
|
||||
@@ -35,9 +38,27 @@ namespace mbts.ui.controls {
|
||||
set { SetValue(TextProperty, value); }
|
||||
}
|
||||
public static readonly DependencyProperty TextProperty =
|
||||
DependencyProperty.Register("Text", typeof(string), typeof(Badge), new PropertyMetadata(string.Empty, changed));
|
||||
DependencyProperty.Register("Text", typeof(string), typeof(Badge), new PropertyMetadata(string.Empty,
|
||||
format_text((b,v) => b._center_text= v)));
|
||||
|
||||
|
||||
public string TopText {
|
||||
get { return (string)GetValue(TopTextProperty); }
|
||||
set { SetValue(TopTextProperty, value); }
|
||||
}
|
||||
public static readonly DependencyProperty TopTextProperty =
|
||||
DependencyProperty.Register(nameof(TopText), typeof(string), typeof(Badge), new PropertyMetadata(string.Empty,
|
||||
format_text((b, v) => b._top_text = v)));
|
||||
|
||||
public string BottomText {
|
||||
get { return (string)GetValue(BottomTextProperty); }
|
||||
set { SetValue(BottomTextProperty, value); }
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty BottomTextProperty =
|
||||
DependencyProperty.Register(nameof(BottomText), typeof(string), typeof(Badge), new PropertyMetadata(string.Empty,
|
||||
format_text((b,v)=>b._bottom_text=v)));
|
||||
|
||||
public double CornerRadius {
|
||||
get { return (double)GetValue(CornerRadiusProperty); }
|
||||
set { SetValue(CornerRadiusProperty, value); }
|
||||
@@ -45,37 +66,53 @@ namespace mbts.ui.controls {
|
||||
public static readonly DependencyProperty CornerRadiusProperty =
|
||||
DependencyProperty.Register("CornerRadius", typeof(double), typeof(Badge), new PropertyMetadata(3.0));
|
||||
|
||||
private static void changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
|
||||
Badge b = (Badge)d;
|
||||
b._face = b._face ?? new Typeface(b.FontFamily, b.FontStyle, b.FontWeight, b.FontStretch);
|
||||
if (!string.IsNullOrWhiteSpace(b.Text)) {
|
||||
b._ft = new FormattedText(b.Text,
|
||||
static PropertyChangedCallback format_text(Action<Badge,FormattedText> f) {
|
||||
return (d, e) => {
|
||||
Badge b = (Badge)d;
|
||||
ensure_fontface(b);
|
||||
string text = e.NewValue as string;
|
||||
if (string.IsNullOrEmpty(text)) f(b, null);
|
||||
f(b, new FormattedText(text,
|
||||
System.Globalization.CultureInfo.CurrentCulture,
|
||||
FlowDirection.LeftToRight,
|
||||
b._face,
|
||||
b.FontSize, b.Foreground, _dpi);
|
||||
}
|
||||
else { b._ft = null; }
|
||||
|
||||
b.InvalidateVisual();
|
||||
b._face, 4.2, b.Foreground, _dpi));
|
||||
b.InvalidateVisual();
|
||||
};
|
||||
}
|
||||
static FormattedText format_text(Badge badge, DependencyProperty source) {
|
||||
FormattedText result = null;
|
||||
var value = badge.GetValue(source);
|
||||
format_text((b, v) => result = v)(badge, new DependencyPropertyChangedEventArgs(source, value, value));
|
||||
return result;
|
||||
}
|
||||
|
||||
protected override Size MeasureOverride(Size constraint) {
|
||||
Size desired = new Size(Width, Height);
|
||||
if (_ft != null) {
|
||||
desired = new Size(0.6*desired.Width + _ft.Width, Math.Max(desired.Height, _ft.Height + 2));
|
||||
}
|
||||
desired.Width = Math.Min(desired.Width, constraint.Width);
|
||||
desired.Height = Math.Min(desired.Height, constraint.Height);
|
||||
return desired;
|
||||
static void update_text(DependencyObject d, DependencyPropertyChangedEventArgs args) {
|
||||
// Force formatted text regeneration when font/color changes
|
||||
Badge badge = (Badge)d;
|
||||
badge._face = null;
|
||||
ensure_fontface(badge);
|
||||
badge._center_text = format_text(badge, TextProperty);
|
||||
badge._top_text = format_text(badge, TopTextProperty);
|
||||
badge._bottom_text = format_text(badge, BottomTextProperty);
|
||||
}
|
||||
|
||||
private static void ensure_fontface(Badge b) {
|
||||
b._face = b._face ?? new Typeface(b.FontFamily, b.FontStyle, b.FontWeight, b.FontStretch);
|
||||
}
|
||||
|
||||
protected override void OnRender(DrawingContext dc) {
|
||||
base.OnRender(dc);
|
||||
var pen = new Pen(BorderBrush, BorderThickness.Top);
|
||||
double border_thickness = BorderThickness.Top;
|
||||
var pen = new Pen(BorderBrush, border_thickness);
|
||||
dc.DrawRoundedRectangle(Background, pen, new Rect(0, 0, ActualWidth, ActualHeight), CornerRadius, CornerRadius);
|
||||
if (_ft != null && _ft.Width < ActualWidth) {
|
||||
dc.DrawText(_ft, new Point((ActualWidth-_ft.Width)/2, (ActualHeight-_ft.Height)/2));
|
||||
if (_center_text != null && _center_text.Width < ActualWidth) {
|
||||
dc.DrawText(_center_text, new Point((ActualWidth-_center_text.Width)/2, (ActualHeight-_center_text.Height)/2));
|
||||
}
|
||||
if (_top_text != null) {
|
||||
dc.DrawText(_top_text, new Point(border_thickness, 0.0));
|
||||
}
|
||||
if (_bottom_text != null) {
|
||||
dc.DrawText(_bottom_text, new Point(border_thickness, ActualHeight - _bottom_text.Height));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,7 +124,7 @@ namespace mbts.ui.controls {
|
||||
var loc = e.GetPosition(this);
|
||||
var delta = loc - _drag_start;
|
||||
if (delta.Length > _min_drag_delta.Length) {
|
||||
Logger.info(bts.log.Subsystem.ui, "Begin Drag");
|
||||
Logger.info(bts.log.Subsystem.Ui, "Begin Drag");
|
||||
DragDrop.DoDragDrop(this, DataContext, DragDropEffects.Move|DragDropEffects.All);
|
||||
}
|
||||
}
|
||||
@@ -96,12 +133,12 @@ namespace mbts.ui.controls {
|
||||
protected override void OnMouseDown(MouseButtonEventArgs e) {
|
||||
base.OnMouseDown(e);
|
||||
CaptureMouse();
|
||||
Logger.info(bts.log.Subsystem.ui, "Mouse Down");
|
||||
Logger.info(bts.log.Subsystem.Ui, "Mouse Down");
|
||||
}
|
||||
protected override void OnMouseUp(MouseButtonEventArgs e) {
|
||||
base.OnMouseUp(e);
|
||||
ReleaseMouseCapture();
|
||||
Logger.info(bts.log.Subsystem.ui, "Mouse Up");
|
||||
Logger.info(bts.log.Subsystem.Ui, "Mouse Up");
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ namespace mbts.ui.controls
|
||||
|
||||
}
|
||||
catch (Exception e) {
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Failed to register bts:// url extension. " + e.Message);
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "Failed to register bts:// url extension. " + e.Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ using mbts.ui.spark.converters;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Input;
|
||||
using System;
|
||||
|
||||
namespace mbts.ui.spark
|
||||
{
|
||||
@@ -17,17 +18,18 @@ namespace mbts.ui.spark
|
||||
}
|
||||
|
||||
#region Value
|
||||
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(PriceEntryControl), new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
|
||||
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(PriceEntryControl),new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceValue));
|
||||
private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((ContractSpecification)d.GetValue(ContractSpecProperty)).round((double)baseValue); }
|
||||
public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
|
||||
#endregion
|
||||
|
||||
#region TickUp
|
||||
#region TickUp (ReadOnly)
|
||||
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
|
||||
#region TickDown (ReadOnly)
|
||||
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); }
|
||||
|
||||
@@ -124,6 +124,7 @@ namespace mbts.ui.spark
|
||||
public event Action IsAllSelectedChanged;
|
||||
public bool IsExpanded { get => _is_expanded; set { if (_is_expanded != value) { _is_expanded = value; OnPropertyChanged(new PropertyChangedEventArgs(nameof(IsExpanded))); } } }
|
||||
public override bool IsBottomLevel { get; }
|
||||
public override int GetHashCode() { return Name.GetHashCode(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ namespace mbts.ui.spark
|
||||
public ContractOneofCase type => security.ContractCase;
|
||||
public string symbol => security.ForceSymbol();
|
||||
public string display_name => security.ToString(null);
|
||||
public string display_exchange => security.DisplayExchange();
|
||||
public bool is_selected {
|
||||
get => _is_selected;
|
||||
set {
|
||||
@@ -30,6 +31,7 @@ namespace mbts.ui.spark
|
||||
}
|
||||
}
|
||||
public event Action<Security, bool> IsSelectedChanged;
|
||||
public override int GetHashCode() { return security.Id.GetHashCode(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -91,7 +91,7 @@ namespace mbts.ui.spark
|
||||
if (new_val != null) {
|
||||
new_val.ViewDestroyed += target._internal_security_items_ViewDestroyed;
|
||||
var vs = new CollectionViewSource<SecurityCollectionView>(new_val);
|
||||
vs.GroupDescriptions.AddRange(new[] { "exchange", "symbol", "type" }.Select(p => new PropertyGroupDescription(p)));
|
||||
vs.GroupDescriptions.AddRange(new[] { "display_exchange", "symbol", "type" }.Select(p => new PropertyGroupDescription(p)));
|
||||
target.SecurityItemsViewSource = vs;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ namespace mbts.ui.converters
|
||||
try {
|
||||
return _get_property(((IDataGridCellCollection)target).get_cell(key), remaining_path.Skip(1));
|
||||
} catch (Exception ex) {
|
||||
Logger.error(bts.log.Subsystem.ui, "CellPathConverter bad property lookup({0}): {1}.".fmt(key == null ? "null" : key, ex));
|
||||
Logger.error(bts.log.Subsystem.Ui, "CellPathConverter bad property lookup({0}): {1}.".fmt(key == null ? "null" : key, ex));
|
||||
Logger.assert(false, "CellPathConverter bad property assert: {0}".fmt(ex));
|
||||
return null;
|
||||
}
|
||||
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
using bts.spark;
|
||||
using System;
|
||||
using System.Windows.Data;
|
||||
using System.Globalization;
|
||||
|
||||
namespace mbts.ui.converters
|
||||
{
|
||||
[ValueConversion(typeof(QuantityMeasure.QuantityOneofCase), typeof(string))]
|
||||
internal class QuantityMeasureCaseDisplayTextConverter : IValueConverter
|
||||
{
|
||||
public const string RATIO_TEXT = "Ratio";
|
||||
public const string ABSOLUTE_TEXT = "Size";
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
switch ((QuantityMeasure.QuantityOneofCase)value) {
|
||||
case QuantityMeasure.QuantityOneofCase.Absolute: return ABSOLUTE_TEXT;
|
||||
case QuantityMeasure.QuantityOneofCase.Ratio: return RATIO_TEXT;
|
||||
default: return value.ToString();
|
||||
}
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
using bts.api;
|
||||
using System;
|
||||
using System.Windows.Data;
|
||||
using System.Globalization;
|
||||
using mbts.ui.utilities;
|
||||
|
||||
namespace mbts.ui.converters
|
||||
{
|
||||
[ValueConversion(typeof(SyntheticContract.Types.PriceCalc), typeof(string))]
|
||||
internal class SyntheticPriceCalcDisplayTextConverter : IValueConverter
|
||||
{
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
switch ((SyntheticContract.Types.PriceCalc)value) {
|
||||
case SyntheticContract.Types.PriceCalc.Diff: return "Standard";
|
||||
default: return DisplayNameHelper.camel_to_title_case(value.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,7 +81,7 @@ namespace mbts.ui.shell
|
||||
return bitmap;
|
||||
}
|
||||
else {
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Unexpected document type in TabDocument: {0}".fmt(document.Content.GetType()));
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "Unexpected document type in TabDocument: {0}".fmt(document.Content.GetType()));
|
||||
return Icons.Logo;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +104,7 @@ namespace mbts.ui
|
||||
try {
|
||||
var effect = DragDrop.DoDragDrop(_source, data, DragDropEffects.Move);
|
||||
}
|
||||
catch (Exception error) { Logger.log(Level.Warn, Subsystem.ui, "Dragdrop failed: " + error.ToString()); }
|
||||
catch (Exception error) { Logger.log(Level.Warn, Subsystem.Ui, "Dragdrop failed: " + error.ToString()); }
|
||||
show_document(_source, _source_window, true);
|
||||
_source = null;
|
||||
_source_window = null;
|
||||
|
||||
@@ -54,13 +54,13 @@ namespace mbts.ui
|
||||
if(w != null)
|
||||
try { w.Close(); w = null; }
|
||||
catch (Exception ex) {
|
||||
Logger.warn(Subsystem.ui, "{0} error while attempting to Close window of Type {1} on Dispose: {2}".fmt(GetType(), typeof(TWindow), ex.Message));
|
||||
Logger.warn(Subsystem.Ui, "{0} error while attempting to Close window of Type {1} on Dispose: {2}".fmt(GetType(), typeof(TWindow), ex.Message));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception ex){
|
||||
Logger.warn(Subsystem.ui, "{0} error while attempting to launch window of type {1}: {2}".fmt(GetType(), typeof(TWindow), ex.Message));
|
||||
Logger.warn(Subsystem.Ui, "{0} error while attempting to launch window of type {1}: {2}".fmt(GetType(), typeof(TWindow), ex.Message));
|
||||
}
|
||||
finally {
|
||||
_is_executing = false;
|
||||
|
||||
@@ -55,4 +55,5 @@
|
||||
<cv:NumericSignBrushConverter x:Key="DayChangeSignBrushConverter" Zero="{StaticResource DoubleZero}"/>
|
||||
<sys:Int32 x:Key="IntZero">0</sys:Int32>
|
||||
<sys:Double x:Key="DoubleZero">0</sys:Double>
|
||||
<cv:QuantityMeasureCaseDisplayTextConverter x:Key="QuantityMeasureCaseDisplayConverter"/>
|
||||
</ResourceDictionary>
|
||||
@@ -18,7 +18,7 @@ namespace mbts.ui
|
||||
window.Close();
|
||||
}
|
||||
catch (Exception err) {
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "Exception closing window : {0}".fmt(err.ToString()));
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "Exception closing window : {0}".fmt(err.ToString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ namespace mbts.ui.shell
|
||||
}
|
||||
this.Activate();
|
||||
handled = true;
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Login window brought to the foreground by attempt to re-launch the bts_shell.");
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Login window brought to the foreground by attempt to re-launch the bts_shell.");
|
||||
}
|
||||
return IntPtr.Zero;
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ namespace mbts.ui.shell
|
||||
Logger.assert(false, e.ToString());
|
||||
}
|
||||
finally {
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui,
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui,
|
||||
"Disposing slow {0} and cleaning up background thread.".fmt(name));
|
||||
UIThreadData unused;
|
||||
_shared_threads.TryRemove(name, out unused);
|
||||
|
||||
@@ -92,7 +92,7 @@ namespace mbts.ui.shell
|
||||
}
|
||||
catch (Exception e) {
|
||||
error_text = e.Message;
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, "Error getting window contents. " + e.ToString());
|
||||
Logger.log(bts.log.Level.Error, bts.log.Subsystem.Ui, "Error getting window contents. " + e.ToString());
|
||||
}
|
||||
}, DispatcherPriority.Send);
|
||||
|
||||
@@ -177,7 +177,7 @@ namespace mbts.ui.shell
|
||||
}
|
||||
else if (IsSlow) {
|
||||
// Terminating the background thread will dispose the model on that thread
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Beginning asyncronous dispose of slow window {0} .".fmt(_model.GetType().ToString()));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Beginning asyncronous dispose of slow window {0} .".fmt(_model.GetType().ToString()));
|
||||
_dispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -137,7 +137,7 @@ namespace mbts.ui.shell
|
||||
pos.host_id = window.host_id;
|
||||
return pos;
|
||||
}
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.ui, "IShellWindow '{0}' does not have a valid position. It may not be displayed".fmt(shell_window.Title));
|
||||
Logger.log(bts.log.Level.Warn, bts.log.Subsystem.Ui, "IShellWindow '{0}' does not have a valid position. It may not be displayed".fmt(shell_window.Title));
|
||||
return new WindowPosition();
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ namespace mbts.ui.tests
|
||||
finally {
|
||||
gonow.Set();
|
||||
}
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Init Application");
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Init Application");
|
||||
Dispatcher.Run();
|
||||
});
|
||||
t.Name = "Application Thread";
|
||||
@@ -53,7 +53,7 @@ namespace mbts.ui.tests
|
||||
|
||||
[TearDown]
|
||||
public static void teardown() {
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, ("Tear down Application"));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, ("Tear down Application"));
|
||||
if (Application.Current != null && Application.Current.Dispatcher != null) {
|
||||
Application.Current.Dispatcher.InvokeShutdown();
|
||||
}
|
||||
@@ -69,7 +69,7 @@ namespace mbts.ui.tests
|
||||
Assert.IsNotNull(Application.Current);
|
||||
// Run the logic of this test on the "Main" thread
|
||||
Application.Current.Dispatcher.Invoke(() => {
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Begin: test_windows_disposed");
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Begin: test_windows_disposed");
|
||||
// Make sure that an IShellWindow and ISlowWindow added to the Windows collection is eventually disposed
|
||||
ObservableCollection<IShellWindow> windows = new ObservableCollection<IShellWindow>();
|
||||
var thread_factory = new ShellThreadFactory();
|
||||
@@ -95,7 +95,7 @@ namespace mbts.ui.tests
|
||||
public void test_slow_windows_disposed() {
|
||||
Assert.IsNotNull(Application.Current);
|
||||
Application.Current.Dispatcher.Invoke(() => {
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Begin: test_slow_windows_disposed");
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Begin: test_slow_windows_disposed");
|
||||
// Make sure that an IShellWindow and ISlowWindow added to the Windows collection is eventually disposed
|
||||
ObservableCollection<IShellWindow> windows = new ObservableCollection<IShellWindow>();
|
||||
var thread_factory = new ShellThreadFactory();
|
||||
|
||||
@@ -8,17 +8,36 @@ namespace mbts.ui.utility
|
||||
{
|
||||
public class RXObservableCollection<T> : ObservableCollection<T>, IObserver<IEnumerable<T>>, IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of RXObservableCollection<T>, that will observe the source with a 1 second throttle on the current synchronization context
|
||||
/// </summary>
|
||||
public RXObservableCollection(IObservable<IEnumerable<T>> data) : this(data, SynchronizationContext.Current) { }
|
||||
public RXObservableCollection(IObservable<IEnumerable<T>> data, SynchronizationContext context) {
|
||||
_sub = (context != null ? data.ObserveOn(context) : data).Subscribe(this);
|
||||
/// <summary>
|
||||
/// Initializes a new instance of RXObservableCollection, that will observe the source with a 1 second throttle on the specified synchronization context
|
||||
/// </summary>
|
||||
public RXObservableCollection(IObservable<IEnumerable<T>> data, SynchronizationContext context) : this(data, context, TimeSpan.FromSeconds(1)) { }
|
||||
/// <summary>
|
||||
/// Initializes a new instance of RXObservableCollection, that will observe the source with a 1 second throttle on the specified synchronization context
|
||||
/// </summary>
|
||||
public RXObservableCollection(IObservable<IEnumerable<T>> data, SynchronizationContext context, TimeSpan throttle) : this(data, context, throttle, EqualityComparer<T>.Default) { }
|
||||
/// <summary>
|
||||
/// <para>Initializes a new instance of RXObservableCollection, that will observe the source with the specified throttle on the specified synchronization context, and synchronize with the specified IEqualityComparer<T></para>
|
||||
/// <para>If a throttle of TimeSpan.Zero is passed, no throttle will used.</para>
|
||||
/// </summary>
|
||||
public RXObservableCollection(IObservable<IEnumerable<T>> data, SynchronizationContext context, TimeSpan throttle, IEqualityComparer<T> equality_comparer) {
|
||||
_equality_comparer = equality_comparer ?? EqualityComparer<T>.Default;
|
||||
if (throttle != TimeSpan.Zero) data = data.Buffer(throttle).Where(d => d.Count > 0).Select(d => d[d.Count - 1]);
|
||||
if (context != null) data = data.ObserveOn(context);
|
||||
_sub = data.Subscribe(this);
|
||||
}
|
||||
|
||||
private readonly IEqualityComparer<T> _equality_comparer;
|
||||
private IDisposable _sub;
|
||||
|
||||
public virtual void OnCompleted() { }
|
||||
public virtual void OnError(Exception error) { }
|
||||
public virtual void OnNext(IEnumerable<T> value) {
|
||||
this.sync_with(value);
|
||||
this.sync_with(value, _equality_comparer);
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
|
||||
@@ -25,7 +25,7 @@ namespace mbts.ui.utility
|
||||
}
|
||||
|
||||
public Stream capture_encoded(string format, int width, int height) {
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui, "Capturing screenshot ({0})".fmt(format));
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.Ui, "Capturing screenshot ({0})".fmt(format));
|
||||
|
||||
BitmapEncoder encoder = get_encoder(format);
|
||||
BitmapSource bmp;
|
||||
|
||||
@@ -8,8 +8,8 @@ using System.Threading.Tasks;
|
||||
using System.Reactive.Linq;
|
||||
using System.IO;
|
||||
using System.Reactive.Disposables;
|
||||
using mbts;
|
||||
|
||||
using mbts;
|
||||
|
||||
namespace bts.api.core {
|
||||
|
||||
internal class QuickbusClientChannel : ClientChannel {
|
||||
@@ -40,7 +40,6 @@ namespace bts.api.core {
|
||||
};
|
||||
var buffer = header.serialize(request);
|
||||
var tcs = new TaskCompletionSource<Result<Response>>();
|
||||
// todo: lifetime of callback is wrong
|
||||
ApiNativeMethods.raw_pb_callback callback = (rbuffer, rlength, _) => {
|
||||
var res = ApiUtils.deserialize<ResponseHeader, Response>(rbuffer, (long)rlength);
|
||||
if (res.header.Code == ApiError.Success) {
|
||||
@@ -78,8 +77,8 @@ namespace bts.api.core {
|
||||
observer.OnNext(new RawUpdate<T>(added_items, added_keys, removed_keys));
|
||||
}
|
||||
else if (event_type == ApiNativeMethods.EventType.TABLE_CREATED) {
|
||||
if (!first_update) {
|
||||
observer.OnNext(RawUpdate<T>.Reset());
|
||||
if (!first_update) {
|
||||
observer.OnNext(RawUpdate<T>.Reset());
|
||||
}
|
||||
first_update = false;
|
||||
}
|
||||
@@ -97,7 +96,7 @@ namespace bts.api.core {
|
||||
});
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
private class FinalizeableAnonymousDisposable : IDisposable {
|
||||
private Action<bool> _action;
|
||||
public FinalizeableAnonymousDisposable(Action<bool> dispose) {
|
||||
@@ -111,15 +110,15 @@ namespace bts.api.core {
|
||||
GC.SuppressFinalize(this);
|
||||
Dispose(true);
|
||||
}
|
||||
|
||||
|
||||
protected virtual void Dispose(bool disposing) {
|
||||
_action?.Invoke(disposing);
|
||||
_action = null;
|
||||
}
|
||||
}
|
||||
|
||||
public override bool is_sync_call_ok() {
|
||||
return !ApiNativeMethods.api_client_is_on_qb_thread(_client);
|
||||
}
|
||||
public override bool is_sync_call_ok() {
|
||||
return !ApiNativeMethods.api_client_is_on_qb_thread(_client);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -19,10 +19,21 @@ namespace bts.log {
|
||||
|
||||
internal enum Subsystem {
|
||||
gen,
|
||||
Config,
|
||||
QBus,
|
||||
Log,
|
||||
Jetfix,
|
||||
MarketData,
|
||||
Api,
|
||||
Persistence,
|
||||
User,
|
||||
OrderMan,
|
||||
Latency,
|
||||
Assert,
|
||||
Engine,
|
||||
ui,
|
||||
Persist
|
||||
Engine,
|
||||
Ui,
|
||||
Persist,
|
||||
// Please keep this list in sync with logging.h/logging.cpp
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -140,7 +140,7 @@ namespace bts.api
|
||||
public string separator { get; }
|
||||
public bool add_part(FutureLeg fl, out string result) {
|
||||
if (_first_leg) {
|
||||
if (fl.Item4 > 0) result = fl.Item4 == 1 ? string.Empty : fl.Item3.ToString();
|
||||
if (fl.Item4 > 0) result = fl.Item4 == 1 ? string.Empty : fl.Item4.ToString();
|
||||
else result = fl.Item4 == -1 ? "-" : fl.Item4.ToString("-0");
|
||||
_first_leg = false;
|
||||
} else {
|
||||
|
||||
@@ -1,29 +1,15 @@
|
||||
//using bts.config;
|
||||
using Google.Protobuf.Collections;
|
||||
using mbts;
|
||||
using mbts.config;
|
||||
using Google.Protobuf.Collections;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using static bts.api.Security;
|
||||
using FutureLeg = System.Tuple<bts.api.Venue, string, bts.api.FutureContract, int>;
|
||||
using bts.log;
|
||||
|
||||
namespace bts.api
|
||||
{
|
||||
internal static class SecurityHelper
|
||||
{
|
||||
//static SecurityHelper() {
|
||||
// try {
|
||||
// ExpirationDisplayOffset offset_list = Configuration.get<ExpirationDisplayOffset>();
|
||||
// _offset_map = offset_list.entries.ToDictionary(e => e.security_name, e => e);
|
||||
// }
|
||||
// catch (Exception ex) { Logger.error(Subsystem.ui, $"Failed to get Configuration for type {typeof(ExpirationDisplayOffset)}: {ex}"); }
|
||||
//}
|
||||
|
||||
#region Private Members
|
||||
//private static readonly IDictionary<string, ExpirationDisplayOffsetEntry> _offset_map;
|
||||
|
||||
private static IEnumerable<FutureLeg> _get_flat_future_legs(RepeatedField<ContractLeg> legs, int qty) {
|
||||
foreach (var l in legs) {
|
||||
switch (l.Security.ContractCase) {
|
||||
@@ -33,6 +19,11 @@ namespace bts.api
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private class InternalIDEqualityComparer : IEqualityComparer<Security> {
|
||||
public bool Equals(Security x, Security y) { return x == null ? y == null : y != null && x.Id == y.Id; }
|
||||
public int GetHashCode(Security security) { return security.Id.GetHashCode(); }
|
||||
}
|
||||
#endregion
|
||||
|
||||
public static IEnumerable<FutureLeg> get_flat_future_legs(Security sec) {
|
||||
@@ -43,21 +34,14 @@ namespace bts.api
|
||||
}
|
||||
}
|
||||
|
||||
public static readonly IEqualityComparer<Security> IDEqualityComparer = new InternalIDEqualityComparer();
|
||||
|
||||
#region Extensions
|
||||
public static DateTime RawExpDate(this FutureContract future) { return new DateTime((int)future.ExpirationYear, (int)future.ExpirationMonth, (int)future.ExpirationDay); }
|
||||
|
||||
// probably do not need MappedExpDates in spark, leaving the method-infrastructure alone just in case
|
||||
// TODO: Remove (probably do not need MappedExpDates in spark)
|
||||
public static DateTime MappedExpDate(this FutureContract future) {
|
||||
return RawExpDate(future);
|
||||
//ExpirationDisplayOffsetEntry offset_entry;
|
||||
//if (_offset_map.TryGetValue(future.Symbol, out offset_entry)) {
|
||||
// if (offset_entry.addition_type == ExpirationOffsetType.type.Month) return future.RawExpDate().AddMonths(offset_entry.addition_count);
|
||||
// else if (offset_entry.addition_type == ExpirationOffsetType.type.MonthMoveToStart) {
|
||||
// DateTime rv = future.RawExpDate().AddMonths(offset_entry.addition_count);
|
||||
// return new DateTime(rv.Year, rv.Month, 1);
|
||||
// }
|
||||
//}
|
||||
//return future.RawExpDate();
|
||||
}
|
||||
|
||||
public static int SignedQuantity(this ContractLeg leg) { return leg.Side == Side.Buy ? (int)leg.Quantity : -(int)leg.Quantity; }
|
||||
@@ -66,6 +50,10 @@ namespace bts.api
|
||||
if (security.ContractCase == ContractOneofCase.Synthetic) return ForceSymbol(security.Synthetic.Legs.First().Security);
|
||||
else return security.Symbol;
|
||||
}
|
||||
|
||||
public static string DisplayExchange(this Security security) {
|
||||
return security.ContractCase == ContractOneofCase.Synthetic ? $"[{string.Join(",", get_flat_future_legs(security).Select(flt => flt.Item1.ToString()).Distinct().OrderBy(e => e))}]" : security.Exchange.ToString();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,9 @@ namespace mbts.utils
|
||||
[DllImport("spark_lib")]
|
||||
public static extern void finit_spark_lib();
|
||||
|
||||
[DllImport("spark_lib")]
|
||||
public static extern UInt64 ll_now();
|
||||
|
||||
[DllImport("kernel32.dll")]
|
||||
public static extern bool SetConsoleTitle(string lpConsoleTitle);
|
||||
}
|
||||
|
||||
@@ -10,15 +10,21 @@ namespace mbts.utils
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct LLDateTime
|
||||
{
|
||||
public LLDateTime(Int64 value) {
|
||||
public LLDateTime(UInt64 value) {
|
||||
_value = value;
|
||||
}
|
||||
DateTime to_datetime() {
|
||||
return _value.lldatetime();
|
||||
}
|
||||
|
||||
public static implicit operator DateTime (LLDateTime time) { return time.to_datetime(); }
|
||||
|
||||
private Int64 _value;
|
||||
public static LLDateTime now() {
|
||||
return new LLDateTime(BTSNativeMethods.ll_now());
|
||||
}
|
||||
public UInt64 value => _value;
|
||||
|
||||
private UInt64 _value;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
|
||||
@@ -1 +1 @@
|
||||
set(sources api/apicore.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/services/ApiUnitTestService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Account.conf;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Symbols.conf;config/defaults/User.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/Account.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/User.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Structure/FixedSecurity.cpp;md/Structure/PriceSize.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/windows_test_driver.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp)
|
||||
set(sources api/apicore.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/services/ApiUnitTestService.proto;api/services/HelloService.proto;api/services/MarketDataRelay.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/UserService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/Account.conf;config/defaults/Executor.conf;config/defaults/MarketData.conf;config/defaults/Symbols.conf;config/defaults/User.conf;config/defaults/edge.conf;config/defaults/expiration_display_offset.conf;config/defaults/jetfix.conf;config/defaults/logging.conf;config/defaults/testkeys.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/Account.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/User.proto;config/protos/environment.proto;config/protos/expiration_display_offset.proto;config/protos/jetfix.proto;config/protos/logging.proto;config/protos/quickbus_cfg.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPriceLantencyTester.cpp;md/Diag/ShmDumper.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MDRecoverableConsumer.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/SecurityIDRecorder.cpp;md/SettlementRecorder.cpp;md/Structure/FixedSecurity.cpp;md/Structure/PriceSize.cpp;md/common.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/test/Co2TestInstrument.cpp;md/test/md2_tests.cpp;os/os.cpp;os/tests/os_tests.cpp;quickbus/core/LocalNode.cpp;quickbus/core/Quickbus.cpp;quickbus/core/SubscriptionID.cpp;quickbus/core/TableID.cpp;quickbus/message_model/Update.cpp;quickbus/message_model/merge_updates.cpp;quickbus/network/QBConnection.cpp;quickbus/network/QBConnectionManager.cpp;quickbus/network/endpoint_description.cpp;quickbus/network/quickbus_msgs.proto;quickbus/pubsub/TablePublisher.cpp;quickbus/pubsub/TableSubscriber.cpp;quickbus/pubsub/tests/qb_pubsub_tests.cpp;quickbus/routing/INode.cpp;quickbus/routing/NodeID.cpp;quickbus/routing/Router.cpp;quickbus/rpc/RPCClient.cpp;quickbus/rpc/RPCServer.cpp;quickbus/rpc/RPCSessionID.cpp;quickbus/rpc/rpc_utils.cpp;quickbus/rpc/tests/qb_rpc_tests.cpp;quickbus/tests/quickbus_tests.cpp;sparkproto/SparkProtos.proto;testing/windows_test_driver.cpp;utils/Dispatcher.cpp;utils/HTTPStream.cpp;utils/PBUtils.cpp;utils/Puid.cpp;utils/SharedMemory.cpp;utils/Sqlite_utils.cpp;utils/Uuid.cpp;utils/datetime.cpp;utils/download.cpp;utils/file_utils.cpp;utils/init_spark_lib.cpp;utils/is_unittest_environment.cpp)
|
||||
@@ -109,3 +109,4 @@ endif()
|
||||
if (WIN32)
|
||||
include(${CMAKE_SOURCE_DIR}/tools/vs_filters.cmake)
|
||||
endif()
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
SparkUseFakeOrderLogic {
|
||||
value {
|
||||
enabled: true
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ message PublisherNamespace {
|
||||
message CMEOptions
|
||||
{
|
||||
enum OnixSLogMode {
|
||||
None = 0;
|
||||
Important = 10;
|
||||
Regular = 50;
|
||||
Debug = 100;
|
||||
|
||||
@@ -96,6 +96,10 @@ void configure_logging(bts::config::Logging const&cfg)
|
||||
{log::User,"User"},
|
||||
{log::OrderMan,"OrderMan"},
|
||||
{log::Latency,"Latency"},
|
||||
{log::Assert,"Assert"},
|
||||
{log::Engine,"Engine"},
|
||||
{log::Ui,"UI"},
|
||||
{log::Persist,"Persist"},
|
||||
};
|
||||
|
||||
real_cfg.sinks["console"] =
|
||||
@@ -170,9 +174,10 @@ LoggingConfigPoller::~LoggingConfigPoller ()
|
||||
}
|
||||
|
||||
namespace interop {
|
||||
|
||||
extern "C" BTS_EXPORT void Logger_log (int level, int subsystem, const char *message, const char *file, int line)
|
||||
{
|
||||
bts::log::_thread_logger.logger->enqueue(log::Subsystem{(uint8_t)subsystem},log::Level{(uint8_t)level},file,line,message);
|
||||
bts::log::_thread_logger.logger->enqueue(log::Subsystem{(uint8_t)subsystem}, log::Level{(uint8_t)level}, file, line, "{}", std::string(message));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -33,6 +33,11 @@ constexpr log::Subsystem Persistence{Api.ordinal+1};
|
||||
constexpr log::Subsystem User {Persistence.ordinal+1};
|
||||
constexpr log::Subsystem OrderMan {User.ordinal+1};
|
||||
constexpr log::Subsystem Latency {OrderMan.ordinal+1};
|
||||
constexpr log::Subsystem Assert {Latency.ordinal+1};
|
||||
constexpr log::Subsystem Engine {Assert.ordinal+1};
|
||||
constexpr log::Subsystem Ui {Engine.ordinal+1};
|
||||
constexpr log::Subsystem Persist {Ui.ordinal+1};
|
||||
// Please keep this list in sync with Logger.cs
|
||||
|
||||
struct LoggerHandle {
|
||||
LoggerHandle(LoggerHandle const&) = delete;
|
||||
|
||||
@@ -131,7 +131,7 @@ void replay_recording(istream& in, IRelayWriter& writer, int32_t naggle_ms) {
|
||||
}
|
||||
}
|
||||
|
||||
void replay_file(const std::string& filename, IRelayWriter& writer, int32_t naggle_ms) {
|
||||
void replay_file(const std::string& filename, IRelayWriter& writer, int32_t naggle_ms, bool loop = false) {
|
||||
ifstream in;
|
||||
in.open(filename, ios::binary | ios::in);
|
||||
if (in.is_open()) {
|
||||
@@ -140,6 +140,7 @@ void replay_file(const std::string& filename, IRelayWriter& writer, int32_t nagg
|
||||
else {
|
||||
LOG(MarketData,Diag, "Cannot read file {}", filename);
|
||||
}
|
||||
if (loop) replay_file(filename, writer, naggle_ms, true);
|
||||
}
|
||||
|
||||
void replay_url(const std::string& url, IRelayWriter& writer, int32_t naggle_ms) {
|
||||
@@ -152,7 +153,7 @@ void replay_url(const std::string& url, IRelayWriter& writer, int32_t naggle_ms)
|
||||
auto filename = url.substr(last_slash+1);
|
||||
|
||||
utils::download_file_if_newer(host, path, filename);
|
||||
replay_file(filename, writer, naggle_ms);
|
||||
replay_file(filename, writer, naggle_ms, true);
|
||||
}
|
||||
|
||||
shared_ptr<IRelayWriter> mkrelayproducer(bool shared);
|
||||
|
||||
@@ -720,6 +720,7 @@ message PostHedgePriceBasedForcedCross
|
||||
message OrderMetadata {
|
||||
uint32 color = 10;
|
||||
string key_binding = 11;
|
||||
bool no_props = 12;
|
||||
}
|
||||
|
||||
message Fill {
|
||||
@@ -757,7 +758,6 @@ message OrderStatus {
|
||||
string text = 200;
|
||||
|
||||
OrderID parent_id = 220;
|
||||
repeated OrderID children = 300;
|
||||
}
|
||||
|
||||
message OrderBookEntry
|
||||
@@ -786,6 +786,7 @@ message CrossingHedgeOrder
|
||||
{
|
||||
uint32 ticks_threshold = 10;
|
||||
uint32 market_cross_ticks = 20;
|
||||
OrderID pre_assigned_id = 30;
|
||||
}
|
||||
|
||||
message ExecutionStrategy
|
||||
|
||||
@@ -352,6 +352,30 @@ void MDP3Listener::onBookUpdate(onixs::Handler&, const onixs::Security& sec, con
|
||||
}
|
||||
//
|
||||
// Trades
|
||||
void MDP3Listener::onTrade(onixs::Handler&, const onixs::Security& sec, const onixs::RecoveryEntryArgs& arg) {
|
||||
utils::TimeStamp ts = utils::TimeStamp::now();
|
||||
auto* data = _index.get_security(sec.id());
|
||||
if (data != NULL) {
|
||||
int size = 0;
|
||||
arg.entry().entrySize(size);
|
||||
onixs::PRICE price;
|
||||
arg.entry().entryPx(price);
|
||||
PriceSize ps = pricesize_of_price_size(price, data->handle.security().display_factor, size);
|
||||
auto date = ll_of_timestamp(arg.message().transactTime());
|
||||
data->handle.add_trade(ts, ps, date, data->electronic_volume + size);
|
||||
}
|
||||
}
|
||||
void MDP3Listener::onTrade(onixs::Handler&, const onixs::Security& sec, const onixs::TradeSummaryArgs& arg) {
|
||||
utils::TimeStamp ts = utils::TimeStamp::now();
|
||||
auto* data = _index.get_security(sec.id());
|
||||
if (data != NULL) {
|
||||
auto size = arg.entry().entrySize();
|
||||
onixs::PRICE price = arg.entry().entryPx();
|
||||
PriceSize ps = pricesize_of_price_size(price, data->handle.security().display_factor, size);
|
||||
auto date = ll_of_timestamp(arg.message().transactTime());
|
||||
data->handle.add_trade(ts, ps, date, data->electronic_volume + size);
|
||||
}
|
||||
}
|
||||
void MDP3Listener::onTrade(onixs::Handler&, const onixs::Security& sec, const onixs::TradeArgs& arg) {
|
||||
utils::TimeStamp ts = utils::TimeStamp::now();
|
||||
if (arg.entry().updateAction() == onixs::UpdateAction::New) {
|
||||
|
||||
@@ -56,7 +56,9 @@ public:
|
||||
|
||||
//
|
||||
// Trades
|
||||
void onTrade(onixs::Handler&, const onixs::Security&, const onixs::RecoveryEntryArgs&) override;
|
||||
void onTrade(onixs::Handler&, const onixs::Security&, const onixs::TradeArgs&) override;
|
||||
void onTrade(onixs::Handler&, const onixs::Security&, const onixs::TradeSummaryArgs&) override;
|
||||
|
||||
//
|
||||
// RFQ
|
||||
|
||||
@@ -29,8 +29,7 @@ MDP3Main::MDP3Main() :
|
||||
_engines(),
|
||||
_handlers(),
|
||||
_listeners(),
|
||||
_recovery(),
|
||||
_loggers()
|
||||
_recovery()
|
||||
{
|
||||
}
|
||||
|
||||
@@ -260,10 +259,16 @@ unique_ptr<onixs::Handler> MDP3Main::prepare_handler(const string& channel_id) {
|
||||
|
||||
//
|
||||
// Logging
|
||||
onixs::FileLoggerSettings loggerSettings;
|
||||
loggerSettings.filename(log_path() + "/log_" + channel_id);
|
||||
loggerSettings.severityLevel((onixs::LogSeverity::Enum)options.onixs_log_mode());
|
||||
std::unique_ptr<onixs::FileLogger> logger(new onixs::FileLogger(loggerSettings));
|
||||
onixs::Logger* logger;
|
||||
if (options.onixs_log_mode() == CMEOptions_OnixSLogMode_None) {
|
||||
logger = new onixs::NullLogger();
|
||||
}
|
||||
else {
|
||||
onixs::FileLoggerSettings loggerSettings;
|
||||
loggerSettings.filename(log_path() + "/log_" + channel_id);
|
||||
loggerSettings.severityLevel((onixs::LogSeverity::Enum)options.onixs_log_mode());
|
||||
logger = new onixs::FileLogger(loggerSettings);
|
||||
}
|
||||
|
||||
|
||||
//
|
||||
@@ -294,7 +299,6 @@ unique_ptr<onixs::Handler> MDP3Main::prepare_handler(const string& channel_id) {
|
||||
}
|
||||
if (logger) {
|
||||
handler->bindLogger(*logger);
|
||||
_loggers.push_back(std::move(logger));
|
||||
}
|
||||
|
||||
return handler;
|
||||
|
||||
@@ -45,7 +45,6 @@ private:
|
||||
std::vector<std::unique_ptr<onixs::Handler>> _handlers;
|
||||
std::vector<std::unique_ptr<MDP3Listener>> _listeners;
|
||||
std::vector<std::unique_ptr<onixs::TcpRecoveryService>> _recovery;
|
||||
std::vector<std::unique_ptr<onixs::FileLogger>> _loggers;
|
||||
};
|
||||
|
||||
}}//namespace
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
#pragma once
|
||||
#include <OnixS/CME/MDH.h>
|
||||
|
||||
namespace onixs = OnixS::CME::MDH;
|
||||
// namespace onixs = OnixS::CME::MDH;
|
||||
namespace onixs {
|
||||
using namespace OnixS::CME::MDH;
|
||||
}
|
||||
@@ -48,9 +48,7 @@ void clean_dir(const std::string base_path) {
|
||||
void run_replay() {
|
||||
auto naggle_ms = config::get<RelayOptions>().naggle_ms();
|
||||
auto file = "http://mdreplay/spark/futures.coconut";
|
||||
while(true) {
|
||||
replay_recording(file, naggle_ms);
|
||||
}
|
||||
replay_recording(file, naggle_ms);
|
||||
}
|
||||
|
||||
void run_onixs() {
|
||||
|
||||
@@ -7,6 +7,5 @@ if not exist build\src\lib\spark_lib.vcxproj (
|
||||
copy /y tools\cpp.build.props build\Directory.Build.Props > nul
|
||||
@call "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\Tools\VsDevCmd.bat" > nul
|
||||
cd %~dp0\..
|
||||
msbuild /m /p:platform=x64 /clp:verbosity=minimal /clp:summary /t:restore spark_client.sln
|
||||
msbuild /m /p:platform=x64 /p:GenerateFullPaths=true /clp:verbosity=minimal /clp:summary spark_client.sln
|
||||
|
||||
msbuild /m /p:platform=x64 /clp:verbosity=minimal /clp:summary /t:restore %* spark_client.sln
|
||||
msbuild /m /p:platform=x64 /p:GenerateFullPaths=true /clp:verbosity=minimal /clp:summary %* spark_client.sln
|
||||
@@ -0,0 +1,2 @@
|
||||
@echo off
|
||||
start %~dp0\..\build\Debug\bin\net462\Spark.exe
|
||||
Reference in new issue
Block a user