Merge branch 'master' of bitbucket.org:bluetradesys/spark into limits
This commit is contained in:
commit
d03574ccc7
127 files changed
+2011
-1197
No files matched your search
@@ -128,6 +128,7 @@ namespace System.Collections.ObjectModel
|
||||
public static class ObservableCollectionExtensions
|
||||
{
|
||||
public static int RemoveAll<T>(this ObservableCollection<T> collection, Func<T, bool> match) {
|
||||
if (collection == null) return 0;
|
||||
// In terms of allocations we could do this more efficiently by copying items from the end of the
|
||||
// collection in (see https://referencesource.microsoft.com/#q=RemoveAll) but that would allow
|
||||
// transient duplication in the list which could be observed from the outside
|
||||
@@ -218,7 +219,7 @@ namespace mbts.collections.extensions
|
||||
public static class DictionaryExtensions
|
||||
{
|
||||
#region GetValueOrDefault
|
||||
public static TValue GetValueOrDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key) {
|
||||
public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key) {
|
||||
return dictionary.TryGetValue(key, out TValue result) ? result : default(TValue);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,14 +7,18 @@ using System.Threading.Tasks;
|
||||
namespace bts.api
|
||||
{
|
||||
public interface ITag { }
|
||||
// It is important that ITag<T> is a distinct type from ITag
|
||||
public interface ITag<T> { }
|
||||
public interface ISubscribe
|
||||
{
|
||||
IObservable<T> subscribe<T>(ITag tag);
|
||||
IObservable<T> subscribe<T>(ITag<T> tag);
|
||||
}
|
||||
|
||||
public interface IPost
|
||||
{
|
||||
void post<T>(ITag tag, T data);
|
||||
void post<T>(ITag<T> tag, T data);
|
||||
}
|
||||
|
||||
public interface IBus : IPost, ISubscribe
|
||||
|
||||
@@ -1,37 +1,44 @@
|
||||
using bts.api;
|
||||
using bts.api;
|
||||
using mbts.utils;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.Composition;
|
||||
using System.Reactive.Subjects;
|
||||
|
||||
namespace bts.core
|
||||
{
|
||||
[Export(typeof(IBus))]
|
||||
public class SingletonBus : IBus {
|
||||
|
||||
private class SubjectSingleton<T> {
|
||||
public static Dictionary<ITag, ISubject<T>> instance = new Dictionary<ITag, ISubject<T>>();
|
||||
}
|
||||
|
||||
private ISubject<T> subject<T>(ITag tag) {
|
||||
var inst = SubjectSingleton<T>.instance;
|
||||
lock (inst) {
|
||||
if (inst.TryGetValue(tag, out ISubject<T> result)) {
|
||||
return result;
|
||||
}
|
||||
result = new StateSubject<T>();
|
||||
inst[tag] = result;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public void post<T>(ITag tag, T data) {
|
||||
subject<T>(tag).OnNext(data);
|
||||
}
|
||||
|
||||
public IObservable<T> subscribe<T>(ITag tag) {
|
||||
return subject<T>(tag);
|
||||
}
|
||||
}
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.Composition;
|
||||
using System.Reactive.Subjects;
|
||||
|
||||
namespace bts.core
|
||||
{
|
||||
[Export(typeof(IBus))]
|
||||
public class SingletonBus : IBus {
|
||||
|
||||
private class SubjectSingleton<T> {
|
||||
public static Dictionary<object, ISubject<T>> instance = new Dictionary<object, ISubject<T>>();
|
||||
}
|
||||
|
||||
private ISubject<T> subject<T>(object tag) {
|
||||
var inst = SubjectSingleton<T>.instance;
|
||||
lock (inst) {
|
||||
if (inst.TryGetValue(tag, out ISubject<T> result)) {
|
||||
return result;
|
||||
}
|
||||
result = new Subject<T>();
|
||||
inst[tag] = result;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public void post<T>(ITag tag, T data) {
|
||||
subject<T>(tag).OnNext(data);
|
||||
}
|
||||
public void post<T>(ITag<T> tag, T data) {
|
||||
subject<T>(tag).OnNext(data);
|
||||
}
|
||||
|
||||
public IObservable<T> subscribe<T>(ITag tag) {
|
||||
return subject<T>(tag);
|
||||
}
|
||||
|
||||
public IObservable<T> subscribe<T>(ITag<T> tag) {
|
||||
return subject<T>(tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ namespace mbts.spark
|
||||
class GatewayAdapter : IMarketDataSource, IDropCopy, IPollable
|
||||
{
|
||||
SimExchangeGateway _gw;
|
||||
IDictionary<uint, SecurityMD> _cache;
|
||||
IReadOnlyDictionary<uint, SecurityMD> _cache;
|
||||
object _lock = new object();
|
||||
|
||||
ConcurrentBag<Tuple<SecurityMD, MDHolder<BBOSubject>>> _bbo = new ConcurrentBag<Tuple<SecurityMD, MDHolder<BBOSubject>>>();
|
||||
@@ -61,8 +61,8 @@ namespace mbts.spark
|
||||
}
|
||||
}
|
||||
|
||||
public IObservable<Tuple<co2.PriceSize, co2.PriceSize>>
|
||||
subscribe_bbo(bts.api.Security security)
|
||||
public IObservable<Tuple<PriceSize, PriceSize>>
|
||||
subscribe_bbo(bts.api.SecurityImmutable security)
|
||||
{
|
||||
lock(_cache)
|
||||
{
|
||||
@@ -77,8 +77,8 @@ namespace mbts.spark
|
||||
}
|
||||
}
|
||||
|
||||
public IObservable<Tuple<co2.PriceSize[], co2.PriceSize[]>>
|
||||
subscribe_depth(bts.api.Security security)
|
||||
public IObservable<Tuple<PriceSize[], PriceSize[]>>
|
||||
subscribe_depth(bts.api.SecurityImmutable security)
|
||||
{
|
||||
lock(_cache)
|
||||
{
|
||||
|
||||
@@ -6,9 +6,9 @@ using mbts.co2;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
public interface IMarketDataSource
|
||||
interface IMarketDataSource
|
||||
{
|
||||
IObservable<Tuple<PriceSize, PriceSize>> subscribe_bbo(Security security);
|
||||
IObservable<Tuple<PriceSize[], PriceSize[]>> subscribe_depth(Security security);
|
||||
IObservable<Tuple<PriceSize, PriceSize>> subscribe_bbo(SecurityImmutable security);
|
||||
IObservable<Tuple<PriceSize[], PriceSize[]>> subscribe_depth(SecurityImmutable security);
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,6 @@ namespace mbts.spark
|
||||
{
|
||||
_bus = bus;
|
||||
_consumer = Co2RelayControl.instance.consumer;
|
||||
new OrderHub(bus, username);
|
||||
}
|
||||
|
||||
public void OnCompleted() { }
|
||||
@@ -45,7 +44,6 @@ namespace mbts.spark
|
||||
temp.Add(v.security.Id, new SecurityMD(v.security, v.handle));
|
||||
}
|
||||
_exchange_sec_map = temp;
|
||||
//_publish_securities();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,7 +81,6 @@ 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +89,7 @@ namespace mbts.spark
|
||||
var rv = new Dictionary<security_key, SecurityMD>(_exchange_sec_map);
|
||||
foreach (var kv in _synthetic_sec_map)
|
||||
{
|
||||
Security sec = kv.Value.security;
|
||||
var sec = kv.Value.security;
|
||||
rv.Add(sec.Id, new SecurityMD(sec, new SyntheticSecurityMDHandle(sec, _exchange_sec_map)));
|
||||
}
|
||||
Logger.log(bts.log.Level.Info, bts.log.Subsystem.gen, String.Format("MDSource publishing {0} securities", rv.Count));
|
||||
|
||||
@@ -14,11 +14,11 @@ namespace mbts.spark
|
||||
[ImportingConstructor]
|
||||
public PositionSource(IBus bus) {
|
||||
_bus = bus;
|
||||
_orders_model = new OrdersModel(_bus);
|
||||
_orders_model = new DemoOrdersModel(_bus);
|
||||
}
|
||||
|
||||
private readonly IBus _bus;
|
||||
private readonly OrdersModel _orders_model;
|
||||
private readonly DemoOrdersModel _orders_model;
|
||||
|
||||
public int priority => int.MaxValue;
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using mbts.co2;
|
||||
using bts.api;
|
||||
using mbts.co2;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -9,10 +10,10 @@ namespace mbts.spark
|
||||
{
|
||||
struct SecurityMD
|
||||
{
|
||||
public bts.api.Security security { get; }
|
||||
public SecurityImmutable security { get; }
|
||||
public IMDHandle md { get; }
|
||||
|
||||
public SecurityMD(bts.api.Security security, IMDHandle md) {
|
||||
public SecurityMD(SecurityImmutable security, IMDHandle md) {
|
||||
this.security = security;
|
||||
this.md = md;
|
||||
}
|
||||
|
||||
@@ -50,15 +50,15 @@ namespace mbts.spark
|
||||
}
|
||||
public class ShowAuditLogsMessage { }
|
||||
public class ShowFillsMessage { }
|
||||
public class ShowLadderMessage : BusMessageWrapper<IReadOnlyCollection<Security>> {
|
||||
public ShowLadderMessage(Security security) : this(new[] { security }) { }
|
||||
public ShowLadderMessage(IReadOnlyCollection<Security> security) : base(security) { }
|
||||
public class ShowLadderMessage : BusMessageWrapper<IReadOnlyCollection<SecurityImmutable>> {
|
||||
public ShowLadderMessage(SecurityImmutable security) : this(new[] { security }) { }
|
||||
public ShowLadderMessage(IReadOnlyCollection<SecurityImmutable> security) : base(security) { }
|
||||
}
|
||||
public class ShowLinkedLadderMessage : BusMessageWrapper<IObservable<SecurityMD>> {
|
||||
public ShowLinkedLadderMessage(IObservable<SecurityMD> security_md) : base(security_md) { }
|
||||
}
|
||||
public class ShowMarketViewMessage : BusMessageWrapper<IReadOnlyCollection<Security>> {
|
||||
public ShowMarketViewMessage(IReadOnlyCollection<Security> securities) : base(securities) { }
|
||||
public class ShowMarketViewMessage : BusMessageWrapper<IReadOnlyCollection<SecurityImmutable>> {
|
||||
public ShowMarketViewMessage(IReadOnlyCollection<SecurityImmutable> securities) : base(securities) { }
|
||||
}
|
||||
public class ShowOrderBookMessage { }
|
||||
public class ShowOrderModifyMessage : BusMessageWrapper<IReadOnlyCollection<Order>> {
|
||||
@@ -73,17 +73,17 @@ namespace mbts.spark
|
||||
public ShowLinkedOrderTicketMessage(IObservable<Order> order) : base(order) { }
|
||||
}
|
||||
public class ShowPositionsMessage { }
|
||||
public class ShowSpreadMatrixMessage : BusMessageWrapper<IReadOnlyCollection<Security>> {
|
||||
public ShowSpreadMatrixMessage(IReadOnlyCollection<Security> securities) : base(securities) { }
|
||||
public class ShowSpreadMatrixMessage : BusMessageWrapper<IReadOnlyCollection<SecurityImmutable>> {
|
||||
public ShowSpreadMatrixMessage(IReadOnlyCollection<SecurityImmutable> securities) : base(securities) { }
|
||||
}
|
||||
public class ShowSyntheticCreateMessage : BusMessageWrapper<IReadOnlyCollection<Security>> {
|
||||
public ShowSyntheticCreateMessage(IReadOnlyCollection<Security> securities) : base(securities) { }
|
||||
public class ShowSyntheticCreateMessage : BusMessageWrapper<IReadOnlyCollection<SecurityImmutable>> {
|
||||
public ShowSyntheticCreateMessage(IReadOnlyCollection<SecurityImmutable> securities) : base(securities) { }
|
||||
}
|
||||
public class ShowSyntheticStrategyMessage : BusMessageWrapper<Security> {
|
||||
public ShowSyntheticStrategyMessage(Security security) : base(security) { }
|
||||
public class ShowSyntheticStrategyMessage : BusMessageWrapper<SecurityImmutable> {
|
||||
public ShowSyntheticStrategyMessage(SecurityImmutable security) : base(security) { }
|
||||
}
|
||||
public class ShowTimeAndSalesMessage : BusMessageWrapper<IReadOnlyCollection<Security>> {
|
||||
public ShowTimeAndSalesMessage(IReadOnlyCollection<Security> security) : base(security) { }
|
||||
public class ShowTimeAndSalesMessage : BusMessageWrapper<IReadOnlyCollection<SecurityImmutable>> {
|
||||
public ShowTimeAndSalesMessage(IReadOnlyCollection<SecurityImmutable> security) : base(security) { }
|
||||
}
|
||||
|
||||
public class PositionsMessage : BusMessageWrapper<IReadOnlyDictionary<uint, int>> {
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
using bts.api;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace mbts.spark {
|
||||
public static class SparkTags {
|
||||
static class SparkTags {
|
||||
private class SparkTag : ITag { private readonly string Name; public SparkTag(string name) { Name = name; } }
|
||||
private class SparkTag<T> : ITag<T> { private readonly string Name; public SparkTag(string name) { Name = name; } }
|
||||
|
||||
#region Core Data
|
||||
public static ITag ExchangeSecuritiesTag { get; } = new SparkTag("ExchangeSecuritiesTag");
|
||||
public static ITag SecuritiesTag { get; } = new SparkTag("Securities");
|
||||
public static ITag<IReadOnlyDictionary<uint, SecurityMD>> SecuritiesTag { get; } = new SparkTag<IReadOnlyDictionary<uint, SecurityMD>>("Securities");
|
||||
public static ITag SyntheticSecuritiesTag { get; } = new SparkTag("SyntheticSecuritiesTag");
|
||||
public static ITag OrderBookTag = new SparkTag("OrderBookTag");
|
||||
public static ITag PositionsTag { get; } = new SparkTag(nameof(PositionsTag));
|
||||
|
||||
@@ -71,10 +71,10 @@ namespace mbts.spark
|
||||
public uint normalized_head_size { get { return active ? levels[0].qty : 0; } }
|
||||
}
|
||||
|
||||
private readonly Security _security;
|
||||
private readonly SecurityImmutable _security;
|
||||
private IEnumerable<Tuple<SecurityMD, Side, double>> _legs;
|
||||
private const uint _default_book_size = 10;
|
||||
public SyntheticSecurityMDHandle(Security security, IDictionary<uint, SecurityMD> md_handles)
|
||||
public SyntheticSecurityMDHandle(SecurityImmutable security, IDictionary<uint, SecurityMD> md_handles)
|
||||
{
|
||||
_security = security;
|
||||
_legs = security.get_base_exchange_securities().Select(t =>
|
||||
|
||||
@@ -7,23 +7,23 @@ using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
|
||||
namespace mbts.spark {
|
||||
public static class TickUtils {
|
||||
public static readonly ContractSpecification DefaultSpec = new ContractSpecification { CashPerPoint = 1.0, LowTick = 0.01, HighTick = 0.01, PriceBreak = double.MaxValue, PriceMultiplier = 1.0 };
|
||||
public static double ticksize(this ContractSpecification spec, double price) {
|
||||
static class TickUtils {
|
||||
public static readonly ContractSpecificationImmutable DefaultSpec = new ContractSpecification { CashPerPoint = 1.0, LowTick = 0.01, HighTick = 0.01, PriceBreak = double.MaxValue, PriceMultiplier = 1.0 };
|
||||
public static double ticksize(this ContractSpecificationImmutable spec, double price) {
|
||||
return Math.Abs(price) > spec.PriceBreak ? spec.HighTick : spec.LowTick;
|
||||
}
|
||||
|
||||
public static string format(this ContractSpecification spec, double price) {
|
||||
public static string format(this ContractSpecificationImmutable spec, double price) {
|
||||
var tick_factors = _get_tick_factors(spec.ticksize(price));
|
||||
return tick_factors.format(price, false);
|
||||
}
|
||||
|
||||
public static double parse(this ContractSpecification spec, string text) {
|
||||
public static double parse(this ContractSpecificationImmutable spec, string text) {
|
||||
var regional_tfs = new RegionalTickFactors { low_tick = _get_tick_factors(spec.LowTick), high_tick = _get_tick_factors(spec.HighTick), low_tick_inclusive_end = spec.PriceBreak };
|
||||
return regional_tfs.parse(text);
|
||||
}
|
||||
|
||||
public static double mid_tick(ContractSpecification spec, double bid, double ask) {
|
||||
public static double mid_tick(ContractSpecificationImmutable spec, double bid, double ask) {
|
||||
double raw_mid;
|
||||
if (double.IsNaN(bid)) { raw_mid = ask; }
|
||||
else if (double.IsNaN(ask)) { raw_mid = bid; }
|
||||
@@ -35,12 +35,12 @@ 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 ContractSpecificationImmutable contract, double value) { return get_regional_ticks(contract).tickup(value); }
|
||||
public static double tickup(this ContractSpecificationImmutable contract, double value, int count) { return get_regional_ticks(contract).tickup(value, (uint)count); }
|
||||
public static double tickdown(this ContractSpecificationImmutable contract, double value) { return get_regional_ticks(contract).tickdown(value); }
|
||||
public static double tickdown(this ContractSpecificationImmutable 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) {
|
||||
public static double round_to_tick(this ContractSpecificationImmutable spec, double value) {
|
||||
double intpart = (long)value;
|
||||
double floatpart = value % 1;
|
||||
double tick = spec.ticksize(value);
|
||||
@@ -48,7 +48,7 @@ namespace mbts.spark {
|
||||
return intpart + floatpart;
|
||||
}
|
||||
|
||||
public static int ticks_between(double a, double b, ContractSpecification spec) {
|
||||
public static int ticks_between(double a, double b, ContractSpecificationImmutable spec) {
|
||||
double low = Math.Min(a, b);
|
||||
double high = Math.Max(a, b);
|
||||
int count = 0;
|
||||
@@ -59,10 +59,10 @@ namespace mbts.spark {
|
||||
return count;
|
||||
}
|
||||
|
||||
public static int[] get_tick_jump_quantities(ContractSpecification spec) {
|
||||
public static int[] get_tick_jump_quantities(ContractSpecificationImmutable 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(ContractSpecificationImmutable 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) {
|
||||
|
||||
@@ -23,7 +23,7 @@ namespace mbts.spark {
|
||||
IDisposable _settings_sub, _tick_sub;
|
||||
LadderSettings _settings;
|
||||
LadderVM _vm;
|
||||
ContractSpecification _spec;
|
||||
ContractSpecificationImmutable _spec;
|
||||
|
||||
VisualHost _visualHost = new VisualHost() {};
|
||||
LadderOrdersHost _ordershost;
|
||||
@@ -55,7 +55,7 @@ namespace mbts.spark {
|
||||
|
||||
public event Action<double,Side?> click;
|
||||
|
||||
public Security security => _vm.security;
|
||||
public SecurityImmutable security => _vm.security;
|
||||
|
||||
public ICommand RecenterCommand { get; }
|
||||
public ICommand Command {
|
||||
|
||||
@@ -14,15 +14,15 @@ namespace mbts.spark {
|
||||
|
||||
class LadderModel {
|
||||
|
||||
private OrdersModel _order_gateway;
|
||||
private DemoOrdersModel _order_gateway;
|
||||
|
||||
public LadderModel(SecurityMD source, OrdersModel ordergw) {
|
||||
public LadderModel(SecurityMD source, DemoOrdersModel ordergw) {
|
||||
security = source.security;
|
||||
md = source.md;
|
||||
_order_gateway = ordergw;
|
||||
}
|
||||
|
||||
public Security security { get; }
|
||||
public SecurityImmutable security { get; }
|
||||
public IMDHandle md { get; }
|
||||
|
||||
public enum CancelType { All, Bids, Asks }
|
||||
@@ -32,6 +32,6 @@ namespace mbts.spark {
|
||||
Logger.info(bts.log.Subsystem.Ui, $"Cancel {ct}");
|
||||
}
|
||||
|
||||
public OrdersModel order_gateway => _order_gateway;
|
||||
public DemoOrdersModel order_gateway => _order_gateway;
|
||||
}
|
||||
}
|
||||
@@ -68,7 +68,7 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
internal LadderModel model => _model;
|
||||
public Security security => _model.security;
|
||||
public SecurityImmutable security => _model.security;
|
||||
public IMDHandle md => _model.md;
|
||||
|
||||
public bool is_synthetic => _model.security.ContractCase == Security.ContractOneofCase.Synthetic;
|
||||
|
||||
@@ -30,7 +30,7 @@ namespace mbts.spark {
|
||||
#pragma warning restore CS0618 // Type or member is obsolete
|
||||
}
|
||||
|
||||
public static double[] gen_prices(double mid, int row_count, ContractSpecification spec) {
|
||||
public static double[] gen_prices(double mid, int row_count, ContractSpecificationImmutable spec) {
|
||||
// require odd number
|
||||
Logger.assert(row_count % 2 == 1);
|
||||
var result = new double[row_count];
|
||||
@@ -48,7 +48,7 @@ namespace mbts.spark {
|
||||
return result;
|
||||
}
|
||||
|
||||
public static FormattedText[] format_prices(double[] prices, string font_family, double font_size, SolidColorBrush foreground, ContractSpecification spec) {
|
||||
public static FormattedText[] format_prices(double[] prices, string font_family, double font_size, SolidColorBrush foreground, ContractSpecificationImmutable spec) {
|
||||
var result = new FormattedText[prices.Length];
|
||||
var font = new Typeface(font_family);
|
||||
Parallel.For(0, prices.Length, i => {
|
||||
@@ -64,7 +64,7 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
public static double[] render_prices(DrawingVisual price, double mid, int row_count, double row_height,
|
||||
LadderColumnSettings settings, ContractSpecification spec) {
|
||||
LadderColumnSettings settings, ContractSpecificationImmutable spec) {
|
||||
var foreground = new SolidColorBrush(settings.foreground.rgb_color());
|
||||
var background = new SolidColorBrush(settings.background.rgb_color());
|
||||
var dprices = gen_prices(mid, row_count, spec);
|
||||
@@ -107,7 +107,7 @@ namespace mbts.spark {
|
||||
double[] prices,
|
||||
NativePriceSize[] rungs,
|
||||
double row_height,
|
||||
ContractSpecification spec,
|
||||
ContractSpecificationImmutable spec,
|
||||
LadderColumnSettings settings
|
||||
) {
|
||||
if (rungs.Length > 1) {
|
||||
|
||||
@@ -23,7 +23,7 @@ namespace mbts.spark {
|
||||
is_bts_type = order.Descriptor.Name.StartsWith("BTS", StringComparison.CurrentCultureIgnoreCase);
|
||||
algo_type = OrderDataHelper.get_algo_type(order);
|
||||
_accessor = Order.Descriptor.Oneofs
|
||||
.First(ood => ood.Name == "algo_order_type")
|
||||
.First(ood => ood.Name == "AlgoOrderType")
|
||||
.Fields
|
||||
.First(f => f.MessageType == order.Descriptor)
|
||||
.Accessor;
|
||||
|
||||
@@ -15,7 +15,7 @@ namespace mbts.spark {
|
||||
DispatcherTimer _timer = new DispatcherTimer(DispatcherPriority.Background) {
|
||||
Interval = TimeSpan.FromSeconds(1)
|
||||
};
|
||||
Security _security;
|
||||
SecurityImmutable _security;
|
||||
IMDHandle _handle;
|
||||
LadderSettings _settings;
|
||||
DateTime _last_recenter = DateTime.MaxValue;
|
||||
@@ -29,7 +29,7 @@ namespace mbts.spark {
|
||||
_timer.Start();
|
||||
}
|
||||
|
||||
static (double,double) tick_range(double price, int tick_count, ContractSpecification spec) {
|
||||
static (double,double) tick_range(double price, int tick_count, ContractSpecificationImmutable spec) {
|
||||
return (TickUtils.tickdown(spec, price, tick_count), TickUtils.tickup(spec, price, tick_count));
|
||||
}
|
||||
|
||||
|
||||
@@ -8,8 +8,7 @@ using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
using static mbts.spark.SparkBusData;
|
||||
using static mbts.spark.SparkTags;
|
||||
using MDMap = System.Collections.Generic.Dictionary<System.UInt32, mbts.spark.SecurityMD>;
|
||||
using SecurityKey = System.UInt32;
|
||||
using security_key = System.UInt32;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
@@ -20,25 +19,25 @@ namespace mbts.spark
|
||||
_subs.Add(_bus.subscribe<PositionsMessage>(PositionsTag).Subscribe(m => {
|
||||
foreach (var kv in m.data) _positions_demuxer.push_data(kv.Key, kv.Value);
|
||||
}));
|
||||
_orders_model = new OrdersModel(_bus);
|
||||
_orders_model = new DemoOrdersModel(_bus);
|
||||
}
|
||||
|
||||
private readonly IBus _bus;
|
||||
private readonly OrdersModel _orders_model;
|
||||
private readonly Subject<HashSet<SecurityKey>> _securities_subject = new Subject<HashSet<SecurityKey>>();
|
||||
private readonly ObservableDemuxer<SecurityKey, int> _positions_demuxer = new ObservableDemuxer<SecurityKey, int>(k => 0);
|
||||
private readonly DemoOrdersModel _orders_model;
|
||||
private readonly Subject<HashSet<security_key>> _securities_subject = new Subject<HashSet<security_key>>();
|
||||
private readonly ObservableDemuxer<security_key, int> _positions_demuxer = new ObservableDemuxer<security_key, int>(k => 0);
|
||||
private IList<IDisposable> _subs = new List<IDisposable>();
|
||||
private IDictionary<SecurityKey, SecurityMD> _data = new Dictionary<SecurityKey, SecurityMD>();
|
||||
private IDictionary<security_key, SecurityMD> _data = new Dictionary<security_key, SecurityMD>();
|
||||
|
||||
public IObservable<IEnumerable<SecurityMD>> rows => _bus.subscribe<MDMap>(SecuritiesTag).StartWith(new MDMap()).CombineLatest(_securities_subject, (md, secs) => md.Intersect(secs, kv => kv.Key).Select(kv => kv.Value));
|
||||
public IReadOnlyCollection<Security> all_securities => _data.Values.Select(s => s.security).ToList();
|
||||
public OrdersModel orders_model => _orders_model;
|
||||
public IObservable<IEnumerable<SecurityMD>> rows => _bus.subscribe(SecuritiesTag).StartWith(new Dictionary<uint, SecurityMD>()).CombineLatest(_securities_subject, (md, secs) => md.Intersect(secs, kv => kv.Key).Select(kv => kv.Value));
|
||||
public IReadOnlyCollection<SecurityImmutable> all_securities => _data.Values.Select(s => s.security).ToList();
|
||||
public DemoOrdersModel orders_model => _orders_model;
|
||||
|
||||
public IObservable<int> security_position(SecurityKey key) { return _positions_demuxer.subscribe(key).DistinctUntilChanged(); }
|
||||
public void show_ladder(Security security) { _bus.post(ShowLadderTag, new ShowLadderMessage(security)); }
|
||||
public IObservable<int> security_position(security_key key) { return _positions_demuxer.subscribe(key).DistinctUntilChanged(); }
|
||||
public void show_ladder(SecurityImmutable security) { _bus.post(ShowLadderTag, new ShowLadderMessage(security)); }
|
||||
public void show_order_modify(Order order) { _bus.post(ShowOrderModifyTag, new ShowOrderModifyMessage(order)); }
|
||||
public void show_order_ticket(Order order) { _orders_model.show_order_ticket(order); }
|
||||
public void set_securities(IEnumerable<Security> securities) { _securities_subject.OnNext(new HashSet<SecurityKey>(securities.Select(s => s.Id))); }
|
||||
public void set_securities(IEnumerable<SecurityImmutable> securities) { _securities_subject.OnNext(new HashSet<security_key>(securities.Select(s => s.Id))); }
|
||||
public void Dispose() {
|
||||
Disposable.dispose(_subs);
|
||||
_securities_subject.Dispose();
|
||||
|
||||
@@ -80,7 +80,7 @@ namespace mbts.spark
|
||||
private void _animation_AnimationsChanged() { RaisePropertyChanged(nameof(animations)); }
|
||||
|
||||
#region Bound Properties
|
||||
public SelectableViewModelBase<Security> security { get; }
|
||||
public SelectableViewModelBase<SecurityImmutable> security { get; }
|
||||
public RXReadOnlyDataGridCell<int> position { get; }
|
||||
public RXReadOnlyDataGridCell<double> last_price { get; }
|
||||
public RXReadOnlyDataGridCell<ushort> last_size { get; }
|
||||
|
||||
@@ -26,8 +26,9 @@ namespace mbts.spark
|
||||
public const int VERSION = 1;
|
||||
public const string SAVE_NAME = "MarketView";
|
||||
|
||||
public MarketViewVM(IBus bus, IReadOnlyCollection<Security> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria) {
|
||||
public MarketViewVM(IBus bus, SecuritySource ssrc, IReadOnlyCollection<SecurityImmutable> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria) {
|
||||
_bus = bus;
|
||||
_ssrc = ssrc;
|
||||
_resources.Add(_model = new MarketViewModel(bus));
|
||||
_resources.Add(_rows = new RXObservableCollection<SecurityMD>(_model.rows));
|
||||
_rows_vm = new ObservableAutoWrapper<Row, SecurityMD>(_rows, smd => new Row(this, _model, smd, _model.security_position(smd.security.Id)));
|
||||
@@ -46,6 +47,7 @@ namespace mbts.spark
|
||||
}
|
||||
|
||||
private readonly IBus _bus;
|
||||
private readonly SecuritySource _ssrc;
|
||||
private readonly MarketViewModel _model;
|
||||
private readonly ContextMenuVM _context_menu;
|
||||
private readonly ObservableAutoWrapper<Row, SecurityMD> _rows_vm;
|
||||
@@ -60,12 +62,12 @@ namespace mbts.spark
|
||||
}
|
||||
|
||||
private IEnumerable<MenuItemVM> _context_menu_item_factory() {
|
||||
yield return MenuItemVM.Create(new ModifySecuritySelectionMenuItem(_rows.Select(r => r.security).ToList(), _model.set_securities));
|
||||
yield return MenuItemVM.Create(new ModifySecuritySelectionMenuItem(_rows.Select(r => r.security).ToList(), _ssrc, _model.set_securities));
|
||||
if (current_cell != null && current_cell.Column != null && current_cell.Item != null && !current_cell.Item.Equals(System.Windows.DependencyProperty.UnsetValue)) {
|
||||
var curr_col = (Columns)DataGridEx.GetArgument(current_cell.Column);
|
||||
var securities = _rows_vm.Where(r => r.is_selected).Select(r => r.security.value).ToList();
|
||||
yield return MenuItemVM.Create(new LadderMenuItem(_bus), securities);
|
||||
yield return MenuItemVM.Create(new LinkedLadderMenuItem(_bus, _get_current_security_observable().ToSecurityMD()));
|
||||
yield return MenuItemVM.Create(new LinkedLadderMenuItem(_bus, _get_current_security_observable().ToSecurityMD(_bus)));
|
||||
yield return MenuItemVM.Create(new OrderTicketMenuItem(_model.orders_model, s => _create_order(_rows_vm.First(r => r.security.value.Equals(s)), curr_col)), securities);
|
||||
yield return MenuItemVM.Create(new LinkedOrderTicketMenuItem(_bus, _current_cell.Select(_create_order)));
|
||||
yield return MenuItemVM.Create(new SpreadMatrixMenuItem(_bus), securities);
|
||||
@@ -80,8 +82,8 @@ namespace mbts.spark
|
||||
}
|
||||
}
|
||||
|
||||
private IObservable<Security> _get_current_security_observable() { return _current_cell.Select(_get_security).DistinctUntilChanged(); }
|
||||
private static Security _get_security(DataGridCellInfo cell) { return (cell.Item as Row)?.security.value; }
|
||||
private IObservable<SecurityImmutable> _get_current_security_observable() { return _current_cell.Select(_get_security).Where(s => s.HasValue).Select(s => s.Value).DistinctUntilChanged(); }
|
||||
private static SecurityImmutable? _get_security(DataGridCellInfo cell) { return (cell.Item as Row)?.security.value; }
|
||||
private static Order _create_order(DataGridCellInfo cell) { return _create_order((Row)cell.Item, (Columns)DataGridEx.GetArgument(cell.Column)); }
|
||||
private static Order _create_order(Row row, Columns col) {
|
||||
var order = OrderDataHelper.Defaults.Order(row.security.value, Order.AlgoOrderTypeOneofCase.MarketOrder);
|
||||
@@ -114,8 +116,8 @@ namespace mbts.spark
|
||||
public class StartupData {
|
||||
public const int Version = 1;
|
||||
public StartupData() { }
|
||||
public StartupData(Security[] securities, SortingCriteria[] sorting_criteria) {
|
||||
if (securities != null) this.securities = securities.Select(s => s.ToByteArray()).ToArray();
|
||||
public StartupData(SecurityImmutable[] securities, SortingCriteria[] sorting_criteria) {
|
||||
if (securities != null) this.securities = securities.Select(s => ((IImmutableMessage)s).ToByteArray()).ToArray();
|
||||
this.sorting_criteria = sorting_criteria;
|
||||
}
|
||||
[ProtoMember(1)]
|
||||
|
||||
@@ -11,37 +11,18 @@ namespace mbts.spark
|
||||
IEnumerable<OrderBookEntry> get_all_orders();
|
||||
}
|
||||
|
||||
public static class OrderBookExtensions
|
||||
static class OrderBookExtensions
|
||||
{
|
||||
public static IEnumerable<OrderBookEntry> get_all_orders_for_security(this IOrderBook ob, Security security) { return ob.get_all_orders_for_security(security.Id); }
|
||||
public static IEnumerable<OrderBookEntry> get_all_orders_for_security(this IOrderBook ob, IEnumerable<Security> security) { return ob.get_all_orders_for_security(new HashSet<uint>(security.Select(s => s.Id))); }
|
||||
public static IEnumerable<OrderBookEntry> get_all_orders_for_security(this IOrderBook ob, uint security) { return ob.get_all_orders().Where(e => e.sec_key() == security); }
|
||||
public static IEnumerable<OrderBookEntry> get_all_orders_for_security(this IOrderBook ob, IEnumerable<uint> securities) { return ob.get_all_orders_for_security(new HashSet<uint>(securities)); }
|
||||
public static IEnumerable<OrderBookEntry> get_all_orders_for_security(this IOrderBook ob, HashSet<uint> securities) { return ob.get_all_orders().Where(e => securities.Contains(e.sec_key())); }
|
||||
public static IDictionary<uint, IEnumerable<OrderBookEntry>> get_order_sec_map(this IOrderBook ob) { return ob.get_all_orders().Map(e => e.sec_key()); }
|
||||
|
||||
public static IEnumerable<OrderBookEntry> get_active_orders(this IOrderBook ob) { return ob.get_all_orders().Where(e => e.is_active()); }
|
||||
public static IEnumerable<OrderBookEntry> get_active_orders_for_security(this IOrderBook ob, Security security) { return ob.get_active_orders_for_security(security.Id); }
|
||||
public static IEnumerable<OrderBookEntry> get_active_orders_for_security(this IOrderBook ob, IEnumerable<Security> security) { return ob.get_active_orders_for_security(new HashSet<uint>(security.Select(s => s.Id))); }
|
||||
public static IEnumerable<OrderBookEntry> get_active_orders_for_security(this IOrderBook ob, IEnumerable<SecurityImmutable> security) { return ob.get_active_orders_for_security(new HashSet<uint>(security.Select(s => s.Id))); }
|
||||
public static IEnumerable<OrderBookEntry> get_active_orders_for_security(this IOrderBook ob, uint security) { return ob.get_all_orders().Where(e => e.sec_key() == security && e.is_active()); }
|
||||
public static IEnumerable<OrderBookEntry> get_active_orders_for_security(this IOrderBook ob, IEnumerable<uint> securities) { return ob.get_active_orders_for_security(new HashSet<uint>(securities)); }
|
||||
public static IEnumerable<OrderBookEntry> get_active_orders_for_security(this IOrderBook ob, HashSet<uint> securities) { return ob.get_all_orders().Where(e => securities.Contains(e.sec_key()) && e.is_active()); }
|
||||
public static IDictionary<uint, IEnumerable<OrderBookEntry>> get_active_order_sec_map(this IOrderBook ob) { return ob.get_active_orders().Map(e => e.sec_key()); }
|
||||
|
||||
public static IEnumerable<Fill> get_all_fills(this IOrderBook ob) { return ob.get_all_orders().SelectMany(e => e.Fills); }
|
||||
public static IEnumerable<Fill> get_all_fills_for_security(this IOrderBook ob, Security security) { return ob.get_all_fills_for_security(security.Id); }
|
||||
public static IEnumerable<Fill> get_all_fills_for_security(this IOrderBook ob, IEnumerable<Security> security) { return ob.get_all_fills_for_security(new HashSet<uint>(security.Select(s => s.Id))); }
|
||||
public static IEnumerable<Fill> get_all_fills_for_security(this IOrderBook ob, uint security) { return ob.get_all_orders_for_security(security).SelectMany(e => e.Fills); }
|
||||
public static IEnumerable<Fill> get_all_fills_for_security(this IOrderBook ob, IEnumerable<uint> securities) { return ob.get_all_fills_for_security(new HashSet<uint>(securities)); }
|
||||
public static IEnumerable<Fill> get_all_fills_for_security(this IOrderBook ob, HashSet<uint> securities) { return ob.get_all_orders_for_security(securities).SelectMany(e => e.Fills); }
|
||||
public static IDictionary<uint, IEnumerable<Fill>> get_fill_sec_map(this IOrderBook ob) { return ob.get_all_fills().Map(f => f.Order.Security.Id); }
|
||||
|
||||
public static IEnumerable<FillTuple> get_all_fill_tuples(this IOrderBook ob) { return ob.get_all_orders().SelectMany(e => e.Fills.Select(f => new FillTuple(f, e))); }
|
||||
public static IEnumerable<FillTuple> get_all_fill_tuples_for_security(this IOrderBook ob, Security security) { return ob.get_all_fill_tuples_for_security(security.Id); }
|
||||
public static IEnumerable<FillTuple> get_all_fill_tuples_for_security(this IOrderBook ob, IEnumerable<Security> security) { return ob.get_all_fill_tuples_for_security(new HashSet<uint>(security.Select(s => s.Id))); }
|
||||
public static IEnumerable<FillTuple> get_all_fill_tuples_for_security(this IOrderBook ob, uint security) { return ob.get_all_orders_for_security(security).SelectMany(e => e.Fills.Select(f => new FillTuple(f, e))); }
|
||||
public static IEnumerable<FillTuple> get_all_fill_tuples_for_security(this IOrderBook ob, IEnumerable<uint> securities) { return ob.get_all_fill_tuples_for_security(new HashSet<uint>(securities)); }
|
||||
public static IEnumerable<FillTuple> get_all_fill_tuples_for_security(this IOrderBook ob, HashSet<uint> securities) { return ob.get_all_orders_for_security(securities).SelectMany(e => e.Fills.Select(f => new FillTuple(f, e))); }
|
||||
public static IDictionary<uint, IEnumerable<FillTuple>> get_fill_tuple_sec_map(this IOrderBook ob) { return ob.get_all_orders().Map(o => o.sec_key(), o => o.Fills.Select(f => new FillTuple(f, o))); }
|
||||
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ namespace mbts.spark
|
||||
var parts = new List<object>();
|
||||
if (show_side) parts.Add(order.Side);
|
||||
if (show_security) parts.Add(order.Security.ToString(null));
|
||||
if (show_price) parts.Add(order.Security.ContractSpec.format(order.Price));
|
||||
if (show_price) parts.Add(((SecurityImmutable)order.Security).ContractSpec.format(order.Price));
|
||||
if (show_qty) parts.Add("@ {0}".fmt(order.Size));
|
||||
return string.Join(" ", parts);
|
||||
}
|
||||
|
||||
@@ -14,8 +14,8 @@ namespace mbts.spark
|
||||
{
|
||||
internal class OrderParamsVM : DisposableViewModelBase
|
||||
{
|
||||
public OrderParamsVM(Order order, OrdersModel model) : this(Observable.Return(order), model) { }
|
||||
public OrderParamsVM(IObservable<Order> order, OrdersModel model) {
|
||||
public OrderParamsVM(Order order, DemoOrdersModel model) : this(Observable.Return(order), model) { }
|
||||
public OrderParamsVM(IObservable<Order> order, DemoOrdersModel model) {
|
||||
_model = model;
|
||||
_dispose = order.Subscribe(o => {
|
||||
_order = o;
|
||||
@@ -26,7 +26,7 @@ namespace mbts.spark
|
||||
algo_types = new ObservableCollection<OrderTypeVM>(_get_algo_types());
|
||||
}
|
||||
|
||||
private readonly OrdersModel _model;
|
||||
private readonly DemoOrdersModel _model;
|
||||
private Order _order = new Order { LimitOrder = new LimitOrder() };
|
||||
|
||||
private IEnumerable<OrderTypeVM> _get_algo_types() {
|
||||
|
||||
@@ -10,8 +10,8 @@ namespace mbts.spark
|
||||
{
|
||||
internal class OrderTicketVM : DisposableViewModelBase
|
||||
{
|
||||
public OrderTicketVM(OrdersModel model, Order order, IObservable<LadderSettings> settings) : this(model, Observable.Return(order), settings) { }
|
||||
public OrderTicketVM(OrdersModel model, IObservable<Order> order, IObservable<LadderSettings> settings) {
|
||||
public OrderTicketVM(DemoOrdersModel model, Order order, IObservable<LadderSettings> settings, IBus bus) : this(model, Observable.Return(order), settings, bus) { }
|
||||
public OrderTicketVM(DemoOrdersModel model, IObservable<Order> order, IObservable<LadderSettings> settings, IBus bus) {
|
||||
var order_pub = order.Select(o => {
|
||||
_order = o;
|
||||
size_calculator.value = _order.Size;
|
||||
@@ -19,7 +19,7 @@ namespace mbts.spark
|
||||
return _order;
|
||||
}).Publish();
|
||||
order_params = new OrderParamsVM(order_pub, model);
|
||||
bbo = new BBOVM(order.Select(o => o.Security));
|
||||
bbo = new BBOVM(order.Select(o => (SecurityImmutable)o.Security), bus);
|
||||
size_calculator = new CalculatorLogic(0, settings.Select(s => s.calculator_buttons));
|
||||
set_price_command = new DelegateCommand<double>(p => { price = p; RaisePropertyChanged(nameof(price)); });
|
||||
send_order = new DelegateCommand<Side>(side => { _prepare_order(side); model.send_order(_order); });
|
||||
|
||||
@@ -14,13 +14,13 @@ using mbts.utils;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
class OrdersModel
|
||||
class DemoOrdersModel
|
||||
{
|
||||
private readonly IBus _bus;
|
||||
private IObservable<IOrderBook> _on_orderbook;
|
||||
private IDictionary<uint, SyntheticExecutionStrategy> _synth_map = new Dictionary<uint, SyntheticExecutionStrategy> ();
|
||||
|
||||
public OrdersModel(IBus bus)
|
||||
public DemoOrdersModel(IBus bus)
|
||||
{
|
||||
_bus = bus;
|
||||
_on_orderbook = _bus.subscribe<SparkBusData.AllOrderState>(SparkTags.OrderBookTag)
|
||||
|
||||
@@ -12,14 +12,14 @@ namespace mbts.spark
|
||||
{
|
||||
private readonly OrderHub _hub = null;
|
||||
private readonly IBus _bus = null;
|
||||
private IDictionary<uint, SecurityMD> _md_map = new Dictionary<uint, SecurityMD>();
|
||||
private IReadOnlyDictionary<uint, SecurityMD> _md_map = new Dictionary<uint, SecurityMD>();
|
||||
private OrderBook _orderbook = new OrderBook();
|
||||
|
||||
public OrderActivitySimulator(OrderHub order_hub, IBus bus)
|
||||
{
|
||||
_hub = order_hub;
|
||||
_bus = bus;
|
||||
_bus.subscribe<Dictionary<uint, SecurityMD>>(SparkTags.SecuritiesTag).ObserveOnDispatcher().Subscribe(m => _md_map = m);
|
||||
_bus.subscribe(SparkTags.SecuritiesTag).ObserveOnDispatcher().Subscribe(m => _md_map = m);
|
||||
_hub.on_new_order += _hub_on_new_order;
|
||||
_hub.on_cancel += _hub_on_order_cancel;
|
||||
_hub.on_price_change += _hub_on_order_price_change;
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace mbts.spark
|
||||
{
|
||||
private readonly IBus _bus;
|
||||
private readonly Venue _venue;
|
||||
private IDictionary<uint, SecurityMD> _md_map = new ConcurrentDictionary<uint, SecurityMD>();
|
||||
private IReadOnlyDictionary<uint, SecurityMD> _md_map = new ConcurrentDictionary<uint, SecurityMD>();
|
||||
private IDictionary<OrderID, ISingleSecurityExchangeGateway> _worker_map = new ConcurrentDictionary<OrderID, ISingleSecurityExchangeGateway>();
|
||||
|
||||
public SimExchangeGateway(IBus bus, Venue venue)
|
||||
@@ -88,9 +88,9 @@ namespace mbts.spark
|
||||
internal IObservable<Fill> on_fills { get { return _fill_sub; } }
|
||||
|
||||
|
||||
internal IObservable<IDictionary<uint, SecurityMD>> on_md
|
||||
internal IObservable<IReadOnlyDictionary<uint, SecurityMD>> on_md
|
||||
{
|
||||
get { return _bus.subscribe<Dictionary<uint, SecurityMD>>(SparkTags.SecuritiesTag); }
|
||||
get { return _bus.subscribe(SparkTags.SecuritiesTag); }
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
@@ -6,8 +6,8 @@ namespace mbts.spark
|
||||
{
|
||||
internal class SecurityBrowserVM : SecuritySelectorVM
|
||||
{
|
||||
public SecurityBrowserVM(IBus bus) {
|
||||
var orders_model = new OrdersModel(bus);
|
||||
public SecurityBrowserVM(IBus bus, SecuritySource ssrc) :base(ssrc) {
|
||||
var orders_model = new DemoOrdersModel(bus);
|
||||
_actions = MenuItemVM.CreateMenu(selected_securities, new CancelOrdersMenuItem(orders_model), new SyntheticCreateMenuItem(bus), new SyntheticStrategyMenuItem(bus), new OrderTicketMenuItem(orders_model));
|
||||
_windows = MenuItemVM.CreateMenu(selected_securities, new LadderMenuItem(bus), new MarketViewMenuItem(bus), new SpreadMatrixMenuItem(bus), new TimeAndSalesMenuItem(bus));
|
||||
}
|
||||
|
||||
@@ -8,8 +8,8 @@ namespace mbts.spark
|
||||
{
|
||||
internal class SecuritySelectorDialogVM : SecuritySelectorVM
|
||||
{
|
||||
public SecuritySelectorDialogVM(string title, IReadOnlyCollection<Security> preselected_securities, Action<IEnumerable<Security>> commit) : this (title, preselected_securities, commit, SecuritySource.GetObservable()) { }
|
||||
public SecuritySelectorDialogVM(string title, IReadOnlyCollection<Security> preselected_securities, Action<IEnumerable<Security>> commit, IObservable<Security[]> securities_stream) : base(preselected_securities, securities_stream) {
|
||||
public SecuritySelectorDialogVM(string title, IReadOnlyCollection<SecurityImmutable> preselected_securities, Action<IEnumerable<SecurityImmutable>> commit, SecuritySource ssrc) : this (title, preselected_securities, commit, ssrc.GetObservable()) { }
|
||||
public SecuritySelectorDialogVM(string title, IReadOnlyCollection<SecurityImmutable> preselected_securities, Action<IEnumerable<SecurityImmutable>> commit, IObservable<SecurityImmutable[]> securities_stream) : base(preselected_securities, securities_stream) {
|
||||
this.title = title;
|
||||
this.commit = new DelegateCommand(() => commit(selected_securities));
|
||||
}
|
||||
|
||||
@@ -7,17 +7,17 @@ using System.Threading;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
public class SecuritySelectorVM : IDisposable
|
||||
class SecuritySelectorVM : IDisposable
|
||||
{
|
||||
public SecuritySelectorVM() : this(new Security[0]) { }
|
||||
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, SynchronizationContext.Current, TimeSpan.FromSeconds(1), SecurityHelper.IDEqualityComparer);
|
||||
public SecuritySelectorVM(SecuritySource src) : this(new SecurityImmutable[0], src) { }
|
||||
public SecuritySelectorVM(IReadOnlyCollection<SecurityImmutable> preselected_securities, SecuritySource src) : this(preselected_securities, src.GetObservable()) { }
|
||||
public SecuritySelectorVM(IReadOnlyCollection<SecurityImmutable> preselected_securities, IObservable<SecurityImmutable[]> securities_stream) {
|
||||
selected_securities = new ObservableCollection<SecurityImmutable>(preselected_securities);
|
||||
securities = new RXObservableCollection<SecurityImmutable>(securities_stream, SynchronizationContext.Current, TimeSpan.FromSeconds(1));
|
||||
}
|
||||
|
||||
public RXObservableCollection<Security> securities { get; }
|
||||
public ObservableCollection<Security> selected_securities { get; }
|
||||
public RXObservableCollection<SecurityImmutable> securities { get; }
|
||||
public ObservableCollection<SecurityImmutable> selected_securities { get; }
|
||||
|
||||
protected virtual void OnDispose() { }
|
||||
public void Dispose() { securities.Dispose(); }
|
||||
|
||||
@@ -9,28 +9,17 @@ using System.Reactive.Linq;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
internal static class SecuritySource
|
||||
[Export]
|
||||
internal class SecuritySource
|
||||
{
|
||||
public static IObservable<Security[]> GetObservable() {
|
||||
return _instance.publisher.AsObservable();
|
||||
[ImportingConstructor]
|
||||
public SecuritySource(IBus bus) {
|
||||
securities =
|
||||
bus.subscribe(SparkTags.SecuritiesTag).Select(dict => dict.Values.Select(s => s.security).ToArray()).Publish().RefCount();
|
||||
}
|
||||
|
||||
private static InternalSource _instance;
|
||||
|
||||
[Export(typeof(IInitializable))]
|
||||
private class InternalSource : IInitializable
|
||||
{
|
||||
[ImportingConstructor]
|
||||
public InternalSource(IBus bus) {
|
||||
publisher = new StatePublisher<Security[]>(bus.subscribe<Dictionary<uint, SecurityMD>>(SparkTags.SecuritiesTag)
|
||||
.Select(m => m.Values.Select(s => s.security).Ordered(SecurityDataHelper.Comparer.Instance).ToArray()));
|
||||
_instance = this;
|
||||
}
|
||||
|
||||
internal readonly StatePublisher<Security[]> publisher;
|
||||
|
||||
public int priority => int.MaxValue;
|
||||
public void initialize() { }
|
||||
readonly IObservable<SecurityImmutable[]> securities;
|
||||
public IObservable<SecurityImmutable[]> GetObservable() {
|
||||
return securities;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,10 +24,10 @@ namespace mbts.spark
|
||||
public const int VERSION = 1;
|
||||
public const string SAVE_NAME = "Fills";
|
||||
|
||||
public FillsVM(IBus bus, OrdersModel model, IReadOnlyCollection<Security> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria = null) {
|
||||
public FillsVM(IBus bus, DemoOrdersModel model, SecuritySource ssrc, IReadOnlyCollection<SecurityImmutable> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria = null) {
|
||||
_bus = bus;
|
||||
_model = model;
|
||||
_securities = new HashSet<Security>(securities ?? Enumerable.Empty<Security>());
|
||||
_securities = new HashSet<SecurityImmutable>(securities ?? Enumerable.Empty<SecurityImmutable>());
|
||||
_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()));
|
||||
@@ -39,17 +39,17 @@ namespace mbts.spark
|
||||
modify_security_selection = new DialogCommand(() => new SecuritySelectorDialog {
|
||||
DataContext = new SecuritySelectorDialogVM("Fills", _securities.ToArray(),
|
||||
secs => {
|
||||
_securities = new HashSet<Security>(secs);
|
||||
_securities = new HashSet<SecurityImmutable>(secs);
|
||||
_update();
|
||||
})
|
||||
}, ssrc)
|
||||
}, () => true, true, -12, -30);
|
||||
}
|
||||
|
||||
private readonly IBus _bus;
|
||||
private readonly OrdersModel _model;
|
||||
private readonly DemoOrdersModel _model;
|
||||
private readonly ObservableCollection<FillTuple> _fills = new ObservableCollection<FillTuple>();
|
||||
private readonly ObservableAutoWrapper<Row, FillTuple> _rows;
|
||||
private HashSet<Security> _securities;
|
||||
private HashSet<SecurityImmutable> _securities;
|
||||
private IOrderBook _order_book = new OrderBook();
|
||||
private List<TimeSpan> _update_log = new List<TimeSpan>();
|
||||
private ContextMenuVM _context_menu;
|
||||
@@ -64,7 +64,7 @@ namespace mbts.spark
|
||||
}
|
||||
private IEnumerable<MenuItemVM> _context_menu_item_factory() {
|
||||
var selected_rows = _rows.Where(r => r.is_selected);
|
||||
var securities = new HashSet<Security>(selected_rows.Select(r => r.security.value));
|
||||
var securities = new HashSet<SecurityImmutable>(selected_rows.Select(r => r.security.value));
|
||||
yield return MenuItemVM.Create(new LadderMenuItem(_bus), securities);
|
||||
yield return MenuItemVM.Create(new OrderTicketMenuItem(_model), securities);
|
||||
yield return MenuItemVM.Create(new MarketViewMenuItem(_bus), securities);
|
||||
@@ -88,16 +88,16 @@ namespace mbts.spark
|
||||
}
|
||||
|
||||
private class Row {
|
||||
public Row(FillTuple fill, OrdersModel model) {
|
||||
public Row(FillTuple fill, DemoOrdersModel model) {
|
||||
_fill = fill.Fill;
|
||||
_entry = fill.OrderBookEntry;
|
||||
_model = model;
|
||||
security = new SelectableViewModelBase<Security>(_fill.Order.Security, SecurityDataHelper.Comparer.Instance);
|
||||
security = new SelectableViewModelBase<SecurityImmutable>(_fill.Order.Security, SecurityDataHelper.Comparer.Instance);
|
||||
uint aggr_fills = 0;
|
||||
foreach (var f in _entry.Fills) if (f.Timestamp <= _fill.Timestamp) aggr_fills += f.Size;
|
||||
order_percentage = (double)aggr_fills / (double)_fill.Order.Size;
|
||||
}
|
||||
private readonly OrdersModel _model;
|
||||
private readonly DemoOrdersModel _model;
|
||||
private readonly Fill _fill;
|
||||
private readonly OrderBookEntry _entry;
|
||||
public OrderBookEntry entry => _entry;
|
||||
@@ -109,7 +109,7 @@ namespace mbts.spark
|
||||
public string account => _fill.Order.Account;
|
||||
public string user => _fill.Order.User;
|
||||
public Venue exchange => _fill.Order.Security.Exchange;
|
||||
public SelectableViewModelBase<Security> security { get; }
|
||||
public SelectableViewModelBase<SecurityImmutable> security { get; }
|
||||
public Side side => _fill.Order.Side;
|
||||
public double price => _fill.Price;
|
||||
public uint size => _fill.Size;
|
||||
@@ -127,8 +127,8 @@ namespace mbts.spark
|
||||
public class StartupData {
|
||||
public const int Version = 1;
|
||||
public StartupData() { }
|
||||
public StartupData(IReadOnlyCollection<Security> securities, SortingCriteria[] sorting_criteria) {
|
||||
if (securities != null) this.securities = securities.Select(s => s.ToByteArray()).ToArray();
|
||||
public StartupData(IReadOnlyCollection<SecurityImmutable> securities, SortingCriteria[] sorting_criteria) {
|
||||
if (securities != null) this.securities = securities.Select(s => ((IImmutableMessage)s).ToByteArray()).ToArray();
|
||||
this.sorting_criteria = sorting_criteria;
|
||||
}
|
||||
[ProtoMember(1)]
|
||||
|
||||
@@ -16,17 +16,17 @@ namespace mbts.spark.menu_items
|
||||
internal class LaunchMenuItemVM : MenuItemVM, IHaveTemplate, IDisposable
|
||||
{
|
||||
#region Static Factory
|
||||
public static IList<LaunchMenuItemVM> CreateMenu(params IMenuItem[] models) {
|
||||
return models.Select(Create).ToList();
|
||||
public static IList<LaunchMenuItemVM> CreateMenu(SecuritySource ssrc, params IMenuItem[] models) {
|
||||
return models.Select(i => Create(i, ssrc)).ToList();
|
||||
}
|
||||
|
||||
public static LaunchMenuItemVM Create(IMenuItem model) {
|
||||
public static LaunchMenuItemVM Create(IMenuItem model, SecuritySource ssrc) {
|
||||
var act_mi = model as IMenuActionItem;
|
||||
if (act_mi != null) return Create(act_mi);
|
||||
var secs_mi = model as IMenuSecuritiesActionItem;
|
||||
if (secs_mi != null) return Create(secs_mi);
|
||||
if (secs_mi != null) return Create(secs_mi, ssrc);
|
||||
var grp_mi = model as IMenuGroupItem;
|
||||
if (grp_mi != null) return Create(grp_mi);
|
||||
if (grp_mi != null) return Create(grp_mi, ssrc);
|
||||
throw new NotImplementedException("LaunchMenuVM cannot create vm for {0} ({1}).".fmt(model?.display_name ?? "unnamed", model?.GetType().ToString() ?? "null"));
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ namespace mbts.spark.menu_items
|
||||
return new LaunchMenuItemVM(model.display_name, model.sectional_id, model.icon, command, Template.Action, dispose:model as IDisposable);
|
||||
}
|
||||
|
||||
public static LaunchMenuItemVM Create(IMenuSecuritiesActionItem model) {
|
||||
public static LaunchMenuItemVM Create(IMenuSecuritiesActionItem model, SecuritySource ssrc) {
|
||||
SecurityLaunchMenuItem rv = null;
|
||||
IDisposable sub = null;
|
||||
IRaiseCanExecuteChangedCommand command = null;
|
||||
@@ -45,14 +45,14 @@ namespace mbts.spark.menu_items
|
||||
rv.selected_securities.Clear();
|
||||
sub = rv.selected_securities.Subscribe((s, e) => command.RaiseCanExecuteChanged());
|
||||
}, () => model.can_execute(rv.selected_securities));
|
||||
rv = new SecurityLaunchMenuItem(model.display_name, model.sectional_id, model.icon, command, Template.Securities, Disposable.Create(() => { (model as IDisposable)?.Dispose(); sub?.Dispose(); }));
|
||||
rv = new SecurityLaunchMenuItem(model.display_name, model.sectional_id, model.icon, command, Template.Securities, Disposable.Create(() => { (model as IDisposable)?.Dispose(); sub?.Dispose(); }), ssrc);
|
||||
sub = rv.selected_securities.Subscribe((s, e) => command.RaiseCanExecuteChanged());
|
||||
model.can_execute_changed += () => command.RaiseCanExecuteChanged();
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static LaunchMenuItemVM Create(IMenuGroupItem model) {
|
||||
return new LaunchMenuItemVM(model.display_name, model.sectional_id, model.icon, template_key:Template.Group, items:CreateMenu(model.items.ToArray()));
|
||||
public static LaunchMenuItemVM Create(IMenuGroupItem model, SecuritySource ssrc) {
|
||||
return new LaunchMenuItemVM(model.display_name, model.sectional_id, model.icon, template_key:Template.Group, items:CreateMenu(ssrc, model.items.ToArray()));
|
||||
}
|
||||
#endregion
|
||||
|
||||
@@ -66,11 +66,14 @@ namespace mbts.spark.menu_items
|
||||
|
||||
internal class SecurityLaunchMenuItem : LaunchMenuItemVM
|
||||
{
|
||||
internal SecurityLaunchMenuItem(string display_name, string sectional_id, ImageSource icon, ICommand launch_command, Template template_key, IDisposable dispose)
|
||||
: base(display_name, sectional_id, icon, template_key:template_key, dispose:dispose) { this.launch_command = launch_command; }
|
||||
private RXObservableCollection<Security> _securities = new RXObservableCollection<Security>(SecuritySource.GetObservable());
|
||||
public RXObservableCollection<Security> securities => _securities;
|
||||
public ObservableCollection<Security> selected_securities { get; } = new ObservableCollection<Security>();
|
||||
internal SecurityLaunchMenuItem(string display_name, string sectional_id, ImageSource icon, ICommand launch_command, Template template_key, IDisposable dispose, SecuritySource src)
|
||||
: base(display_name, sectional_id, icon, template_key:template_key, dispose:dispose) {
|
||||
this.launch_command = launch_command;
|
||||
_securities = new RXObservableCollection<SecurityImmutable>(src.GetObservable());
|
||||
}
|
||||
private RXObservableCollection<SecurityImmutable> _securities;
|
||||
public RXObservableCollection<SecurityImmutable> securities => _securities;
|
||||
public ObservableCollection<SecurityImmutable> selected_securities { get; } = new ObservableCollection<SecurityImmutable>();
|
||||
public ICommand launch_command { get; }
|
||||
protected override void Dispose(bool disposing) { Disposable.dispose(ref _securities); }
|
||||
}
|
||||
|
||||
@@ -7,8 +7,8 @@ namespace mbts.spark
|
||||
{
|
||||
internal class LaunchMenuVM : ViewModelBase
|
||||
{
|
||||
public LaunchMenuVM(params IMenuItem[] models) {
|
||||
var vms = LaunchMenuItemVM.CreateMenu(models);
|
||||
public LaunchMenuVM(SecuritySource ssrc, params IMenuItem[] models) {
|
||||
var vms = LaunchMenuItemVM.CreateMenu(ssrc, models);
|
||||
items_view = CollectionViewSource.GetDefaultView(vms);
|
||||
items_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(IMenuItem.sectional_id)));
|
||||
}
|
||||
|
||||
@@ -23,11 +23,13 @@ namespace mbts.spark
|
||||
[Export(typeof(IShellModule))]
|
||||
internal class MarketModule : IShellModule {
|
||||
[ImportingConstructor]
|
||||
public MarketModule(IBus bus, IWindowManager wm) {
|
||||
public MarketModule(IBus bus, SecuritySource ssrc, IWindowManager wm, [Import("username")]string user_name) {
|
||||
_bus = bus;
|
||||
_ssrc = ssrc;
|
||||
_wm = wm;
|
||||
_user_name = user_name;
|
||||
_dispose = Disposable.Create(
|
||||
_bus.subscribe<Dictionary<SecurityKey, SecurityMD>>(SecuritiesTag).ObserveOnDispatcher().Subscribe(s => _securities = s),
|
||||
_bus.subscribe(SecuritiesTag).ObserveOnDispatcher().Subscribe(s => _securities = s),
|
||||
_bus.subscribe<SyntheticSecuritiesMessage>(SyntheticSecuritiesTag).ObserveOnDispatcher().Subscribe(ssm => _synthetic_strategy_map = ssm.data),
|
||||
_bus.subscribe<ShowMarketViewMessage>(ShowMarketViewTag).ObserveOnDispatcher().Subscribe(show_market_view),
|
||||
_bus.subscribe<ShowSpreadMatrixMessage>(ShowSpreadMatrixTag).ObserveOnDispatcher().Subscribe(show_spread_matrix),
|
||||
@@ -41,9 +43,11 @@ namespace mbts.spark
|
||||
);
|
||||
}
|
||||
private readonly IBus _bus;
|
||||
private readonly SecuritySource _ssrc;
|
||||
private readonly IWindowManager _wm;
|
||||
private readonly IDisposable _dispose;
|
||||
private IDictionary<SecurityKey, SecurityMD> _securities = new Dictionary<SecurityKey, SecurityMD>();
|
||||
private readonly string _user_name;
|
||||
private IReadOnlyDictionary<SecurityKey, SecurityMD> _securities = new Dictionary<SecurityKey, SecurityMD>();
|
||||
private IDictionary<SecurityKey, SyntheticExecutionStrategy> _synthetic_strategy_map = new Dictionary<SecurityKey, SyntheticExecutionStrategy>();
|
||||
|
||||
public int priority => 2;
|
||||
@@ -51,10 +55,11 @@ namespace mbts.spark
|
||||
public ImageSource icon => Icons.Date;
|
||||
public IShellWindow launch_ui => new LaunchMenu {
|
||||
DataContext = new LaunchMenuVM(
|
||||
_ssrc,
|
||||
new MarketViewMenuItem(_bus),
|
||||
new SpreadMatrixMenuItem(_bus),
|
||||
new LadderMenuItem(_bus),
|
||||
new OrderTicketMenuItem(new OrdersModel(_bus)),
|
||||
new OrderTicketMenuItem(new DemoOrdersModel(_bus)),
|
||||
MenuItemFactory.Create("Security Browser...", "sb", Icons.Coins, execute: show_security_browser))
|
||||
};
|
||||
public void load_state(Stream state = null) { }
|
||||
@@ -68,7 +73,7 @@ namespace mbts.spark
|
||||
if (_securities != null && _securities.TryGetValue((uint)header.version, out SecurityMD md)) return create_ladder_window(md);
|
||||
else break;
|
||||
case MarketViewVM.SAVE_NAME:
|
||||
if (try_deserialize(load_stream, out MarketViewVM.StartupData data)) return create_market_view(data.securities.Select(deserialize<Security>).ToList(), data.sorting_criteria);
|
||||
if (try_deserialize(load_stream, out MarketViewVM.StartupData data)) return create_market_view(data.securities.Select(x => (SecurityImmutable)deserialize<Security>(x)).ToList(), data.sorting_criteria);
|
||||
else break;
|
||||
}
|
||||
}
|
||||
@@ -78,13 +83,13 @@ namespace mbts.spark
|
||||
public void Dispose() { _dispose.Dispose(); }
|
||||
|
||||
#region SecurityBrowser
|
||||
private void show_security_browser() { new SecurityBrowser { DataContext = new SecurityBrowserVM(_bus) }.Show(-200, -300, true); }
|
||||
private void show_security_browser() { new SecurityBrowser { DataContext = new SecurityBrowserVM(_bus, _ssrc) }.Show(-200, -300, true); }
|
||||
#endregion
|
||||
|
||||
#region MarketView
|
||||
private void show_market_view(ShowMarketViewMessage msg) { _wm.Windows.Add(create_market_view(msg.data, null)); }
|
||||
private IShellWindow create_market_view(IReadOnlyCollection<Security> securities, IReadOnlyCollection<SortingCriteria> sorting) {
|
||||
var vm = new MarketViewVM(_bus, securities, sorting);
|
||||
private IShellWindow create_market_view(IReadOnlyCollection<SecurityImmutable> securities, IReadOnlyCollection<SortingCriteria> sorting) {
|
||||
var vm = new MarketViewVM(_bus, _ssrc, securities, sorting);
|
||||
var view = new MarketViewView { DataContext = vm };
|
||||
const double two_thirds = 2.0 / 3.0;
|
||||
const double title_panel_height = 32.0, col_header_height = 26 + two_thirds + 10.0;
|
||||
@@ -108,15 +113,15 @@ namespace mbts.spark
|
||||
private void show_order_ticket(IReadOnlyCollection<Order> orders, bool is_modify) {
|
||||
foreach (var o in orders) {
|
||||
if (_securities.TryGetValue(o.Security.Id, out SecurityMD smd)) {
|
||||
if (string.IsNullOrEmpty(o.User)) o.User = ImportedResources.UserName;
|
||||
var vm = new OrderTicketVM(new OrdersModel(_bus), o, _get_ladder_settings());
|
||||
if (string.IsNullOrEmpty(o.User)) o.User = _user_name;
|
||||
var vm = new OrderTicketVM(new DemoOrdersModel(_bus), o, _get_ladder_settings(), _bus);
|
||||
(is_modify ? (Window)new OrderModificationDialog { DataContext = vm } : new OrderTicket { DataContext = vm }).Show(-200, -160, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
private void show_linked_order_ticket(ShowLinkedOrderTicketMessage msg) {
|
||||
new OrderTicket {
|
||||
DataContext = new OrderTicketVM(new OrdersModel(_bus), msg.data, _get_ladder_settings())
|
||||
DataContext = new OrderTicketVM(new DemoOrdersModel(_bus), msg.data, _get_ladder_settings(), _bus)
|
||||
}.Show(-200, -160, true);
|
||||
}
|
||||
#endregion
|
||||
@@ -126,7 +131,7 @@ namespace mbts.spark
|
||||
private void show_ladder(SecurityMD sec) { _wm.Windows.Add(create_ladder_window(sec)); }
|
||||
private async void show_linked_ladder(ShowLinkedLadderMessage msg) { _wm.Windows.Add(await create_ladder_window(msg.data)); }
|
||||
private IShellWindow create_ladder_window(SecurityMD md) {
|
||||
var model = new LadderModel(md, new OrdersModel(_bus));
|
||||
var model = new LadderModel(md, new DemoOrdersModel(_bus));
|
||||
var vm = new LadderVM(model, _get_ladder_settings());
|
||||
var view = new LadderView { DataContext = vm };
|
||||
return ShellWindow.create(this, md.security.ToString(null), view, vm, vm.save_state, Icons.Depth);
|
||||
@@ -134,7 +139,7 @@ namespace mbts.spark
|
||||
private IObservable<LadderSettings> _get_ladder_settings() { return Observable.Return(new LadderSettings()); }
|
||||
private async Task<IShellWindow> create_ladder_window(IObservable<SecurityMD> security_md) {
|
||||
var first_smd = await security_md.FirstAsync();
|
||||
OrdersModel om = new OrdersModel(_bus);
|
||||
DemoOrdersModel om = new DemoOrdersModel(_bus);
|
||||
LadderVM vm = new LadderVM(new LadderModel(first_smd, om), _get_ladder_settings());
|
||||
LadderView view = new LadderView { DataContext = vm };
|
||||
IDisposable sub = null;
|
||||
@@ -170,7 +175,7 @@ namespace mbts.spark
|
||||
string warn_msg = $"Did not find execution strategy for {msg.data}";
|
||||
Logger.warn(bts.log.Subsystem.Ui, warn_msg);
|
||||
show_synthetic_editor_warning(warn_msg);
|
||||
} else show_synthetic_editor(msg.data, ses.ExecutionStrategy);
|
||||
} else show_synthetic_editor(msg.data.CloneToMutable(), ses.ExecutionStrategy);
|
||||
}
|
||||
private void show_synthetic_editor_warning(string warn_msg) {
|
||||
BTSMessageBox.Show(warn_msg, "Synthetic Strategy", MessageBoxButton.OK, MessageBoxImage.Exclamation, true, false, true);
|
||||
|
||||
@@ -7,21 +7,21 @@ namespace mbts.spark.menu_items
|
||||
{
|
||||
internal class CancelOrderRootMenuItem : OrderActionMenuItemRoot
|
||||
{
|
||||
public CancelOrderRootMenuItem(OrdersModel model, IReadOnlyCollection<Order> orders) : base(orders) {
|
||||
public CancelOrderRootMenuItem(DemoOrdersModel model, IReadOnlyCollection<Order> orders) : base(orders) {
|
||||
_model = model;
|
||||
}
|
||||
private OrdersModel _model;
|
||||
private DemoOrdersModel _model;
|
||||
public override string display_name => "Cancel Order";
|
||||
public override ImageSource icon => Icons.CancelOrders;
|
||||
protected override OrderMenuActionItem create_item(Order order) { return new CancelOrderMenuItem(_model, order); }
|
||||
|
||||
internal class CancelOrderMenuItem : OrderMenuActionItem {
|
||||
public CancelOrderMenuItem(OrdersModel model, Order order) : base(order, model.get_metadata(order)) {
|
||||
public CancelOrderMenuItem(DemoOrdersModel model, Order order) : base(order, model.get_metadata(order)) {
|
||||
_model = model;
|
||||
_order = order;
|
||||
}
|
||||
|
||||
private readonly OrdersModel _model;
|
||||
private readonly DemoOrdersModel _model;
|
||||
private readonly Order _order;
|
||||
public override void execute() { _model.cancel_order(_order.Id); }
|
||||
}
|
||||
|
||||
@@ -10,23 +10,23 @@ namespace mbts.spark.menu_items
|
||||
{
|
||||
internal class CancelOrdersMenuItem : IMenuSecuritiesActionItem
|
||||
{
|
||||
public CancelOrdersMenuItem(OrdersModel model) {
|
||||
public CancelOrdersMenuItem(DemoOrdersModel model) {
|
||||
_model = model;
|
||||
_sub = _model.on_orderbook().ObserveOnDispatcher().Subscribe(ob => _orderbook = ob);
|
||||
}
|
||||
private readonly IDisposable _sub;
|
||||
private readonly OrdersModel _model;
|
||||
private readonly DemoOrdersModel _model;
|
||||
private IOrderBook _orderbook = new OrderBook();
|
||||
|
||||
public virtual string display_name => "Cancel All Orders";
|
||||
public int priority => 0;
|
||||
public ImageSource icon => Icons.CancelOrders;
|
||||
public string sectional_id => MenuItemSections.OrderOp;
|
||||
public void execute(IReadOnlyCollection<Security> securities) {
|
||||
public void execute(IReadOnlyCollection<SecurityImmutable> securities) {
|
||||
var orders = _orderbook.get_all_orders().Select(e => e.order()).Where(o => securities.Contains(o.Security) && filter(o)).Select(o => o.Id).ToList();
|
||||
_model.cancel_order(orders);
|
||||
}
|
||||
public bool can_execute(IReadOnlyCollection<Security> securities) { return securities.Any(); }
|
||||
public bool can_execute(IReadOnlyCollection<SecurityImmutable> securities) { return securities.Any(); }
|
||||
public void raise_display_name_changed() { display_name_changed?.Invoke(); }
|
||||
public void raise_can_execute_changed() { can_execute_changed?.Invoke(); }
|
||||
public event Action display_name_changed;
|
||||
@@ -36,13 +36,13 @@ namespace mbts.spark.menu_items
|
||||
}
|
||||
|
||||
internal class CancelBuyOrdersMenuItem : CancelOrdersMenuItem {
|
||||
public CancelBuyOrdersMenuItem(OrdersModel model) : base(model) { }
|
||||
public CancelBuyOrdersMenuItem(DemoOrdersModel model) : base(model) { }
|
||||
public override string display_name => "Cancel Buy Orders";
|
||||
protected override bool filter(Order order) { return order.Side == Side.Buy; }
|
||||
}
|
||||
|
||||
internal class CancelSellOrdersMenuItem : CancelOrdersMenuItem {
|
||||
public CancelSellOrdersMenuItem(OrdersModel model) : base(model) { }
|
||||
public CancelSellOrdersMenuItem(DemoOrdersModel model) : base(model) { }
|
||||
protected override bool filter(Order order) { return order.Side == Side.Sell; }
|
||||
public override string display_name => "Cancel Sell Orders";
|
||||
}
|
||||
|
||||
@@ -25,10 +25,10 @@ namespace mbts.spark.menu_items
|
||||
bool can_execute();
|
||||
}
|
||||
|
||||
public interface IMenuSecuritiesActionItem : IMenuItem, ICanExecuteChanged
|
||||
interface IMenuSecuritiesActionItem : IMenuItem, ICanExecuteChanged
|
||||
{
|
||||
void execute(IReadOnlyCollection<Security> securities);
|
||||
bool can_execute(IReadOnlyCollection<Security> securities);
|
||||
void execute(IReadOnlyCollection<SecurityImmutable> securities);
|
||||
bool can_execute(IReadOnlyCollection<SecurityImmutable> securities);
|
||||
}
|
||||
|
||||
public interface IMenuGroupItem : IMenuItem
|
||||
|
||||
@@ -20,8 +20,8 @@ namespace mbts.spark.menu_items
|
||||
public int priority => 2;
|
||||
public ImageSource icon => Icons.Depth;
|
||||
public string sectional_id => MenuItemSections.OrderActiveWindow;
|
||||
public void execute(IReadOnlyCollection<Security> securities) { _bus.post(ShowLadderTag, new ShowLadderMessage(securities)); }
|
||||
public bool can_execute(IReadOnlyCollection<Security> securities) { return securities.Count > 0; }
|
||||
public void execute(IReadOnlyCollection<SecurityImmutable> securities) { _bus.post(ShowLadderTag, new ShowLadderMessage(securities)); }
|
||||
public bool can_execute(IReadOnlyCollection<SecurityImmutable> securities) { return securities.Count > 0; }
|
||||
public void raise_display_name_changed() { display_name_changed?.Invoke(); }
|
||||
public void raise_can_execute_changed() { can_execute_changed?.Invoke(); }
|
||||
public event Action display_name_changed;
|
||||
|
||||
@@ -19,8 +19,8 @@ namespace mbts.spark.menu_items
|
||||
public int priority => 0;
|
||||
public ImageSource icon => Icons.Sheets;
|
||||
public string sectional_id => MenuItemSections.SecurityWindow;
|
||||
public void execute(IReadOnlyCollection<Security> securities) { _bus.post(SparkTags.ShowMarketViewTag, new SparkBusData.ShowMarketViewMessage(securities.ToList())); }
|
||||
public bool can_execute(IReadOnlyCollection<Security> securities) { return securities.Any(); }
|
||||
public void execute(IReadOnlyCollection<SecurityImmutable> securities) { _bus.post(SparkTags.ShowMarketViewTag, new SparkBusData.ShowMarketViewMessage(securities.ToList())); }
|
||||
public bool can_execute(IReadOnlyCollection<SecurityImmutable> securities) { return securities.Any(); }
|
||||
public void raise_display_name_changed() { display_name_changed?.Invoke(); }
|
||||
public void raise_can_execute_changed() { can_execute_changed?.Invoke(); }
|
||||
public event Action display_name_changed;
|
||||
|
||||
@@ -15,18 +15,18 @@ using System.Windows.Media;
|
||||
|
||||
namespace mbts.spark.menu_items
|
||||
{
|
||||
public class MenuItemVM : DisposableViewModelBase
|
||||
class MenuItemVM : DisposableViewModelBase
|
||||
{
|
||||
#region Static Factory
|
||||
public static IList<MenuItemVM> CreateMenu(ObservableCollection<Security> selected_securities, params IMenuItem[] menu_items) {
|
||||
public static IList<MenuItemVM> CreateMenu(ObservableCollection<SecurityImmutable> selected_securities, params IMenuItem[] menu_items) {
|
||||
return menu_items.Select(m => Create(m, selected_securities)).ToList();
|
||||
}
|
||||
|
||||
public static IList<MenuItemVM> CreateMenu(IReadOnlyCollection<Security> selected_securities, params IMenuItem[] menu_items) {
|
||||
public static IList<MenuItemVM> CreateMenu(IReadOnlyCollection<SecurityImmutable> selected_securities, params IMenuItem[] menu_items) {
|
||||
return menu_items.Select(m => Create(m, selected_securities)).ToList();
|
||||
}
|
||||
|
||||
public static MenuItemVM Create(IMenuItem model, ObservableCollection<Security> selected_securities) {
|
||||
public static MenuItemVM Create(IMenuItem model, ObservableCollection<SecurityImmutable> selected_securities) {
|
||||
var act_mi = model as IMenuActionItem;
|
||||
if (act_mi != null) return Create(act_mi);
|
||||
var secs_mi = model as IMenuSecuritiesActionItem;
|
||||
@@ -36,7 +36,7 @@ namespace mbts.spark.menu_items
|
||||
throw new NotImplementedException("LaunchMenuVM cannot create vm for {0} ({1}).".fmt(model?.display_name ?? "unnamed", model?.GetType().ToString() ?? "null"));
|
||||
}
|
||||
|
||||
public static MenuItemVM Create(IMenuItem model, IReadOnlyCollection<Security> selected_securities) {
|
||||
public static MenuItemVM Create(IMenuItem model, IReadOnlyCollection<SecurityImmutable> selected_securities) {
|
||||
var act_mi = model as IMenuActionItem;
|
||||
if (act_mi != null) return Create(act_mi);
|
||||
var secs_mi = model as IMenuSecuritiesActionItem;
|
||||
@@ -50,21 +50,21 @@ namespace mbts.spark.menu_items
|
||||
return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, _hook_command(model, model.execute, model.can_execute), dispose: model as IDisposable);
|
||||
}
|
||||
|
||||
public static MenuItemVM Create(IMenuSecuritiesActionItem model, IReadOnlyCollection<Security> selected_securities) {
|
||||
public static MenuItemVM Create(IMenuSecuritiesActionItem model, IReadOnlyCollection<SecurityImmutable> selected_securities) {
|
||||
return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, _hook_command(model, () => model.execute(selected_securities), () => model.can_execute(selected_securities)));
|
||||
}
|
||||
|
||||
public static MenuItemVM Create(IMenuSecuritiesActionItem model, ObservableCollection<Security> selected_securities) {
|
||||
public static MenuItemVM Create(IMenuSecuritiesActionItem model, ObservableCollection<SecurityImmutable> selected_securities) {
|
||||
var command = _hook_command(model, () => model.execute(selected_securities), () => model.can_execute(selected_securities));
|
||||
IDisposable sub = selected_securities.Subscribe((s, e) => command.RaiseCanExecuteChanged());
|
||||
return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, command, dispose: Disposable.Create(() => { (model as IDisposable)?.Dispose(); sub?.Dispose(); }));
|
||||
}
|
||||
|
||||
public static MenuItemVM Create(IMenuGroupItem model, ObservableCollection<Security> selected_securities) {
|
||||
public static MenuItemVM Create(IMenuGroupItem model, ObservableCollection<SecurityImmutable> selected_securities) {
|
||||
return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, new DelegateCommand(() => { }, () => model.items.Any()), CreateMenu(selected_securities, model.items.ToArray()));
|
||||
}
|
||||
|
||||
public static MenuItemVM Create(IMenuGroupItem model, IReadOnlyCollection<Security> selected_securities) {
|
||||
public static MenuItemVM Create(IMenuGroupItem model, IReadOnlyCollection<SecurityImmutable> selected_securities) {
|
||||
return new MenuItemVM(_observe_display_name(model), model.sectional_id, model.icon, new DelegateCommand(() => { }, () => model.items.Any()), CreateMenu(selected_securities, model.items.ToArray()));
|
||||
}
|
||||
|
||||
|
||||
@@ -11,21 +11,21 @@ namespace mbts.spark.menu_items
|
||||
{
|
||||
internal class ModifyOrderRootMenuItem : OrderActionMenuItemRoot
|
||||
{
|
||||
public ModifyOrderRootMenuItem(OrdersModel model, IReadOnlyCollection<Order> orders) : base(orders) {
|
||||
public ModifyOrderRootMenuItem(DemoOrdersModel model, IReadOnlyCollection<Order> orders) : base(orders) {
|
||||
_model = model;
|
||||
}
|
||||
private OrdersModel _model;
|
||||
private DemoOrdersModel _model;
|
||||
public override string display_name => "Modify Order";
|
||||
public override ImageSource icon => Icons.Import;
|
||||
protected override OrderMenuActionItem create_item(Order order) { return new ModifyOrderMenuItem(_model, order); }
|
||||
|
||||
internal class ModifyOrderMenuItem : OrderMenuActionItem {
|
||||
public ModifyOrderMenuItem(OrdersModel model, Order order) : base(order, model.get_metadata(order)) {
|
||||
public ModifyOrderMenuItem(DemoOrdersModel model, Order order) : base(order, model.get_metadata(order)) {
|
||||
_model = model;
|
||||
_order = order;
|
||||
}
|
||||
|
||||
private readonly OrdersModel _model;
|
||||
private readonly DemoOrdersModel _model;
|
||||
private readonly Order _order;
|
||||
public override void execute() { _model.show_order_modify(_order); }
|
||||
}
|
||||
|
||||
@@ -9,14 +9,16 @@ namespace mbts.spark.menu_items
|
||||
{
|
||||
internal class ModifySecuritySelectionMenuItem : IMenuActionItem
|
||||
{
|
||||
public ModifySecuritySelectionMenuItem(IReadOnlyCollection<Security> securities, Action<IEnumerable<Security>> commit, string dialog_title="Select Securities") {
|
||||
public ModifySecuritySelectionMenuItem(IReadOnlyCollection<SecurityImmutable> securities, SecuritySource ssrc, Action<IEnumerable<SecurityImmutable>> commit, string dialog_title="Select Securities") {
|
||||
_securities = securities;
|
||||
_ssrc = ssrc;
|
||||
_commit = commit;
|
||||
_dialog_title = dialog_title;
|
||||
}
|
||||
private readonly string _dialog_title;
|
||||
private readonly IReadOnlyCollection<Security> _securities;
|
||||
private readonly Action<IEnumerable<Security>> _commit;
|
||||
private readonly IReadOnlyCollection<SecurityImmutable> _securities;
|
||||
private readonly Action<IEnumerable<SecurityImmutable>> _commit;
|
||||
readonly SecuritySource _ssrc;
|
||||
public string display_name => "Add/Remove Securities";
|
||||
public int priority => int.MinValue;
|
||||
public ImageSource icon => Icons.Coins;
|
||||
@@ -25,7 +27,7 @@ namespace mbts.spark.menu_items
|
||||
private IDisposable _dialog;
|
||||
public void execute() {
|
||||
Disposable.dispose(ref _dialog);
|
||||
_dialog = new SecuritySelectorDialog { DataContext = new SecuritySelectorDialogVM(_dialog_title, _securities, _commit) }.Show(-12, -30, true);
|
||||
_dialog = new SecuritySelectorDialog { DataContext = new SecuritySelectorDialogVM(_dialog_title, _securities, _commit, _ssrc) }.Show(-12, -30, true);
|
||||
}
|
||||
public event Action display_name_changed;
|
||||
public event Action can_execute_changed;
|
||||
|
||||
@@ -13,20 +13,20 @@ namespace mbts.spark.menu_items
|
||||
{
|
||||
internal class OrderTicketMenuItem : IMenuSecuritiesActionItem
|
||||
{
|
||||
public OrderTicketMenuItem(OrdersModel model, Func<Security, Order> order_factory=null) {
|
||||
public OrderTicketMenuItem(DemoOrdersModel model, Func<SecurityImmutable, Order> order_factory=null) {
|
||||
_model = model;
|
||||
_order_factory = order_factory ?? new Func<Security, Order>(s => new Order { Security = s, LimitOrder = new LimitOrder(), Size = 1 });
|
||||
_order_factory = order_factory ?? new Func<SecurityImmutable, Order>(s => new Order { Security = s.CloneToMutable(), LimitOrder = new LimitOrder(), Size = 1 });
|
||||
}
|
||||
|
||||
private readonly OrdersModel _model;
|
||||
private readonly Func<Security, Order> _order_factory;
|
||||
private readonly DemoOrdersModel _model;
|
||||
private readonly Func<SecurityImmutable, Order> _order_factory;
|
||||
|
||||
public string display_name => "Order Ticket";
|
||||
public int priority => 3;
|
||||
public ImageSource icon => Icons.Ticket;
|
||||
public string sectional_id => MenuItemSections.OrderActiveWindow;
|
||||
public void execute(IReadOnlyCollection<Security> securities) { _model.show_order_ticket(securities.Select(_order_factory).ToList()); }
|
||||
public bool can_execute(IReadOnlyCollection<Security> securities) { return securities.Count > 0; }
|
||||
public void execute(IReadOnlyCollection<SecurityImmutable> securities) { _model.show_order_ticket(securities.Select(_order_factory).ToList()); }
|
||||
public bool can_execute(IReadOnlyCollection<SecurityImmutable> securities) { return securities.Count > 0; }
|
||||
public void raise_display_name_changed() { display_name_changed?.Invoke(); }
|
||||
public void raise_can_execute_changed() { can_execute_changed?.Invoke(); }
|
||||
public event Action display_name_changed;
|
||||
@@ -35,7 +35,7 @@ namespace mbts.spark.menu_items
|
||||
|
||||
internal class LinkedOrderTicketMenuItem : IMenuActionItem
|
||||
{
|
||||
public LinkedOrderTicketMenuItem(IBus bus, IObservable<Security> security, Func<Security, Order> order_factory) : this(bus, security.Select(order_factory).Where(o => o != null)) { }
|
||||
public LinkedOrderTicketMenuItem(IBus bus, IObservable<SecurityImmutable> security, Func<SecurityImmutable, Order> order_factory) : this(bus, security.Select(order_factory).Where(o => o != null)) { }
|
||||
public LinkedOrderTicketMenuItem(IBus bus, IObservable<Order> order) {
|
||||
_bus = bus;
|
||||
_order = order;
|
||||
|
||||
@@ -19,8 +19,8 @@ namespace mbts.spark.menu_items
|
||||
public int priority => 1;
|
||||
public ImageSource icon => Icons.Cube3d;
|
||||
public string sectional_id => MenuItemSections.SecurityWindow;
|
||||
public void execute(IReadOnlyCollection<Security> securities) { _bus.post(SparkTags.ShowSpreadMatrixTag, new SparkBusData.ShowSpreadMatrixMessage(securities.ToList())); }
|
||||
public bool can_execute(IReadOnlyCollection<Security> securities) { return securities.Any(); }
|
||||
public void execute(IReadOnlyCollection<SecurityImmutable> securities) { _bus.post(SparkTags.ShowSpreadMatrixTag, new SparkBusData.ShowSpreadMatrixMessage(securities.ToList())); }
|
||||
public bool can_execute(IReadOnlyCollection<SecurityImmutable> securities) { return securities.Any(); }
|
||||
public void raise_display_name_changed() { display_name_changed?.Invoke(); }
|
||||
public void raise_can_execute_changed() { can_execute_changed?.Invoke(); }
|
||||
public event Action display_name_changed;
|
||||
|
||||
@@ -22,8 +22,8 @@ namespace mbts.spark.menu_items
|
||||
public int priority => 2;
|
||||
public ImageSource icon => Icons.Tetris;
|
||||
public string sectional_id => MenuItemSections.SecurityWindow;
|
||||
public void execute(IReadOnlyCollection<Security> securities) { _bus.post(ShowSyntheticCreateTag, new ShowSyntheticCreateMessage(securities)); }
|
||||
public bool can_execute(IReadOnlyCollection<Security> securities) {
|
||||
public void execute(IReadOnlyCollection<SecurityImmutable> securities) { _bus.post(ShowSyntheticCreateTag, new ShowSyntheticCreateMessage(securities)); }
|
||||
public bool can_execute(IReadOnlyCollection<SecurityImmutable> securities) {
|
||||
return securities.Count > 1 || (securities.Count == 1 && (securities.First().ContractCase == ContractOneofCase.Synthetic || securities.First().ContractCase == ContractOneofCase.Spread));
|
||||
}
|
||||
public void raise_display_name_changed() { display_name_changed?.Invoke(); }
|
||||
|
||||
@@ -21,8 +21,8 @@ namespace mbts.spark.menu_items
|
||||
public int priority => 1;
|
||||
public ImageSource icon => Icons.Knight;
|
||||
public string sectional_id => MenuItemSections.SecurityWindow;
|
||||
public void execute(IReadOnlyCollection<Security> securities) { _bus.post(ShowSyntheticStrategyTag, new ShowSyntheticStrategyMessage(securities.First())); }
|
||||
public bool can_execute(IReadOnlyCollection<Security> securities) { return securities.Count == 1 && securities.First().ContractCase == Security.ContractOneofCase.Synthetic; }
|
||||
public void execute(IReadOnlyCollection<SecurityImmutable> securities) { _bus.post(ShowSyntheticStrategyTag, new ShowSyntheticStrategyMessage(securities.First())); }
|
||||
public bool can_execute(IReadOnlyCollection<SecurityImmutable> securities) { return securities.Count == 1 && securities.First().ContractCase == Security.ContractOneofCase.Synthetic; }
|
||||
public void raise_display_name_changed() { display_name_changed?.Invoke(); }
|
||||
public void raise_can_execute_changed() { can_execute_changed?.Invoke(); }
|
||||
public event Action display_name_changed;
|
||||
|
||||
@@ -7,7 +7,7 @@ using System.Windows.Media;
|
||||
|
||||
namespace mbts.spark.menu_items
|
||||
{
|
||||
public class TimeAndSalesMenuItem : IMenuSecuritiesActionItem
|
||||
class TimeAndSalesMenuItem : IMenuSecuritiesActionItem
|
||||
{
|
||||
public TimeAndSalesMenuItem(IBus bus) {
|
||||
_bus = bus;
|
||||
@@ -19,8 +19,8 @@ namespace mbts.spark.menu_items
|
||||
public int priority => 4;
|
||||
public ImageSource icon => Icons.Clock;
|
||||
public string sectional_id => MenuItemSections.SecurityWindow;
|
||||
public void execute(IReadOnlyCollection<Security> ordered_selection) { _bus.post(SparkTags.ShowTimeAndSalesTag, new SparkBusData.ShowTimeAndSalesMessage(ordered_selection.ToList())); }
|
||||
public bool can_execute(IReadOnlyCollection<Security> ordered_selection) { return ordered_selection.Any(); }
|
||||
public void execute(IReadOnlyCollection<SecurityImmutable> ordered_selection) { _bus.post(SparkTags.ShowTimeAndSalesTag, new SparkBusData.ShowTimeAndSalesMessage(ordered_selection.ToList())); }
|
||||
public bool can_execute(IReadOnlyCollection<SecurityImmutable> ordered_selection) { return ordered_selection.Any(); }
|
||||
public void raise_display_name_changed() { display_name_changed?.Invoke(); }
|
||||
public void raise_can_execute_changed() { can_execute_changed?.Invoke(); }
|
||||
public event Action display_name_changed;
|
||||
|
||||
@@ -10,14 +10,14 @@ namespace mbts.spark
|
||||
{
|
||||
class OrderBookRowVM : ViewModelBase {
|
||||
readonly OrderBookVM _parent;
|
||||
readonly OrdersModel _model;
|
||||
readonly DemoOrdersModel _model;
|
||||
OrderBookEntry _order;
|
||||
|
||||
public OrderBookRowVM(OrderBookVM parent, OrdersModel model, OrderBookEntry entry) {
|
||||
public OrderBookRowVM(OrderBookVM parent, DemoOrdersModel model, OrderBookEntry entry) {
|
||||
_parent = parent;
|
||||
_model = model;
|
||||
_order = entry;
|
||||
security = new SelectableViewModelBase<Security>(_order.order().Security, SecurityDataHelper.Comparer.Instance);
|
||||
security = new SelectableViewModelBase<SecurityImmutable>(_order.order().Security, SecurityDataHelper.Comparer.Instance);
|
||||
_visible = backing(nameof(is_visible), !is_child);
|
||||
_expanded = backing(nameof(is_expanded), false);
|
||||
details_command = new DelegateCommand(() => _model.show_order_details(order_id));
|
||||
@@ -37,7 +37,7 @@ namespace mbts.spark
|
||||
|
||||
// the grid view uses this for sorting, it was just a bts.api.Security once upon a time, but that class no longer implements IComparable
|
||||
// this SelectableViewModeBase is essentially a wrapper class, which implements ISelecatble and IComparable
|
||||
public SelectableViewModelBase<Security> security { get; }
|
||||
public SelectableViewModelBase<SecurityImmutable> security { get; }
|
||||
public OrderBookEntry order => _order;
|
||||
public string security_text {
|
||||
// indent child 3 spaces
|
||||
@@ -114,7 +114,7 @@ namespace mbts.spark
|
||||
public double average_price {
|
||||
get =>
|
||||
_order.Fills.Count > 0 ?
|
||||
_order.order().Security.ContractSpec.round_to_tick(
|
||||
((SecurityImmutable)_order.order().Security).ContractSpec.round_to_tick(
|
||||
_order.Fills.Sum(f => f.Price * f.Size) / _order.Fills.Sum(f => f.Size))
|
||||
: 0;
|
||||
set => ignore();
|
||||
|
||||
@@ -17,9 +17,9 @@ using System.Windows.Input;
|
||||
namespace mbts.spark {
|
||||
class OrderBookVM : DisposableViewModelBase {
|
||||
public const string SAVE_NAME = "SparkOrderBookWindow";
|
||||
readonly OrdersModel _model;
|
||||
readonly DemoOrdersModel _model;
|
||||
|
||||
public OrderBookVM(IBus bus, OrdersModel model, OrderBookState state, IObservable<OrderBookSettings> settings) {
|
||||
public OrderBookVM(IBus bus, DemoOrdersModel model, OrderBookState state, IObservable<OrderBookSettings> settings) {
|
||||
_bus = bus;
|
||||
_model = model;
|
||||
|
||||
@@ -80,7 +80,7 @@ namespace mbts.spark {
|
||||
private IEnumerable<MenuItemVM> _context_menu_item_factory() {
|
||||
var selected_rows = this.orders.Where(vm => vm.is_selected && vm.is_visible).ToList();
|
||||
var orders = selected_rows.Select(vm => vm.order).ToList();
|
||||
var securities = new HashSet<Security>(selected_rows.Select(vm => vm.security.value));
|
||||
var securities = new HashSet<SecurityImmutable>(selected_rows.Select(vm => vm.security.value));
|
||||
yield return MenuItemVM.Create(new LadderMenuItem(_bus), securities);
|
||||
yield return MenuItemVM.Create(new OrderTicketMenuItem(_model), securities);
|
||||
yield return MenuItemVM.Create(new MarketViewMenuItem(_bus), securities);
|
||||
|
||||
@@ -4,7 +4,6 @@ using Google.Protobuf;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reactive.Linq;
|
||||
using MDMap = System.Collections.Generic.Dictionary<uint, mbts.spark.SecurityMD>;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
@@ -24,7 +23,7 @@ namespace mbts.spark
|
||||
/// <param name="strategy">The new strategy to create, or existing strategy modify</param>
|
||||
public async void save(Security synthetic, ExecutionStrategy strategy) {
|
||||
if (synthetic.ContractCase != Security.ContractOneofCase.Synthetic) throw new ArgumentException("Must be a synthetic security.", nameof(synthetic));
|
||||
var map = await _bus.subscribe<MDMap>(SparkTags.SecuritiesTag).FirstAsync();
|
||||
var map = await _bus.subscribe(SparkTags.SecuritiesTag).FirstAsync();
|
||||
if (synthetic.Id == 0) {
|
||||
// CREATE
|
||||
var curr_secmap = new HashSet<uint>(map.Keys);
|
||||
@@ -32,7 +31,7 @@ namespace mbts.spark
|
||||
while (curr_secmap.Contains(id)) id--;
|
||||
synthetic.Id = id;
|
||||
var sec_strategy = new SyntheticExecutionStrategy { Security = synthetic, ExecutionStrategy = strategy };
|
||||
_bus.post(SparkTags.PersistCommandTag, new SparkBusData.PersistMessage(1, "SyntheticSecurity", String.Empty, sec_strategy.ToByteArray()));
|
||||
_bus.post(SparkTags.PersistCommandTag, new SparkBusData.PersistMessage(1, "SyntheticSecurity", String.Empty, ((IImmutableMessage)sec_strategy).ToByteArray()));
|
||||
} else {
|
||||
// MODIFY
|
||||
}
|
||||
|
||||
@@ -12,34 +12,34 @@ namespace mbts.spark
|
||||
{
|
||||
internal class TimeAndSalesModel : IDisposable
|
||||
{
|
||||
public TimeAndSalesModel(IBus bus, IReadOnlyCollection<Security> securities) {
|
||||
public TimeAndSalesModel(IBus bus, IReadOnlyCollection<SecurityImmutable> securities) {
|
||||
set_securities(securities);
|
||||
_orders_model = new OrdersModel(bus);
|
||||
_orders_model = new DemoOrdersModel(bus);
|
||||
_work_loop = WorkLoop.Start(_refresh);
|
||||
}
|
||||
|
||||
private readonly IDisposable _work_loop;
|
||||
private readonly OrdersModel _orders_model;
|
||||
private readonly DemoOrdersModel _orders_model;
|
||||
|
||||
private readonly Subject<IReadOnlyList<Tuple<Security, TradeMessage>>> _trades = new Subject<IReadOnlyList<Tuple<Security, TradeMessage>>>();
|
||||
private readonly Dictionary<Security, MDConsumerChannel> _channels = new Dictionary<Security, MDConsumerChannel>();
|
||||
private readonly Subject<IReadOnlyList<Tuple<SecurityImmutable, TradeMessage>>> _trades = new Subject<IReadOnlyList<Tuple<SecurityImmutable, TradeMessage>>>();
|
||||
private readonly Dictionary<SecurityImmutable, MDConsumerChannel> _channels = new Dictionary<SecurityImmutable, MDConsumerChannel>();
|
||||
|
||||
private void _refresh() {
|
||||
var ts = _channels.SelectMany(kv => kv.Value.read_trades().Select(t => Tuple.Create(kv.Key, t))).ToList();
|
||||
if (ts.Count > 0) _trades.OnNext(ts);
|
||||
}
|
||||
|
||||
private static IEnumerable<Security> _get_real_securities(Security security) {
|
||||
private static IEnumerable<SecurityImmutable> _get_real_securities(SecurityImmutable 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 IObservable<IReadOnlyList<Tuple<SecurityImmutable, TradeMessage>>> trades => _trades.AsObservable();
|
||||
public IReadOnlyCollection<SecurityImmutable> securities => _channels.Keys;
|
||||
public DemoOrdersModel orders_model => _orders_model;
|
||||
|
||||
public void set_securities(IEnumerable<Security> securities) {
|
||||
public void set_securities(IEnumerable<SecurityImmutable> securities) {
|
||||
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()) {
|
||||
|
||||
@@ -26,10 +26,11 @@ namespace mbts.spark
|
||||
public const int VERSION = 1;
|
||||
public const string SAVE_NAME = "TimeAndSales";
|
||||
|
||||
public TimeAndSalesVM(IBus bus, IReadOnlyCollection<Security> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria = null) {
|
||||
public TimeAndSalesVM(IBus bus, IReadOnlyCollection<SecurityImmutable> securities, SecuritySource ssrc, IReadOnlyCollection<SortingCriteria> sorting_criteria = null) {
|
||||
_bus = bus;
|
||||
_ssrc = ssrc;
|
||||
_resources.Add(_model = new TimeAndSalesModel(bus, securities));
|
||||
_rows = new ObservableAutoWrapper<Row, Tuple<Security, TradeMessage>>(_trades, tup => new Row(tup.Item1, tup.Item2));
|
||||
_rows = new ObservableAutoWrapper<Row, Tuple<SecurityImmutable, TradeMessage>>(_trades, tup => new Row(tup.Item1, tup.Item2));
|
||||
_rows.ViewDestroyed += r => r.Dispose();
|
||||
_resources.Add(Disposable.Create(() => _rows.Clear()));
|
||||
rows_view = CollectionViewSource.GetDefaultView(_rows);
|
||||
@@ -52,20 +53,21 @@ namespace mbts.spark
|
||||
}
|
||||
|
||||
private readonly IBus _bus;
|
||||
readonly SecuritySource _ssrc;
|
||||
private readonly TimeAndSalesModel _model;
|
||||
private readonly ObservableCollection<Tuple<Security, TradeMessage>> _trades = new ObservableCollection<Tuple<Security, TradeMessage>>();
|
||||
private readonly ObservableAutoWrapper<Row, Tuple<Security, TradeMessage>> _rows;
|
||||
private readonly ObservableCollection<Tuple<SecurityImmutable, TradeMessage>> _trades = new ObservableCollection<Tuple<SecurityImmutable, TradeMessage>>();
|
||||
private readonly ObservableAutoWrapper<Row, Tuple<SecurityImmutable, TradeMessage>> _rows;
|
||||
private readonly ContextMenuVM _context_menu;
|
||||
private readonly ColdObseravbleProperty<DataGridCellInfo> _current_cell = new ColdObseravbleProperty<DataGridCellInfo>();
|
||||
private IList<IDisposable> _resources = new List<IDisposable>();
|
||||
private IOrderBook _order_book = new OrderBook();
|
||||
|
||||
private IEnumerable<MenuItemVM> _context_menu_item_factory() {
|
||||
yield return MenuItemVM.Create(new ModifySecuritySelectionMenuItem(new HashSet<Security>(_rows.Select(r => r.security.value)), _model.set_securities));
|
||||
yield return MenuItemVM.Create(new ModifySecuritySelectionMenuItem(new HashSet<SecurityImmutable>(_rows.Select(r => r.security.value)), _ssrc, _model.set_securities));
|
||||
if (current_cell != null && current_cell.Column != null && current_cell.Item != null && !current_cell.Item.Equals(System.Windows.DependencyProperty.UnsetValue)) {
|
||||
var securities = _rows.Where(r => r.is_selected).Select(r => r.security.value).ToList();
|
||||
yield return MenuItemVM.Create(new LadderMenuItem(_bus), securities);
|
||||
yield return MenuItemVM.Create(new LinkedLadderMenuItem(_bus, _get_current_security_observable().ToSecurityMD()));
|
||||
yield return MenuItemVM.Create(new LinkedLadderMenuItem(_bus, _get_current_security_observable().ToSecurityMD(_bus)));
|
||||
yield return MenuItemVM.Create(new OrderTicketMenuItem(_model.orders_model), securities);
|
||||
yield return MenuItemVM.Create(new LinkedOrderTicketMenuItem(_bus, _get_current_security_observable().Select(OrderDataHelper.Defaults.Order)));
|
||||
yield return MenuItemVM.Create(new MarketViewMenuItem(_bus), securities);
|
||||
@@ -80,8 +82,8 @@ namespace mbts.spark
|
||||
}
|
||||
}
|
||||
|
||||
private IObservable<Security> _get_current_security_observable() { return _current_cell.Select(_get_security).DistinctUntilChanged(); }
|
||||
private static Security _get_security(DataGridCellInfo cell) { return ((Row)cell.Item).security.value; }
|
||||
private IObservable<SecurityImmutable> _get_current_security_observable() { return _current_cell.Select(_get_security).DistinctUntilChanged(); }
|
||||
private static SecurityImmutable _get_security(DataGridCellInfo cell) { return ((Row)cell.Item).security.value; }
|
||||
|
||||
public ICollectionView rows_view { get; private set; }
|
||||
public DataGridCellInfo current_cell { get => _current_cell.Value; set => _current_cell.set(value); }
|
||||
@@ -91,7 +93,7 @@ namespace mbts.spark
|
||||
public void Dispose() { Disposable.dispose(_resources); }
|
||||
|
||||
private class Row : GridRowViewModelBase<Columns> {
|
||||
public Row(Security security, TradeMessage trade) {
|
||||
public Row(SecurityImmutable security, TradeMessage trade) {
|
||||
this.security = AddCell(Columns.Security, security, SecurityDataHelper.Comparer.Instance);
|
||||
quantity = AddCell(Columns.Size, trade.Size);
|
||||
price = AddCell(Columns.Price, trade.Mantissa * Math.Pow(10, trade.Exponent));
|
||||
@@ -99,7 +101,7 @@ namespace mbts.spark
|
||||
order_type = AddCell(Columns.OrderType, Order.AlgoOrderTypeOneofCase.None);
|
||||
}
|
||||
|
||||
public SelectableViewModelBase<Security> security { get; }
|
||||
public SelectableViewModelBase<SecurityImmutable> security { get; }
|
||||
public SelectableViewModelBase<uint> quantity { get; }
|
||||
public SelectableViewModelBase<double> price { get; }
|
||||
public SelectableViewModelBase<DateTime> trade_time { get; }
|
||||
@@ -110,8 +112,8 @@ namespace mbts.spark
|
||||
public class StartupData {
|
||||
public const int Version = 1;
|
||||
public StartupData() { }
|
||||
public StartupData(IReadOnlyCollection<Security> securities, SortingCriteria[] sorting_criteria) {
|
||||
if (securities != null) this.securities = securities.Select(s => s.ToByteArray()).ToArray();
|
||||
public StartupData(IReadOnlyCollection<SecurityImmutable> securities, SortingCriteria[] sorting_criteria) {
|
||||
if (securities != null) this.securities = securities.Select(s => ((IImmutableMessage)s).ToByteArray()).ToArray();
|
||||
this.sorting_criteria = sorting_criteria;
|
||||
}
|
||||
[ProtoMember(1)]
|
||||
|
||||
@@ -12,18 +12,20 @@ namespace mbts.spark
|
||||
{
|
||||
internal class TimeAndSalesWindow : IShellWindow
|
||||
{
|
||||
public TimeAndSalesWindow(IShellModule owner, IBus bus, IReadOnlyCollection<Security> securities) : this (owner, bus, securities, null) { }
|
||||
public TimeAndSalesWindow(IShellModule owner, IBus bus, TimeAndSalesVM.StartupData startup_data) : this(owner, bus, startup_data.securities.Select(deserialize<Security>).ToList(), startup_data.sorting_criteria) { }
|
||||
public TimeAndSalesWindow(IShellModule owner, IBus bus, IReadOnlyCollection<SecurityImmutable> securities, SecuritySource ssrc) : this (owner, bus, securities, ssrc, null) { }
|
||||
public TimeAndSalesWindow(IShellModule owner, IBus bus, TimeAndSalesVM.StartupData startup_data, SecuritySource ssrc) : this(owner, bus, startup_data.securities.Select(x => (SecurityImmutable)deserialize<Security>(x)).ToList(), ssrc, startup_data.sorting_criteria) { }
|
||||
|
||||
private TimeAndSalesWindow(IShellModule owner, IBus bus, IReadOnlyCollection<Security> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria) {
|
||||
private TimeAndSalesWindow(IShellModule owner, IBus bus, IReadOnlyCollection<SecurityImmutable> securities, SecuritySource ssrc, IReadOnlyCollection<SortingCriteria> sorting_criteria) {
|
||||
_bus = bus;
|
||||
_ssrc = ssrc;
|
||||
_securities = securities;
|
||||
_sorting_criteria = sorting_criteria;
|
||||
_owner = owner;
|
||||
}
|
||||
|
||||
private readonly IBus _bus;
|
||||
private readonly IReadOnlyCollection<Security> _securities;
|
||||
readonly SecuritySource _ssrc;
|
||||
private readonly IReadOnlyCollection<SecurityImmutable> _securities;
|
||||
private readonly IReadOnlyCollection<SortingCriteria> _sorting_criteria;
|
||||
private TimeAndSalesVM _vm;
|
||||
private IShellModule _owner;
|
||||
@@ -37,7 +39,7 @@ namespace mbts.spark
|
||||
public event Action TitleChanged;
|
||||
public event Action IconChanged;
|
||||
public void Dispose() { Disposable.dispose(ref _vm); }
|
||||
public ShellWindowUI GetContent() { return new ShellWindowUI(new TimeAndSalesView { DataContext = _vm = new TimeAndSalesVM(_bus, _securities, _sorting_criteria), Width = 400, Height = 500 }); }
|
||||
public ShellWindowUI GetContent() { return new ShellWindowUI(new TimeAndSalesView { DataContext = _vm = new TimeAndSalesVM(_bus, _securities, _ssrc, _sorting_criteria), Width = 400, Height = 500 }); }
|
||||
public void GetState(Stream save_here) {
|
||||
if (_vm != null) {
|
||||
serialize(save_here, new ShellSerializationHeader { name = TimeAndSalesVM.SAVE_NAME, version = TimeAndSalesVM.VERSION });
|
||||
|
||||
@@ -21,8 +21,9 @@ namespace mbts.spark
|
||||
internal class TradesModule : IShellModule
|
||||
{
|
||||
[ImportingConstructor]
|
||||
public TradesModule(IBus bus, IWindowManager wm) {
|
||||
public TradesModule(IBus bus, IWindowManager wm, SecuritySource ssrc) {
|
||||
_bus = bus;
|
||||
_ssrc = ssrc;
|
||||
_wm = wm;
|
||||
_dispose = Disposable.Create(
|
||||
_bus.subscribe<ShowOrderBookMessage>(ShowOrderBookTag).ObserveOnDispatcher().Subscribe(show_order_book),
|
||||
@@ -34,6 +35,7 @@ namespace mbts.spark
|
||||
}
|
||||
|
||||
private readonly IBus _bus;
|
||||
readonly SecuritySource _ssrc;
|
||||
private readonly IWindowManager _wm;
|
||||
private readonly IDisposable _dispose;
|
||||
|
||||
@@ -42,6 +44,7 @@ namespace mbts.spark
|
||||
public ImageSource icon => Icons.Trades;
|
||||
public IShellWindow launch_ui => new LaunchMenu {
|
||||
DataContext = new LaunchMenuVM(
|
||||
_ssrc,
|
||||
new OrderBookMenuItem(_bus),
|
||||
new FillsMenuItem(_bus),
|
||||
new AuditLogsMenuItem(_bus),
|
||||
@@ -55,7 +58,7 @@ namespace mbts.spark
|
||||
switch(header?.name) {
|
||||
case OrderBookVM.SAVE_NAME: if (try_deserialize(load_stream, out OrderBookState orders_state)) return Task.FromResult(create_order_book_window(orders_state)); break;
|
||||
case FillsVM.SAVE_NAME: { if (try_deserialize(load_stream, out FillsVM.StartupData state)) return Task.FromResult(create_fills_window(state)); break; }
|
||||
case TimeAndSalesVM.SAVE_NAME: { if (try_deserialize(load_stream, out TimeAndSalesVM.StartupData state)) return Task.FromResult<IShellWindow>(new TimeAndSalesWindow(this, _bus, state)); break; }
|
||||
case TimeAndSalesVM.SAVE_NAME: { if (try_deserialize(load_stream, out TimeAndSalesVM.StartupData state)) return Task.FromResult<IShellWindow>(new TimeAndSalesWindow(this, _bus, state, _ssrc)); break; }
|
||||
}
|
||||
return Task.FromResult<IShellWindow>(null);
|
||||
}
|
||||
@@ -63,23 +66,23 @@ namespace mbts.spark
|
||||
public void Dispose() { _dispose.Dispose(); }
|
||||
|
||||
private IShellWindow create_order_book_window(OrderBookState state) {
|
||||
var vm = new OrderBookVM(_bus, new OrdersModel(_bus), state, Observable.Return(new OrderBookSettings()));
|
||||
var vm = new OrderBookVM(_bus, new DemoOrdersModel(_bus), state, Observable.Return(new OrderBookSettings()));
|
||||
var view = new OrderBookView(vm) { Width = 1526, Height = 800 };
|
||||
return ShellWindow.create(this, "Order Book", view, vm.get_state);
|
||||
}
|
||||
|
||||
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);
|
||||
private IShellWindow create_fills_window(FillsVM.StartupData startup_data) { return create_fills_window(startup_data.securities?.Select(x => (SecurityImmutable)deserialize<Security>(x)).ToList(), startup_data.sorting_criteria); }
|
||||
private IShellWindow create_fills_window(IReadOnlyCollection<SecurityImmutable> securities) { return create_fills_window(securities, null); }
|
||||
private IShellWindow create_fills_window(IReadOnlyCollection<SecurityImmutable> securities, IReadOnlyCollection<SortingCriteria> sorting_criteria) {
|
||||
var vm = new FillsVM(_bus, new DemoOrdersModel(_bus), _ssrc, securities, sorting_criteria);
|
||||
var view = new FillsView { DataContext = vm, Width = 1024, Height = 800 };
|
||||
return ShellWindow.create(this, "Fills", view, vm.get_state, Icons.Ticket);
|
||||
}
|
||||
|
||||
private void show_order_book(ShowOrderBookMessage msg) { _wm.Windows.Add(create_order_book_window(new OrderBookState())); }
|
||||
private void show_fills(ShowFillsMessage msg) { _wm.Windows.Add(create_fills_window(new List<Security>())); }
|
||||
private void show_fills(ShowFillsMessage msg) { _wm.Windows.Add(create_fills_window(new List<SecurityImmutable>())); }
|
||||
private void show_audit_log(ShowAuditLogsMessage msg) { }
|
||||
private void show_positions(ShowPositionsMessage msg) { }
|
||||
private void show_time_and_sales(ShowTimeAndSalesMessage msg) { _wm.Windows.Add(new TimeAndSalesWindow(this, _bus, msg.data)); }
|
||||
private void show_time_and_sales(ShowTimeAndSalesMessage msg) { _wm.Windows.Add(new TimeAndSalesWindow(this, _bus, msg.data, _ssrc)); }
|
||||
}
|
||||
}
|
||||
@@ -8,10 +8,10 @@ namespace mbts.spark
|
||||
{
|
||||
internal class BBOVM : DisposableViewModelBase
|
||||
{
|
||||
public BBOVM(uint security) : this(Observable.Return(security)) { }
|
||||
public BBOVM(IObservable<uint> security) : this(security.ToSecurity()) { }
|
||||
public BBOVM(IObservable<Security> security) : this(security, new SecurityMDPump(security)) { }
|
||||
public BBOVM(IObservable<Security> security, ISecurityMDPump md_pump) {
|
||||
public BBOVM(uint security, IBus bus) : this(Observable.Return(security), bus) { }
|
||||
public BBOVM(IObservable<uint> security, IBus bus) : this(security.ToSecurity(bus), bus) { }
|
||||
public BBOVM(IObservable<SecurityImmutable> security, IBus bus) : this(security, new SecurityMDPump(security, bus)) { }
|
||||
public BBOVM(IObservable<SecurityImmutable> security, ISecurityMDPump md_pump) {
|
||||
_security = backing(nameof(security), security, Security.Empty);
|
||||
_bid = backing(nameof(bid), md_pump.bid_price, double.NaN);
|
||||
_ask = backing(nameof(ask), md_pump.ask_price, double.NaN);
|
||||
@@ -19,11 +19,11 @@ namespace mbts.spark
|
||||
_ask_size = backing(nameof(ask_size), md_pump.ask_size, (ushort)0);
|
||||
}
|
||||
|
||||
private readonly Property<Security> _security;
|
||||
private readonly Property<SecurityImmutable> _security;
|
||||
private readonly Property<double> _bid, _ask;
|
||||
private readonly Property<ushort> _bid_size, _ask_size;
|
||||
|
||||
public Security security => _security.Value;
|
||||
public SecurityImmutable security => _security.Value;
|
||||
public double bid => _bid.Value;
|
||||
public double ask => _ask.Value;
|
||||
public ushort bid_size => _bid_size.Value;
|
||||
|
||||
@@ -6,7 +6,6 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
using MDMap = System.Collections.Generic.Dictionary<uint, mbts.spark.SecurityMD>;
|
||||
|
||||
namespace mbts.spark.utilities
|
||||
{
|
||||
@@ -28,18 +27,18 @@ namespace mbts.spark.utilities
|
||||
|
||||
internal class SecurityMDPump : ISecurityMDPump, IDisposable
|
||||
{
|
||||
public SecurityMDPump(Security security) : this(security, WorkLoop.DefaultPollInterval) { }
|
||||
public SecurityMDPump(Security security, TimeSpan poll_interval) : this(security, Observable.Interval(poll_interval)) { }
|
||||
public SecurityMDPump(Security security, IObservable<long> poll) : this(security.Id, poll) { }
|
||||
public SecurityMDPump(IObservable<Security> security) : this(security.Select(s => s.Id)) { }
|
||||
public SecurityMDPump(IObservable<Security> security, TimeSpan poll_interval) : this(security.Select(s => s.Id), poll_interval) { }
|
||||
public SecurityMDPump(IObservable<Security> security, IObservable<long> poll) : this(security.Select(s => s.Id), poll) { }
|
||||
public SecurityMDPump(uint security) : this(security, WorkLoop.DefaultPollInterval) { }
|
||||
public SecurityMDPump(uint security, TimeSpan poll_interval) : this(security, Observable.Interval(poll_interval)) { }
|
||||
public SecurityMDPump(uint security, IObservable<long> poll) : this(Observable.Return(security).ToSecurity(), poll) { }
|
||||
public SecurityMDPump(IObservable<uint> security) : this(security, WorkLoop.DefaultPollInterval) { }
|
||||
public SecurityMDPump(IObservable<uint> security, TimeSpan poll_interval) : this(security, Observable.Interval(poll_interval)) { }
|
||||
public SecurityMDPump(IObservable<uint> security, IObservable<long> poll) : this(security.CombineLatest(ImportedResources.Bus.subscribe<MDMap>(SparkTags.SecuritiesTag), (s, m) => m.GetValueOrDefault(s).md).Where(md => md != null), poll) { }
|
||||
public SecurityMDPump(SecurityImmutable security, IBus bus) : this(security, WorkLoop.DefaultPollInterval, bus) { }
|
||||
public SecurityMDPump(SecurityImmutable security, TimeSpan poll_interval, IBus bus) : this(security, Observable.Interval(poll_interval), bus) { }
|
||||
public SecurityMDPump(SecurityImmutable security, IObservable<long> poll, IBus bus) : this(security.Id, poll, bus) { }
|
||||
public SecurityMDPump(IObservable<SecurityImmutable> security, IBus bus) : this(security.Select(s => s.Id), bus) { }
|
||||
public SecurityMDPump(IObservable<SecurityImmutable> security, TimeSpan poll_interval, IBus bus) : this(security.Select(s => s.Id), poll_interval, bus) { }
|
||||
public SecurityMDPump(IObservable<SecurityImmutable> security, IObservable<long> poll, IBus bus) : this(security.Select(s => s.Id), poll, bus) { }
|
||||
public SecurityMDPump(uint security, IBus bus) : this(security, WorkLoop.DefaultPollInterval, bus) { }
|
||||
public SecurityMDPump(uint security, TimeSpan poll_interval, IBus bus) : this(security, Observable.Interval(poll_interval), bus) { }
|
||||
public SecurityMDPump(uint security, IObservable<long> poll, IBus bus) : this(Observable.Return(security).ToSecurity(bus), poll, bus) { }
|
||||
public SecurityMDPump(IObservable<uint> security, IBus bus) : this(security, WorkLoop.DefaultPollInterval, bus) { }
|
||||
public SecurityMDPump(IObservable<uint> security, TimeSpan poll_interval, IBus bus) : this(security, Observable.Interval(poll_interval), bus) { }
|
||||
public SecurityMDPump(IObservable<uint> security, IObservable<long> poll, IBus bus) : this(security.CombineLatest(bus.subscribe(SparkTags.SecuritiesTag), (s, m) => m.GetValueOrDefault(s).md).Where(md => md != null), poll) { }
|
||||
public SecurityMDPump(IMDHandle md) : this(Observable.Return(md)) { }
|
||||
public SecurityMDPump(IMDHandle md, TimeSpan poll_interval) : this(Observable.Return(md), poll_interval) { }
|
||||
public SecurityMDPump(IMDHandle md, IObservable<long> poll) : this(Observable.Return(md), poll) { }
|
||||
|
||||
@@ -5,44 +5,21 @@ using System;
|
||||
using System.ComponentModel.Composition;
|
||||
using System.Reactive.Linq;
|
||||
using static mbts.spark.SparkTags;
|
||||
using MDMap = System.Collections.Generic.Dictionary<uint, mbts.spark.SecurityMD>;
|
||||
|
||||
namespace mbts.spark.utilities
|
||||
{
|
||||
internal static class ImportedResources
|
||||
{
|
||||
public static IBus Bus => _instance.bus;
|
||||
public static string UserName => _instance.user_name;
|
||||
public static readonly string[] Accounts = new[] { "Account1", "Account2", "Account3", "Account4" };
|
||||
|
||||
#region Misc Extensions (should put these in a more appropriate place eventually)
|
||||
public static IObservable<Security> ToSecurity(this IObservable<uint> securityKey) {
|
||||
return securityKey.CombineLatest(Bus.subscribe<MDMap>(SecuritiesTag), (sk, map) => map.GetValueOrDefault(sk).security).Where(s => s != null);
|
||||
public static IObservable<SecurityImmutable> ToSecurity(this IObservable<uint> securityKey, IBus bus) {
|
||||
return securityKey.CombineLatest(bus.subscribe(SecuritiesTag), (sk, map) => map.GetValueOrDefault(sk).security);
|
||||
}
|
||||
public static IObservable<SecurityMD> ToSecurityMD(this IObservable<uint> securityKey) {
|
||||
return securityKey.CombineLatest(Bus.subscribe<MDMap>(SecuritiesTag), (sk, map) => map.GetValueOrDefault(sk));
|
||||
public static IObservable<SecurityMD> ToSecurityMD(this IObservable<uint> securityKey, IBus bus) {
|
||||
return securityKey.CombineLatest(bus.subscribe(SecuritiesTag), (sk, map) => map.GetValueOrDefault(sk));
|
||||
}
|
||||
public static IObservable<SecurityMD> ToSecurityMD(this IObservable<Security> security) {
|
||||
return security.CombineLatest(Bus.subscribe<MDMap>(SecuritiesTag), (s, map) => map.GetValueOrDefault(s.Id));
|
||||
}
|
||||
#endregion
|
||||
|
||||
private static HiddenInstance _instance;
|
||||
|
||||
[Export(typeof(IInitializable))]
|
||||
private class HiddenInstance : IInitializable
|
||||
{
|
||||
[ImportingConstructor]
|
||||
public HiddenInstance(IBus bus, [Import("username")]string user_name) {
|
||||
this.bus = bus;
|
||||
this.user_name = user_name;
|
||||
}
|
||||
|
||||
internal readonly IBus bus;
|
||||
internal readonly string user_name;
|
||||
|
||||
public int priority => int.MaxValue;
|
||||
public void initialize() { _instance = this; }
|
||||
public static IObservable<SecurityMD> ToSecurityMD(this IObservable<SecurityImmutable> security, IBus bus) {
|
||||
return security.CombineLatest(bus.subscribe(SecuritiesTag), (s, map) => map.GetValueOrDefault(s.Id));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,12 +39,12 @@ namespace mbts.spark.utilities
|
||||
BTSIcebergOrder
|
||||
};
|
||||
|
||||
public static Order Order(Security security) { return Order(security, bts.spark.Order.AlgoOrderTypeOneofCase.LimitOrder); }
|
||||
public static Order Order(Security security, Order.AlgoOrderTypeOneofCase algo_type) {
|
||||
public static Order Order(SecurityImmutable security) { return Order(security, bts.spark.Order.AlgoOrderTypeOneofCase.LimitOrder); }
|
||||
public static Order Order(SecurityImmutable security, Order.AlgoOrderTypeOneofCase algo_type) {
|
||||
var rv = new Order {
|
||||
Account = ImportedResources.Accounts.FirstOrDefault(),
|
||||
User = ImportedResources.UserName,
|
||||
Security = security,
|
||||
User = "bts",
|
||||
Security = security.CloneToMutable(),
|
||||
};
|
||||
switch (algo_type) {
|
||||
case bts.spark.Order.AlgoOrderTypeOneofCase.LimitOrder: rv.LimitOrder = new LimitOrder(); break;
|
||||
|
||||
@@ -6,13 +6,13 @@ using static bts.api.Security;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
public static class SecurityDataHelper
|
||||
static class SecurityDataHelper
|
||||
{
|
||||
public static class Comparer
|
||||
{
|
||||
public static readonly IComparer<Security> Instance = Comparer<Security>.Create(Compare);
|
||||
public static readonly IComparer<SecurityImmutable> Instance = Comparer<SecurityImmutable>.Create(Compare);
|
||||
|
||||
public static int Compare(Security x, Security y) {
|
||||
public static int Compare(SecurityImmutable x, SecurityImmutable y) {
|
||||
if (x == null) return y == null ? 0 : -1;
|
||||
if (y == null) return 1;
|
||||
if (x.ContractCase == ContractOneofCase.Future) return y.ContractCase == ContractOneofCase.Future ? Compare(x.Symbol, x.Future, y.Symbol, y.Future) : -1;
|
||||
@@ -35,7 +35,7 @@ namespace mbts.spark
|
||||
return xlegs.Length.CompareTo(ylegs.Length);
|
||||
}
|
||||
|
||||
public static int Compare(string x_sym, FutureContract x, string y_sym, FutureContract y) {
|
||||
public static int Compare(string x_sym, FutureContractImmutable x, string y_sym, FutureContractImmutable y) {
|
||||
int sym_comp = x_sym.CompareTo(y_sym);
|
||||
return sym_comp == 0 ? x.RawExpDate().CompareTo(y.RawExpDate()) : sym_comp;
|
||||
}
|
||||
|
||||
@@ -130,16 +130,16 @@ namespace mbts.spark.utilities
|
||||
public static PostHedgeTimeBasedForcedCross PostHedgeTimeBasedForcedCross => new PostHedgeTimeBasedForcedCross();
|
||||
#endregion
|
||||
|
||||
public static Security Security(string name, Security from) {
|
||||
public static Security Security(string name, SecurityImmutable from) {
|
||||
Security rv = null;
|
||||
switch(from.ContractCase) {
|
||||
case bts.api.Security.ContractOneofCase.Spread:
|
||||
var legs = from.Spread.Legs.ToList();
|
||||
rv = from.Clone();
|
||||
var legs = from.Spread.Legs.Select(l => l.CloneToMutable()).ToList();
|
||||
rv = from.CloneToMutable();
|
||||
rv.Synthetic = SyntheticContract(name, legs);
|
||||
break;
|
||||
case bts.api.Security.ContractOneofCase.Synthetic:
|
||||
rv = from.Clone();
|
||||
rv = from.CloneToMutable();
|
||||
rv.Synthetic.Name = name;
|
||||
break;
|
||||
default: throw new ArgumentException("Must be a Synthetic, or Spread.", nameof(from));
|
||||
@@ -147,7 +147,7 @@ namespace mbts.spark.utilities
|
||||
rv.Id = 0;
|
||||
return rv;
|
||||
}
|
||||
public static Security Security(string name, IEnumerable<Security> securities) { return Security(name, securities.Select(ContractLeg), MathUtils.GCD(securities.Select(s => s.ContractSpec.LowTick))); }
|
||||
public static Security Security(string name, IEnumerable<SecurityImmutable> securities) { return Security(name, securities.Select(ContractLeg), MathUtils.GCD(securities.Select(s => s.ContractSpec.LowTick))); }
|
||||
public static Security Security(string name, IEnumerable<ContractLeg> legs, double tick_size) {
|
||||
return new Security {
|
||||
Id = 0,
|
||||
@@ -166,18 +166,18 @@ namespace mbts.spark.utilities
|
||||
foreach (var l in legs) rv.Legs.Add(l);
|
||||
return rv;
|
||||
}
|
||||
public static ContractLeg ContractLeg(Security security) {
|
||||
return new ContractLeg { Security = security, PriceMultiplier = 1, Quantity = 1, Side = Side.Buy };
|
||||
public static ContractLeg ContractLeg(SecurityImmutable security) {
|
||||
return new ContractLeg { Security = security.CloneToMutable(), PriceMultiplier = 1, Quantity = 1, Side = Side.Buy };
|
||||
}
|
||||
|
||||
public static ExecutionStrategy ExecutionStrategy(Security security) {
|
||||
public static ExecutionStrategy ExecutionStrategy(SecurityImmutable security) {
|
||||
switch(security.ContractCase) {
|
||||
case bts.api.Security.ContractOneofCase.Spread: return ExecutionStrategy(security.Spread.Legs.Select(l => l.Security));
|
||||
case bts.api.Security.ContractOneofCase.Synthetic: return ExecutionStrategy(security.Synthetic.Legs.Select(l => l.Security));
|
||||
default: throw new ArgumentException("Must be a Spread, or Synthetic", nameof(security));
|
||||
}
|
||||
}
|
||||
public static ExecutionStrategy ExecutionStrategy(IEnumerable<Security> securities) { return ExecutionStrategy(securities.Select(s => s.Id)); }
|
||||
public static ExecutionStrategy ExecutionStrategy(IEnumerable<SecurityImmutable> securities) { return ExecutionStrategy(securities.Select(s => s.Id)); }
|
||||
public static ExecutionStrategy ExecutionStrategy(IEnumerable<uint> security_keys) {
|
||||
var rv = new ExecutionStrategy();
|
||||
foreach (var sk in security_keys) rv.LegParamsMap.Add(sk, LegSpreaderParams);
|
||||
|
||||
@@ -4,7 +4,7 @@ namespace bts.api
|
||||
{
|
||||
static class SecurityConverter
|
||||
{
|
||||
public static SecurityType security_type(this Security security) {
|
||||
public static SecurityType security_type(this SecurityImmutable security) {
|
||||
switch (security.ContractCase) {
|
||||
case ContractOneofCase.Future: return SecurityType.Future;
|
||||
case ContractOneofCase.Spread: return SecurityType.Spread;
|
||||
|
||||
@@ -72,7 +72,7 @@ namespace mbts.api.Test {
|
||||
var h = _context.locate<HelloService>();
|
||||
|
||||
TableUpdate<HelloLog, string> last_update = null;
|
||||
using (var sub1 = h.subscribe_greetings().table().Subscribe(t => last_update = t)) {
|
||||
using (var sub1 = h.subscribe_greetings().Table().Subscribe(t => last_update = t)) {
|
||||
|
||||
var response = h.say_hello(new HelloRequest() { Name = "UnitTest 1" });
|
||||
Assert.AreEqual("Hello UnitTest 1", response.Message);
|
||||
|
||||
@@ -31,10 +31,10 @@ namespace bts.api.core
|
||||
var resp = await _shout.upper_async(new ShoutRequest() { Msg = msg });
|
||||
// Yell so loud you can't hear the last message
|
||||
_gpub.publish(
|
||||
added: new List<HelloLog> { new HelloLog() { Myid = (++id).ToString(), Message = resp.result.MSG } },
|
||||
added: new List<HelloLog> { new HelloLog() { Myid = (++id).ToString(), Message = resp.value.MSG } },
|
||||
removed: new HashSet<string> { (id - 1).ToString() });
|
||||
switch (resp.success) {
|
||||
case true: return new HelloResponse() { Message = resp.result.MSG };
|
||||
case true: return new HelloResponse() { Message = resp.value.MSG };
|
||||
default: return new HelloResponse() { Message = "Sorry {0}. We cannot yell at you right now.".fmt(request.Name) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,9 +50,9 @@ namespace mbts.persist
|
||||
Ns = uns(ns),
|
||||
Key = { key }
|
||||
});
|
||||
check_error(ret.result.Result, ns, key, out bool empty);
|
||||
check_error(ret.value.Result, ns, key, out bool empty);
|
||||
if (empty) return default(T);
|
||||
return deserialize<T>(ret.result.Record.Single().Value);
|
||||
return deserialize<T>(ret.value.Record.Single().Value);
|
||||
}
|
||||
|
||||
private Google.Protobuf.ByteString serialize<T>(T obj) {
|
||||
@@ -90,9 +90,9 @@ namespace mbts.persist
|
||||
new RetrieveAllRequest() {
|
||||
Ns = uns(ns)
|
||||
});
|
||||
check_error(results.result.Result, ns, "", out bool empty);
|
||||
check_error(results.value.Result, ns, "", out bool empty);
|
||||
if (empty) return Enumerable.Empty<PersistResult<T>>();
|
||||
return results.result.Record
|
||||
return results.value.Record
|
||||
.Where(r => re.IsMatch(r.Key))
|
||||
.Select(r => new PersistResult<T>() {
|
||||
user = user(),
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace mbts.ui.settings
|
||||
|
||||
async Task<string[]> get_users(UserService login) {
|
||||
var users = await login.get_users_async(null);
|
||||
if (users.success) return users.result.Users.Select(x => x.Login).ToArray();
|
||||
if (users.success) return users.value.Users.Select(x => x.Login).ToArray();
|
||||
else return new string[0];
|
||||
}
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ namespace mbts.ui.shell
|
||||
_enum_workspace = new PreloginWorkspaceEnumerator(persist);
|
||||
var response = await _logon.get_users_async(new GetUsersRequest());
|
||||
if (response.success) {
|
||||
UserNames = response.result.Users.Select(x => x.Login).ToArray();
|
||||
UserNames = response.value.Users.Select(x => x.Login).ToArray();
|
||||
Array.Sort(UserNames);
|
||||
}
|
||||
else {
|
||||
@@ -127,13 +127,13 @@ namespace mbts.ui.shell
|
||||
Password = password ??""
|
||||
});
|
||||
if (response.success) {
|
||||
if (response.result.IsValid) {
|
||||
if (response.value.IsValid) {
|
||||
_workspace = workspace;
|
||||
set_authenticated_user(username);
|
||||
return (true, "");
|
||||
}
|
||||
else {
|
||||
return (false, response.result.Reason);
|
||||
return (false, response.value.Reason);
|
||||
}
|
||||
}
|
||||
else {
|
||||
|
||||
@@ -19,7 +19,7 @@ namespace mbts.ui.spark
|
||||
|
||||
#region Value
|
||||
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(double), typeof(PriceEntryControl),new FrameworkPropertyMetadata(double.NaN, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceValue));
|
||||
private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((ContractSpecification)d.GetValue(ContractSpecProperty)).round((double)baseValue); }
|
||||
private static object CoerceValue(DependencyObject d, object baseValue) { return TickUtils.get_regional_ticks((ContractSpecificationImmutable)d.GetValue(ContractSpecProperty)).round((double)baseValue); }
|
||||
public double Value { get => (double)GetValue(ValueProperty); set => SetValue(ValueProperty, value); }
|
||||
#endregion
|
||||
|
||||
@@ -36,9 +36,9 @@ namespace mbts.ui.spark
|
||||
#endregion
|
||||
|
||||
#region ContractSpec
|
||||
public static readonly DependencyProperty ContractSpecProperty = DependencyProperty.Register("ContractSpec", typeof(ContractSpecification), typeof(PriceEntryControl), new PropertyMetadata(TickUtils.DefaultSpec, OnContractSpecChanged));
|
||||
public static readonly DependencyProperty ContractSpecProperty = DependencyProperty.Register("ContractSpec", typeof(ContractSpecificationImmutable), typeof(PriceEntryControl), new PropertyMetadata(TickUtils.DefaultSpec, OnContractSpecChanged));
|
||||
private static void OnContractSpecChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { ((PriceEntryControl)d)._update_text_binding(); }
|
||||
public ContractSpecification ContractSpec { get => GetValue(ContractSpecProperty) as ContractSpecification; set => SetValue(ContractSpecProperty, value); }
|
||||
public ContractSpecificationImmutable? ContractSpec { get => GetValue(ContractSpecProperty) as ContractSpecificationImmutable?; set => SetValue(ContractSpecProperty, value); }
|
||||
#endregion
|
||||
|
||||
public PriceEntryControl() {
|
||||
@@ -48,8 +48,8 @@ namespace mbts.ui.spark
|
||||
|
||||
private TextBox _text;
|
||||
|
||||
private void _tick_up() { SetCurrentValue(ValueProperty, ContractSpec.tickup(Value)); }
|
||||
private void _tick_down() { SetCurrentValue(ValueProperty, ContractSpec.tickdown(Value)); }
|
||||
private void _tick_up() { SetCurrentValue(ValueProperty, ContractSpec.HasValue ? ContractSpec.Value.tickup(Value) : Value); }
|
||||
private void _tick_down() { SetCurrentValue(ValueProperty, ContractSpec.HasValue ? ContractSpec.Value.tickdown(Value) : Value); }
|
||||
|
||||
private void _update_text_binding() {
|
||||
if (_text != null) {
|
||||
|
||||
@@ -12,7 +12,7 @@ using static bts.api.Security;
|
||||
|
||||
namespace mbts.ui.spark
|
||||
{
|
||||
public partial class SecuritySelectorControl : Control {
|
||||
partial class SecuritySelectorControl : Control {
|
||||
internal class SecurityCollectionView : ListCollectionView {
|
||||
public SecurityCollectionView(IList list) : base(list) { }
|
||||
private ReadOnlyObservableCollection<object> _base_groups;
|
||||
@@ -79,7 +79,7 @@ namespace mbts.ui.spark
|
||||
|
||||
private bool _suspended;
|
||||
private void _cvg_IsAllSelectedChanged() { if(!_suspended) _refresh_is_all_selected(); }
|
||||
private void _sec_IsSelectedChanged(Security security, bool is_selected) { if (!_suspended) _refresh_is_all_selected(); }
|
||||
private void _sec_IsSelectedChanged(SecurityImmutable security, bool is_selected) { if (!_suspended) _refresh_is_all_selected(); }
|
||||
|
||||
private void _refresh_is_all_selected() {
|
||||
bool? new_ias = _get_is_all_selected();
|
||||
|
||||
@@ -6,15 +6,15 @@ using static bts.api.Security;
|
||||
|
||||
namespace mbts.ui.spark
|
||||
{
|
||||
public partial class SecuritySelectorControl : Control {
|
||||
partial class SecuritySelectorControl : Control {
|
||||
internal class SecurityItem : ViewModelBase, ISelectable
|
||||
{
|
||||
public SecurityItem(Security security, bool is_selected) {
|
||||
public SecurityItem(SecurityImmutable security, bool is_selected) {
|
||||
this.security = security;
|
||||
_is_selected = is_selected;
|
||||
}
|
||||
private bool _is_selected;
|
||||
public Security security { get; private set; }
|
||||
public SecurityImmutable security { get; private set; }
|
||||
public Venue exchange => security.Exchange;
|
||||
public ContractOneofCase type => security.ContractCase;
|
||||
public string symbol => security.ForceSymbol();
|
||||
@@ -30,7 +30,7 @@ namespace mbts.ui.spark
|
||||
}
|
||||
}
|
||||
}
|
||||
public event Action<Security, bool> IsSelectedChanged;
|
||||
public event Action<SecurityImmutable, bool> IsSelectedChanged;
|
||||
public override int GetHashCode() { return security.Id.GetHashCode(); }
|
||||
}
|
||||
}
|
||||
|
||||
+15
-18
@@ -12,48 +12,45 @@ using System.Windows.Data;
|
||||
|
||||
namespace mbts.ui.spark
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for SecuritySelectorControl.xaml
|
||||
/// </summary>
|
||||
public partial class SecuritySelectorControl : Control
|
||||
partial class SecuritySelectorControl : Control
|
||||
{
|
||||
static SecuritySelectorControl() {
|
||||
DefaultStyleKeyProperty.OverrideMetadata(typeof(SecuritySelectorControl), new FrameworkPropertyMetadata(typeof(SecuritySelectorControl)));
|
||||
}
|
||||
|
||||
public SecuritySelectorControl() {
|
||||
SetCurrentValue(SecuritiesProperty, new ObservableCollection<Security>());
|
||||
SetCurrentValue(SelectedSecuritiesProperty, new ObservableCollection<Security>());
|
||||
SetCurrentValue(SecuritiesProperty, new ObservableCollection<SecurityImmutable>());
|
||||
SetCurrentValue(SelectedSecuritiesProperty, new ObservableCollection<SecurityImmutable>());
|
||||
}
|
||||
|
||||
public static readonly DependencyProperty SelectionModeProperty = DependencyProperty.Register("SelectionMode", typeof(SelectionMode), typeof(SecuritySelectorControl), new PropertyMetadata(SelectionMode.Multiple));
|
||||
public SelectionMode SelectionMode { get => (SelectionMode)GetValue(SelectionModeProperty); set => SetValue(SelectionModeProperty, value); }
|
||||
|
||||
#region Securities
|
||||
public static readonly DependencyProperty SecuritiesProperty = DependencyProperty.Register("Securities", typeof(ObservableCollection<Security>), typeof(SecuritySelectorControl), new PropertyMetadata(null, OnSecuritiesChanged));
|
||||
public static readonly DependencyProperty SecuritiesProperty = DependencyProperty.Register("Securities", typeof(ObservableCollection<SecurityImmutable>), typeof(SecuritySelectorControl), new PropertyMetadata(null, OnSecuritiesChanged));
|
||||
private static void OnSecuritiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
|
||||
var securities = e.NewValue as ObservableCollection<Security>;
|
||||
var securities = e.NewValue as ObservableCollection<SecurityImmutable>;
|
||||
if (securities != null) {
|
||||
var target = (SecuritySelectorControl)d;
|
||||
target.InternalSecurityItems = new ObservableAutoWrapper<SecurityItem, Security>(securities, target._create_security_item);
|
||||
target.InternalSecurityItems = new ObservableAutoWrapper<SecurityItem, SecurityImmutable>(securities, target._create_security_item);
|
||||
}
|
||||
}
|
||||
private SecurityItem _create_security_item(Security s) {
|
||||
private SecurityItem _create_security_item(SecurityImmutable s) {
|
||||
var selected_securities = SelectedSecurities;
|
||||
var item = new SecurityItem(s, selected_securities != null && selected_securities.Contains(s));
|
||||
item.IsSelectedChanged += _internal_security_item_IsSelectedChanged;
|
||||
return item;
|
||||
}
|
||||
public ObservableCollection<Security> Securities { get => GetValue(SecuritiesProperty) as ObservableCollection<Security>; set => SetValue(SecuritiesProperty, value); }
|
||||
public ObservableCollection<SecurityImmutable> Securities { get => GetValue(SecuritiesProperty) as ObservableCollection<SecurityImmutable>; set => SetValue(SecuritiesProperty, value); }
|
||||
#endregion
|
||||
|
||||
#region SelectedSecurities
|
||||
public static readonly DependencyProperty SelectedSecuritiesProperty = DependencyProperty.Register("SelectedSecurities", typeof(ObservableCollection<Security>), typeof(SecuritySelectorControl), new PropertyMetadata(null, OnSelectedSecuritiesChanged));
|
||||
public static readonly DependencyProperty SelectedSecuritiesProperty = DependencyProperty.Register("SelectedSecurities", typeof(ObservableCollection<SecurityImmutable>), typeof(SecuritySelectorControl), new PropertyMetadata(null, OnSelectedSecuritiesChanged));
|
||||
private static void OnSelectedSecuritiesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
|
||||
var target = (SecuritySelectorControl)d;
|
||||
var old_val = e.OldValue as ObservableCollection<Security>;
|
||||
var old_val = e.OldValue as ObservableCollection<SecurityImmutable>;
|
||||
if (old_val != null) old_val.CollectionChanged -= target.SelectedSecurities_CollectionChanged;
|
||||
var new_val = e.NewValue as ObservableCollection<Security>;
|
||||
var new_val = e.NewValue as ObservableCollection<SecurityImmutable>;
|
||||
if (new_val != null) {
|
||||
target._selected_securities_changing = true;
|
||||
foreach (var item in target.InternalSecurityItems) item.is_selected = new_val.Contains(item.security);
|
||||
@@ -67,8 +64,8 @@ namespace mbts.ui.spark
|
||||
_selected_securities_changing = true;
|
||||
var items = InternalSecurityItems;
|
||||
switch (e.Action) {
|
||||
case NotifyCollectionChangedAction.Add: foreach (Security s in e.NewItems) items.ApplyToFirst(si => si.security.Equals(s), si => si.is_selected = true); break;
|
||||
case NotifyCollectionChangedAction.Remove: foreach (Security s in e.OldItems) items.ApplyToFirst(si => si.security.Equals(s), si => si.is_selected = false); break;
|
||||
case NotifyCollectionChangedAction.Add: foreach (SecurityImmutable s in e.NewItems) items.ApplyToFirst(si => si.security.Equals(s), si => si.is_selected = true); break;
|
||||
case NotifyCollectionChangedAction.Remove: foreach (SecurityImmutable s in e.OldItems) items.ApplyToFirst(si => si.security.Equals(s), si => si.is_selected = false); break;
|
||||
default:
|
||||
var selected_securities = SelectedSecurities;
|
||||
foreach (SecurityItem si in items) si.is_selected = selected_securities.Contains(si.security);
|
||||
@@ -77,7 +74,7 @@ namespace mbts.ui.spark
|
||||
_selected_securities_changing = false;
|
||||
}
|
||||
}
|
||||
public ObservableCollection<Security> SelectedSecurities { get => GetValue(SelectedSecuritiesProperty) as ObservableCollection<Security>; set => SetValue(SelectedSecuritiesProperty, value); }
|
||||
public ObservableCollection<SecurityImmutable> SelectedSecurities { get => GetValue(SelectedSecuritiesProperty) as ObservableCollection<SecurityImmutable>; set => SetValue(SelectedSecuritiesProperty, value); }
|
||||
#endregion
|
||||
|
||||
#region InternalSecurityItems
|
||||
@@ -96,7 +93,7 @@ namespace mbts.ui.spark
|
||||
}
|
||||
}
|
||||
private void _internal_security_items_ViewDestroyed(SecurityItem item) { item.IsSelectedChanged -= _internal_security_item_IsSelectedChanged; }
|
||||
private void _internal_security_item_IsSelectedChanged(Security security, bool is_selected) {
|
||||
private void _internal_security_item_IsSelectedChanged(SecurityImmutable security, bool is_selected) {
|
||||
if (!_selected_securities_changing) {
|
||||
_selected_securities_changing = true;
|
||||
if (is_selected) SelectedSecurities.Add(security);
|
||||
|
||||
@@ -13,7 +13,7 @@ namespace mbts.ui.spark.converters
|
||||
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
|
||||
var price = (double)values[0];
|
||||
if (HideNaN && double.IsNaN(price)) return string.Empty;
|
||||
var spec = (ContractSpecification)values[1];
|
||||
var spec = (ContractSpecificationImmutable)values[1];
|
||||
return spec.format(price);
|
||||
}
|
||||
|
||||
@@ -25,16 +25,16 @@ namespace mbts.ui.spark.converters
|
||||
internal class TickDisplayTwoWayConverter : IValueConverter
|
||||
{
|
||||
public bool HideNaN { get; set; }
|
||||
public ContractSpecification ContractSpec { get; set; } = new ContractSpecification { CashPerPoint = 1.0, LowTick = 0.01, HighTick = 0.01, PriceBreak = double.MaxValue, PriceMultiplier = 1.0 };
|
||||
public ContractSpecificationImmutable? ContractSpec { get; set; } = new ContractSpecification { CashPerPoint = 1.0, LowTick = 0.01, HighTick = 0.01, PriceBreak = double.MaxValue, PriceMultiplier = 1.0 };
|
||||
|
||||
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
var price = (double)value;
|
||||
if (HideNaN && double.IsNaN(price)) return string.Empty;
|
||||
return ContractSpec.format(price);
|
||||
return ContractSpec.Value.format(price);
|
||||
}
|
||||
|
||||
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
|
||||
return ContractSpec.parse(value as string);
|
||||
return ContractSpec.Value.parse(value as string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,18 +50,18 @@ namespace bts.api.core {
|
||||
return tcs.Task;
|
||||
}
|
||||
|
||||
public unsafe override IObservable<RawUpdate<T>> subscribe<T>(string method_and_qualifier, MessageParser<T> parser) {
|
||||
public unsafe override IObservable<RawUpdate<TOut>> subscribe<TParse,TOut>(string method_and_qualifier, MessageParser<TParse> parser, Func<TParse,TOut> converter) {
|
||||
bool first_update = true;
|
||||
var result = Observable.Create<RawUpdate<T>>(observer => {
|
||||
var result = Observable.Create<RawUpdate<TOut>>(observer => {
|
||||
ApiNativeMethods.raw_subscription_callback cb = (event_type, changes, change_count, unused) => {
|
||||
if (event_type == ApiNativeMethods.EventType.TABLE_UPDATED) {
|
||||
var added_items = new List<T>(change_count);
|
||||
var added_items = new List<TOut>(change_count);
|
||||
var added_keys = new List<int>(change_count);
|
||||
var removed_keys = new List<int>(change_count);
|
||||
foreach (var change in changes) {
|
||||
if (change.type != ApiNativeMethods.ChangeType.REMOVE) {
|
||||
// create or change
|
||||
added_items.Add(parser.ParseFrom(new UnmanagedMemoryStream(change.buffer, change.buffer_len)));
|
||||
added_items.Add( converter( parser.ParseFrom(new UnmanagedMemoryStream(change.buffer, change.buffer_len))));
|
||||
added_keys.Add(change.key);
|
||||
}
|
||||
if (change.type != ApiNativeMethods.ChangeType.CREATE) {
|
||||
@@ -69,11 +69,11 @@ namespace bts.api.core {
|
||||
removed_keys.Add(change.key);
|
||||
}
|
||||
}
|
||||
observer.OnNext(new RawUpdate<T>(added_items, added_keys, removed_keys));
|
||||
observer.OnNext(new RawUpdate<TOut>(added_items, added_keys, removed_keys));
|
||||
}
|
||||
else if (event_type == ApiNativeMethods.EventType.TABLE_CREATED) {
|
||||
if (!first_update) {
|
||||
observer.OnNext(RawUpdate<T>.Reset());
|
||||
observer.OnNext(RawUpdate<TOut>.Reset());
|
||||
}
|
||||
first_update = false;
|
||||
}
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
using Google.Protobuf;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bts.api.core {
|
||||
internal abstract class ClientChannel : IDisposable
|
||||
using Google.Protobuf;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bts.api.core {
|
||||
internal abstract class ClientChannel : IDisposable
|
||||
{
|
||||
readonly ServiceContext _context;
|
||||
|
||||
public ClientChannel(ServiceContext context) {
|
||||
_context = context;
|
||||
}
|
||||
public abstract void Dispose();
|
||||
public abstract Task<Result<Response>> send<Request, Response>(int method_id, Request request)
|
||||
}
|
||||
public abstract void Dispose();
|
||||
public abstract Task<Result<Response>> send<Request, Response>(int method_id, Request request)
|
||||
where Request: IImmutableMessage where Response : class,IMessage,new();
|
||||
public abstract IObservable<RawUpdate<T>> subscribe<T>(string method_and_qualifier, MessageParser<T> parser)
|
||||
where T : IMessage<T>;
|
||||
|
||||
public abstract bool is_sync_call_ok();
|
||||
}
|
||||
}
|
||||
public abstract IObservable<RawUpdate<TOut>> subscribe<TParse,TOut>(string method_and_qualifier, MessageParser<TParse> parser, Func<TParse,TOut> converter=null)
|
||||
where TParse : IMessage<TParse>;
|
||||
|
||||
public abstract bool is_sync_call_ok();
|
||||
}
|
||||
}
|
||||
@@ -3,44 +3,44 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bts.api.core
|
||||
{
|
||||
|
||||
public struct Result<T>
|
||||
{
|
||||
public Result(T v) {
|
||||
_result = v;
|
||||
_code = ApiError.Success;
|
||||
}
|
||||
public Result(ApiError code) {
|
||||
System.Diagnostics.Debug.Assert(code != ApiError.Success);
|
||||
_code = code;
|
||||
_result = default(T);
|
||||
}
|
||||
|
||||
private string error_string(ApiError code) {
|
||||
switch (code) {
|
||||
case ApiError.Success: return "Success";
|
||||
case ApiError.NoServer: return "No server found.";
|
||||
case ApiError.ServerDisconnect: return "Server disconnected.";
|
||||
case ApiError.MissingMethod: return "Method not found.";
|
||||
case ApiError.ServerFault: return "Server error.";
|
||||
default: return "Unknown error";
|
||||
}
|
||||
}
|
||||
|
||||
readonly T _result;
|
||||
readonly ApiError _code;
|
||||
|
||||
public T result {
|
||||
get {
|
||||
if (success) return _result;
|
||||
else throw new ApiException(error_message);
|
||||
}
|
||||
}
|
||||
public bool success { get { return _code == ApiError.Success; } }
|
||||
public ApiError code { get { return _code; } }
|
||||
public string error_message { get { return error_string(_code); } }
|
||||
}
|
||||
}
|
||||
|
||||
namespace bts.api.core
|
||||
{
|
||||
|
||||
public struct Result<T>
|
||||
{
|
||||
public Result(T v) {
|
||||
_result = v;
|
||||
_code = ApiError.Success;
|
||||
}
|
||||
public Result(ApiError code) {
|
||||
System.Diagnostics.Debug.Assert(code != ApiError.Success);
|
||||
_code = code;
|
||||
_result = default(T);
|
||||
}
|
||||
|
||||
private string error_string(ApiError code) {
|
||||
switch (code) {
|
||||
case ApiError.Success: return "Success";
|
||||
case ApiError.NoServer: return "No server found.";
|
||||
case ApiError.ServerDisconnect: return "Server disconnected.";
|
||||
case ApiError.MissingMethod: return "Method not found.";
|
||||
case ApiError.ServerFault: return "Server error.";
|
||||
default: return "Unknown error";
|
||||
}
|
||||
}
|
||||
|
||||
readonly T _result;
|
||||
readonly ApiError _code;
|
||||
|
||||
public T value {
|
||||
get {
|
||||
if (success) return _result;
|
||||
else throw new ApiException(error_message);
|
||||
}
|
||||
}
|
||||
public bool success { get { return _code == ApiError.Success; } }
|
||||
public ApiError code { get { return _code; } }
|
||||
public string error_message { get { return error_string(_code); } }
|
||||
}
|
||||
}
|
||||
@@ -1,85 +1,85 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
namespace bts.api.core {
|
||||
|
||||
public struct RawUpdate<T> {
|
||||
// RawUpdate uses List<T> instead of IReadonlyList to avoid virtual dispatch on a type not likely to be see in a public api surface
|
||||
public RawUpdate(List<T> added_items, List<int> added_keys, List<int> removed_keys) : this() {
|
||||
is_reset = false;
|
||||
this.added_items = added_items;
|
||||
this.added_keys = added_keys;
|
||||
this.removed_keys = removed_keys;
|
||||
}
|
||||
|
||||
public static RawUpdate<T> Reset() {
|
||||
return new RawUpdate<T>() { is_reset = true };
|
||||
}
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
public bool is_reset;
|
||||
public List<T> added_items { get; private set; }
|
||||
public List<int> added_keys { get; private set; }
|
||||
public List<int> removed_keys { get; private set; }
|
||||
}
|
||||
|
||||
public class Update<T, TKey> where TKey : IEquatable<TKey> {
|
||||
private Func<T, TKey> _key;
|
||||
public Update(IEnumerable<T> all, IReadOnlyList<T> added, IReadOnlyList<T> removed, Func<T, TKey> key_extractor) {
|
||||
this.added = added;
|
||||
this.removed = removed;
|
||||
this.all = all;
|
||||
_key = key_extractor;
|
||||
}
|
||||
|
||||
public IEnumerable<T> all { get; private set; }
|
||||
public IReadOnlyList<T> added { get; private set; }
|
||||
public IReadOnlyList<T> removed { get; private set; }
|
||||
|
||||
public TKey key(T t) { return _key(t); }
|
||||
}
|
||||
|
||||
public class TableUpdate<T, TKey> where TKey : IEquatable<TKey> {
|
||||
|
||||
readonly Dictionary<TKey, T> _state;
|
||||
readonly IReadOnlyList<T> _added;
|
||||
readonly IReadOnlyList<T> _removed;
|
||||
|
||||
internal TableUpdate(Dictionary<TKey, T> init, IReadOnlyList<T> added, IReadOnlyList<T> removed) {
|
||||
_state = init;
|
||||
_added = added;
|
||||
_removed = removed;
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<TKey, T> state { get { return _state; } }
|
||||
public IReadOnlyList<T> added { get { return _added; } }
|
||||
public IReadOnlyList<T> removed { get { return _removed; } }
|
||||
|
||||
public TableUpdate<T, TKey> update(Update<T, TKey> update) {
|
||||
var table = new TableUpdate<T, TKey>(new Dictionary<TKey, T>(_state), update.added, update.removed);
|
||||
foreach (var i in update.removed) {
|
||||
table._state.Remove(update.key(i));
|
||||
}
|
||||
foreach (var item in update.added) {
|
||||
table._state.Add(update.key(item), item);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ObservableUpdateExtensions {
|
||||
public static IObservable<Update<T, TKey>> reconstitute<T, TKey>(this IObservable<RawUpdate<T>> source, Func<T, TKey> key_extractor) where TKey : IEquatable<TKey> {
|
||||
var state = new Dictionary<int, T>();
|
||||
return source.Select(raw => {
|
||||
namespace bts.api.core {
|
||||
|
||||
public struct RawUpdate<T> {
|
||||
// RawUpdate uses List<T> instead of IReadonlyList to avoid virtual dispatch on a type not likely to be see in a public api surface
|
||||
public RawUpdate(List<T> added_items, List<int> added_keys, List<int> removed_keys) : this() {
|
||||
is_reset = false;
|
||||
this.added_items = added_items;
|
||||
this.added_keys = added_keys;
|
||||
this.removed_keys = removed_keys;
|
||||
}
|
||||
|
||||
public static RawUpdate<T> Reset() {
|
||||
return new RawUpdate<T>() { is_reset = true };
|
||||
}
|
||||
|
||||
|
||||
public bool is_reset;
|
||||
public List<T> added_items { get; private set; }
|
||||
public List<int> added_keys { get; private set; }
|
||||
public List<int> removed_keys { get; private set; }
|
||||
}
|
||||
|
||||
public class Update<T, TKey> where TKey : IEquatable<TKey> {
|
||||
private Func<T, TKey> _key;
|
||||
public Update(IReadOnlyCollection<T> all, IReadOnlyList<T> added, IReadOnlyList<T> removed, Func<T, TKey> key_extractor) {
|
||||
this.added = added;
|
||||
this.removed = removed;
|
||||
this.all = all;
|
||||
_key = key_extractor;
|
||||
}
|
||||
|
||||
public IReadOnlyCollection<T> all { get; private set; }
|
||||
public IReadOnlyList<T> added { get; private set; }
|
||||
public IReadOnlyList<T> removed { get; private set; }
|
||||
|
||||
public TKey key(T t) { return _key(t); }
|
||||
}
|
||||
|
||||
public class TableUpdate<T, TKey> where TKey : IEquatable<TKey> {
|
||||
|
||||
readonly Dictionary<TKey, T> _state;
|
||||
readonly IReadOnlyList<T> _added;
|
||||
readonly IReadOnlyList<T> _removed;
|
||||
|
||||
internal TableUpdate(Dictionary<TKey, T> init, IReadOnlyList<T> added, IReadOnlyList<T> removed) {
|
||||
_state = init;
|
||||
_added = added;
|
||||
_removed = removed;
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<TKey, T> state { get { return _state; } }
|
||||
public IReadOnlyList<T> added { get { return _added; } }
|
||||
public IReadOnlyList<T> removed { get { return _removed; } }
|
||||
|
||||
public TableUpdate<T, TKey> update(Update<T, TKey> update) {
|
||||
var table = new TableUpdate<T, TKey>(new Dictionary<TKey, T>(_state), update.added, update.removed);
|
||||
foreach (var i in update.removed) {
|
||||
table._state.Remove(update.key(i));
|
||||
}
|
||||
foreach (var item in update.added) {
|
||||
table._state.Add(update.key(item), item);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ObservableUpdateExtensions {
|
||||
public static IObservable<Update<T, TKey>> reconstitute<T, TKey>(this IObservable<RawUpdate<T>> source, Func<T, TKey> key_extractor) where TKey : IEquatable<TKey> {
|
||||
var state = new Dictionary<int, T>();
|
||||
return source.Select(raw => {
|
||||
if (raw.is_reset) {
|
||||
var removed = state.Values.ToList();
|
||||
state.Clear();
|
||||
return new Update<T, TKey>(new T[0], new T[0], removed, key_extractor);
|
||||
}
|
||||
}
|
||||
else {
|
||||
var removed = new List<T>(raw.removed_keys.Count);
|
||||
foreach (var r in raw.removed_keys) {
|
||||
@@ -93,14 +93,14 @@ namespace bts.api.core {
|
||||
state[raw.added_keys[x]] = raw.added_items[x];
|
||||
}
|
||||
return new Update<T, TKey>(state.Values, raw.added_items, removed, key_extractor);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static IObservable<TableUpdate<T,TKey>> table<T,TKey>(this IObservable<Update<T,TKey>> source) where TKey : IEquatable<TKey> {
|
||||
return source.Scan(
|
||||
new TableUpdate<T,TKey>(new Dictionary<TKey, T>(), new List<T>(), new List<T>()),
|
||||
(table, update) => table.update(update));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static IObservable<TableUpdate<T,TKey>> Table<T,TKey>(this IObservable<Update<T,TKey>> source) where TKey : IEquatable<TKey> {
|
||||
return source.Scan(
|
||||
new TableUpdate<T,TKey>(new Dictionary<TKey, T>(), new List<T>(), new List<T>()),
|
||||
(table, update) => table.update(update));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,12 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using static bts.api.SecurityFormatter;
|
||||
using static bts.api.Security;
|
||||
using security_key = System.UInt32;
|
||||
|
||||
namespace bts.api {
|
||||
public partial class Security : IFormattable {
|
||||
|
||||
private static readonly PartFormattingTuple[] _standard_format = new[] {
|
||||
internal static readonly PartFormattingTuple[] _standard_format = new[] {
|
||||
new PartFormattingTuple(ContractParts.Name, "!"),
|
||||
new PartFormattingTuple(ContractParts.Quantity),
|
||||
new PartFormattingTuple(ContractParts.Symbol, "."),
|
||||
@@ -19,34 +20,49 @@ namespace bts.api {
|
||||
return Format(this, string.IsNullOrEmpty(format) ? _standard_format : Parse(format));
|
||||
}
|
||||
|
||||
internal static readonly Security Empty = new Security {
|
||||
Exchange = Venue.Bts,
|
||||
ContractSpec = new ContractSpecification { CashPerPoint = double.NaN, HighTick = double.NaN, LowTick = double.NaN, PriceBreak = double.NaN, PriceMultiplier = double.NaN }
|
||||
};
|
||||
|
||||
public static security_key key(Security s) { return s.Id; }
|
||||
}
|
||||
|
||||
partial struct SecurityImmutable : IComparable<SecurityImmutable> {
|
||||
public int CompareTo(SecurityImmutable other) {
|
||||
return Id.CompareTo(other.Id);
|
||||
}
|
||||
public string ToString(string format, IFormatProvider formatProvider=null) {
|
||||
return Format(this, string.IsNullOrEmpty(format) ? _standard_format : Parse(format));
|
||||
}
|
||||
|
||||
partial void EqualsOverride(ref bool didrun, ref bool result, SecurityImmutable other) {
|
||||
didrun = true;
|
||||
result = Id == other.Id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Traverses the security to get the leaf
|
||||
/// exchange securities
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<Tuple<uint, Side, double>> get_base_exchange_securities ()
|
||||
internal IEnumerable<Tuple<uint, Side, double>> get_base_exchange_securities ()
|
||||
{
|
||||
List<Tuple<uint, Side, double>> rv = new List<Tuple<uint,Side,double>> ();
|
||||
get_base_exchange_securities (this, Side.Buy, 1.0, ref rv);
|
||||
return rv;
|
||||
}
|
||||
|
||||
private static void get_base_exchange_securities (Security sec, Side side, double mult, ref List<Tuple<uint, Side, double>> legs)
|
||||
private static void get_base_exchange_securities (SecurityImmutable sec, Side side, double mult, ref List<Tuple<uint, Side, double>> legs)
|
||||
{
|
||||
Func<Side, Side, Side> resolve_side = (s1, s2) => ((s1 == Side.Buy ? 1 : -1) * (s2 == Side.Buy ? 1 : -1)) == 1 ? Side.Buy : Side.Sell;
|
||||
if (sec.ContractCase == ContractOneofCase.Future)
|
||||
legs.Add (Tuple.Create (sec.Id, side, mult));
|
||||
else if (sec.ContractCase == ContractOneofCase.Spread)
|
||||
foreach (ContractLeg leg in sec.Spread.Legs)
|
||||
foreach (ContractLegImmutable leg in sec.Spread.Legs)
|
||||
get_base_exchange_securities (leg.Security, resolve_side (side, leg.Side), leg.Quantity * mult, ref legs);
|
||||
else if (sec.ContractCase == ContractOneofCase.Synthetic)
|
||||
foreach (ContractLeg leg in sec.Synthetic.Legs)
|
||||
foreach (ContractLegImmutable leg in sec.Synthetic.Legs)
|
||||
get_base_exchange_securities (leg.Security, resolve_side (side, leg.Side), leg.Quantity * mult, ref legs);
|
||||
}
|
||||
|
||||
public static readonly Security Empty = new Security {
|
||||
Exchange = Venue.Bts,
|
||||
ContractSpec = new ContractSpecification { CashPerPoint = double.NaN, HighTick = double.NaN, LowTick = double.NaN, PriceBreak = double.NaN, PriceMultiplier = double.NaN }
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using FutureLeg = System.Tuple<bts.api.Venue, string, bts.api.FutureContract, int>;
|
||||
using FutureLeg = System.Tuple<bts.api.Venue, string, bts.api.FutureContractImmutable, int>;
|
||||
|
||||
namespace bts.api
|
||||
{
|
||||
@@ -16,7 +16,7 @@ namespace bts.api
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
public static string Format(Security s, IEnumerable<PartFormattingTuple> parts) {
|
||||
public static string Format(SecurityImmutable s, IEnumerable<PartFormattingTuple> parts) {
|
||||
var part_formatters = parts.Select(p => PartFormatterFactory.get_formatter(p)).ToList();
|
||||
switch(s.ContractCase) {
|
||||
case Security.ContractOneofCase.Future: return _format_future(s, part_formatters);
|
||||
@@ -52,11 +52,11 @@ namespace bts.api
|
||||
}
|
||||
}
|
||||
|
||||
private static string _format_future(Security s, IEnumerable<IPartFormatter> part_formatters) { return _format(s, part_formatters, _add_future); }
|
||||
private static string _format_future(SecurityImmutable s, IEnumerable<IPartFormatter> part_formatters) { return _format(s, part_formatters, _add_future); }
|
||||
private static string _format_future_leg(FutureLeg l, IEnumerable<IPartFormatter> part_formatters) { return _format(l, part_formatters, _add_future_leg); }
|
||||
|
||||
private delegate bool AddPart<T>(T t, IPartFormatter part_formatter, out string result);
|
||||
private static bool _add_future(Security s, IPartFormatter part_formatter, out string result) { return part_formatter.add_part(s, out result); }
|
||||
private static bool _add_future(SecurityImmutable s, IPartFormatter part_formatter, out string result) { return part_formatter.add_part(s, out result); }
|
||||
private static bool _add_future_leg(FutureLeg l, IPartFormatter part_formatter, out string result) { return part_formatter.add_part(l, out result); }
|
||||
|
||||
private static string _format<T>(T t, IEnumerable<IPartFormatter> part_formatters, AddPart<T> add_part) {
|
||||
@@ -77,7 +77,7 @@ namespace bts.api
|
||||
{
|
||||
string separator { get; }
|
||||
bool add_part(FutureLeg fl, out string result);
|
||||
bool add_part(Security s, out string result);
|
||||
bool add_part(SecurityImmutable s, out string result);
|
||||
}
|
||||
|
||||
private static class PartFormatterFactory
|
||||
@@ -122,7 +122,7 @@ namespace bts.api
|
||||
result = null;
|
||||
return false;
|
||||
}
|
||||
public bool add_part(Security s, out string result) {
|
||||
public bool add_part(SecurityImmutable s, out string result) {
|
||||
if (s.ContractCase == Security.ContractOneofCase.Synthetic) {
|
||||
result = s.Synthetic.Name;
|
||||
return true;
|
||||
@@ -150,7 +150,7 @@ namespace bts.api
|
||||
}
|
||||
return true;
|
||||
}
|
||||
public bool add_part(Security s, out string result) {
|
||||
public bool add_part(SecurityImmutable s, out string result) {
|
||||
result = null;
|
||||
return false;
|
||||
}
|
||||
@@ -161,24 +161,24 @@ namespace bts.api
|
||||
}
|
||||
public string separator { get; }
|
||||
public bool add_part(FutureLeg fl, out string result) { result = fl.Item2; return true; }
|
||||
public bool add_part(Security s, out string result) { result = s.Symbol; return true; }
|
||||
public bool add_part(SecurityImmutable s, out string result) { result = s.Symbol; return true; }
|
||||
}
|
||||
private class Formatter<T> : IPartFormatter {
|
||||
public Formatter(Func<Security, T> get_sec_value, Func<FutureLeg, T> get_leg_value, string separator) : this(get_sec_value, get_leg_value, t => t.ToString(), separator) { }
|
||||
public Formatter(Func<Security, T> get_sec_value, Func<FutureLeg, T> get_leg_value, Func<T, string> format, string separator) {
|
||||
public Formatter(Func<SecurityImmutable, T> get_sec_value, Func<FutureLeg, T> get_leg_value, string separator) : this(get_sec_value, get_leg_value, t => t.ToString(), separator) { }
|
||||
public Formatter(Func<SecurityImmutable, T> get_sec_value, Func<FutureLeg, T> get_leg_value, Func<T, string> format, string separator) {
|
||||
_get_sec_value = get_sec_value;
|
||||
_get_leg_value = get_leg_value;
|
||||
_format = format;
|
||||
_separator = separator;
|
||||
}
|
||||
private readonly Func<Security, T> _get_sec_value;
|
||||
private readonly Func<SecurityImmutable, T> _get_sec_value;
|
||||
private readonly Func<FutureLeg, T> _get_leg_value;
|
||||
private readonly Func<T, string> _format;
|
||||
private readonly string _separator;
|
||||
private T _last_val;
|
||||
|
||||
public string separator => _separator ?? string.Empty;
|
||||
public bool add_part(Security s, out string result) {
|
||||
public bool add_part(SecurityImmutable s, out string result) {
|
||||
T val = _get_sec_value(s);
|
||||
if (!val.Equals(_last_val)) {
|
||||
result = _format(_last_val = val);
|
||||
|
||||
@@ -3,14 +3,14 @@ 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 FutureLeg = System.Tuple<bts.api.Venue, string, bts.api.FutureContractImmutable, int>;
|
||||
|
||||
namespace bts.api
|
||||
{
|
||||
internal static class SecurityHelper
|
||||
{
|
||||
#region Private Members
|
||||
private static IEnumerable<FutureLeg> _get_flat_future_legs(RepeatedField<ContractLeg> legs, int qty) {
|
||||
private static IEnumerable<FutureLeg> _get_flat_future_legs(IEnumerable<ContractLegImmutable> legs, int qty) {
|
||||
foreach (var l in legs) {
|
||||
switch (l.Security.ContractCase) {
|
||||
case ContractOneofCase.Future: yield return new FutureLeg(l.Security.Exchange, l.Security.Symbol, l.Security.Future, qty * l.SignedQuantity()); break;
|
||||
@@ -26,7 +26,7 @@ namespace bts.api
|
||||
}
|
||||
#endregion
|
||||
|
||||
public static IEnumerable<FutureLeg> get_flat_future_legs(Security sec) {
|
||||
public static IEnumerable<FutureLeg> get_flat_future_legs(SecurityImmutable sec) {
|
||||
switch (sec.ContractCase) {
|
||||
case ContractOneofCase.Spread: return _get_flat_future_legs(sec.Spread.Legs, 1);
|
||||
case ContractOneofCase.Synthetic: return _get_flat_future_legs(sec.Synthetic.Legs, 1);
|
||||
@@ -37,21 +37,21 @@ 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); }
|
||||
public static DateTime RawExpDate(this FutureContractImmutable future) { return new DateTime((int)future.ExpirationYear, (int)future.ExpirationMonth, (int)future.ExpirationDay); }
|
||||
|
||||
// TODO: Remove (probably do not need MappedExpDates in spark)
|
||||
public static DateTime MappedExpDate(this FutureContract future) {
|
||||
internal static DateTime MappedExpDate(this FutureContractImmutable future) {
|
||||
return RawExpDate(future);
|
||||
}
|
||||
|
||||
public static int SignedQuantity(this ContractLeg leg) { return leg.Side == Side.Buy ? (int)leg.Quantity : -(int)leg.Quantity; }
|
||||
internal static int SignedQuantity(this ContractLegImmutable leg) { return leg.Side == Side.Buy ? (int)leg.Quantity : -(int)leg.Quantity; }
|
||||
|
||||
public static string ForceSymbol(this Security security) {
|
||||
internal static string ForceSymbol(this SecurityImmutable security) {
|
||||
if (security.ContractCase == ContractOneofCase.Synthetic) return ForceSymbol(security.Synthetic.Legs.First().Security);
|
||||
else return security.Symbol;
|
||||
}
|
||||
|
||||
public static string DisplayExchange(this Security security) {
|
||||
public static string DisplayExchange(this SecurityImmutable 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
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bts {
|
||||
namespace bts.api {
|
||||
internal interface IImmutableMessage {
|
||||
MessageDescriptor Descriptor { get; }
|
||||
int CalculateSize();
|
||||
@@ -77,11 +77,19 @@ EnumModel = namedtuple("EnumModel", "name values")
|
||||
def transform_enum(e):
|
||||
return EnumModel(e.name, [])
|
||||
|
||||
MessageModel = namedtuple("MessageModel", "name field nested_type nested_enum")
|
||||
OneofModel = namedtuple("OneofModel", "name Name")
|
||||
def transform_oneof(o, msg):
|
||||
return OneofModel(
|
||||
name = o.name,
|
||||
Name = o.name[0].upper() + o.name[1:]
|
||||
)
|
||||
|
||||
MessageModel = namedtuple("MessageModel", "name field oneof nested_type nested_enum")
|
||||
def transform_message(i):
|
||||
r = MessageModel(
|
||||
name = i.name,
|
||||
field = [transform_field(f,i) for f in i.field],
|
||||
oneof = [transform_oneof(o,i) for o in i.oneof_decl],
|
||||
nested_type = [transform_message(m) for m in i.nested_type],
|
||||
nested_enum = [transform_enum(e) for e in i.enum_type],
|
||||
)
|
||||
@@ -98,12 +106,11 @@ def transform_service(service, keymap):
|
||||
|
||||
FileModel = namedtuple("FileModel", "name package namespace_csharp message_type service enum_type")
|
||||
def transform_file(p, keymap):
|
||||
message_types = [transform_message(m) for m in p.message_type]
|
||||
return FileModel(
|
||||
name = p.name,
|
||||
package = p.package,
|
||||
namespace_csharp = p.package,
|
||||
message_type = message_types,
|
||||
message_type = [transform_message(m) for m in p.message_type],
|
||||
service = [transform_service(s, keymap) for s in p.service],
|
||||
enum_type = [transform_enum(e) for e in p.enum_type]
|
||||
)
|
||||
@@ -206,7 +213,6 @@ def generate_insertions(params, request, response):
|
||||
def camel_case(item):
|
||||
if item.isupper() and not '_' in item: return item
|
||||
return item.title().replace('_', '')
|
||||
|
||||
return d
|
||||
|
||||
def generate_code(request, response):
|
||||
|
||||
@@ -20,20 +20,37 @@ public sealed class {{name}} : IApiClient, IDisposable {
|
||||
{{#if server_streaming}}
|
||||
// {{comment}}
|
||||
public IObservable<Update<{{output_type_full}},{{key_type.cstype}}>> subscribe_{{name}}({{input_type_full}} qualifier=null) {
|
||||
return _channel.subscribe<{{output_type_full}}>(ApiServer.format_qualifier("{{name}}",qualifier), {{output_type_full}}.Parser).reconstitute(key);
|
||||
return _channel.subscribe<{{output_type_full}}, {{output_type_full}}>(ApiServer.format_qualifier("{{name}}",qualifier), {{output_type_full}}.Parser, a=>a).reconstitute(key);
|
||||
}
|
||||
internal IObservable<Update<{{output_type_full}}Immutable,{{key_type.cstype}}>> subscribei_{{name}}({{input_type_full}} qualifier=null) {
|
||||
return _channel.subscribe<{{output_type_full}}, {{output_type_full}}Immutable>(ApiServer.format_qualifier("{{name}}",qualifier), {{output_type_full}}.Parser, a=>({{output_type_full}}Immutable)a).reconstitute(key);
|
||||
}
|
||||
private static {{key_type.cstype}} key({{output_type_full}} row) {
|
||||
return row.{{camel key_field}};
|
||||
}
|
||||
private static {{key_type.cstype}} key({{output_type_full}}Immutable row) {
|
||||
return row.{{camel key_field}};
|
||||
}
|
||||
{{else}}
|
||||
// {{comment}}
|
||||
public Task<Result<{{output_type_full}}>> {{name}}_async({{input_type_full}} request) {
|
||||
return _channel.send<{{input_type_full}},{{output_type_full}}>({{@index}}, request);
|
||||
}
|
||||
internal Task<Result<{{output_type_full}}>> {{name}}_async({{input_type_full}}Immutable request) {
|
||||
return _channel.send<{{input_type_full}}Immutable,{{output_type_full}}>({{@index}}, request);
|
||||
}
|
||||
// {{comment}}
|
||||
public {{output_type_full}} {{name}}({{input_type_full}} request) {
|
||||
if (_channel.is_sync_call_ok()) {
|
||||
return {{name}}_async(request).Result.result;
|
||||
return {{name}}_async(request).Result.value;
|
||||
}
|
||||
else {
|
||||
throw new bts.api.core.ApiException("API blocking call cannot be made on this thread. Please use {{name}}_async instead.");
|
||||
}
|
||||
}
|
||||
internal {{output_type_full}} {{name}}({{input_type_full}}Immutable request) {
|
||||
if (_channel.is_sync_call_ok()) {
|
||||
return {{name}}_async(request).Result.value;
|
||||
}
|
||||
else {
|
||||
throw new bts.api.core.ApiException("API blocking call cannot be made on this thread. Please use {{name}}_async instead.");
|
||||
|
||||
@@ -8,14 +8,14 @@ using Google.Protobuf.WellKnownTypes;
|
||||
|
||||
namespace {{package}} {
|
||||
{{#each message_type}}
|
||||
partial class {{name}} : bts.IImmutableMessage {
|
||||
MessageDescriptor bts.IImmutableMessage.Descriptor => {{name}}.Descriptor;
|
||||
partial class {{name}} : bts.api.IImmutableMessage {
|
||||
MessageDescriptor bts.api.IImmutableMessage.Descriptor => {{name}}.Descriptor;
|
||||
}
|
||||
partial struct {{name}}Immutable : bts.IImmutableMessage {
|
||||
partial struct {{name}}Immutable : bts.api.IImmutableMessage {
|
||||
readonly {{name}} _impl;
|
||||
|
||||
public static MessageDescriptor Descriptor => {{name}}.Descriptor;
|
||||
MessageDescriptor bts.IImmutableMessage.Descriptor => {{name}}.Descriptor;
|
||||
MessageDescriptor bts.api.IImmutableMessage.Descriptor => {{name}}.Descriptor;
|
||||
public int CalculateSize() => _impl.CalculateSize();
|
||||
public void WriteTo(CodedOutputStream output) => _impl.WriteTo(output);
|
||||
|
||||
@@ -42,8 +42,12 @@ namespace {{package}} {
|
||||
public bool Equals({{name}}Immutable other) {
|
||||
return _impl.Equals(other._impl);
|
||||
}
|
||||
partial void EqualsOverride(ref bool didrun, ref bool result, {{name}}Immutable other);
|
||||
public bool Equals({{name}}Immutable? other) {
|
||||
if (other == null) return false;
|
||||
bool didrun = false, result = false;
|
||||
EqualsOverride(ref didrun, ref result, other.Value);
|
||||
if (didrun) return result;
|
||||
return _impl.Equals(other.Value._impl);
|
||||
}
|
||||
public override int GetHashCode() => _impl.GetHashCode();
|
||||
@@ -61,13 +65,18 @@ namespace {{package}} {
|
||||
{{else}}
|
||||
{{#if type.islist}}
|
||||
// Can remove the cast if immutable==cstype
|
||||
public IEnumerable<{{type.immutable}}> {{Name}} => _impl.{{Name}}.Cast<{{type.immutable}}>();
|
||||
public IEnumerable<{{type.immutable}}> {{Name}} => _impl.{{Name}}.Select(t => ({{type.immutable}})t);
|
||||
{{else}}
|
||||
public {{type.immutable}} {{Name}} => ({{type.immutable}})_impl.{{Name}};
|
||||
{{/if}}
|
||||
{{/if}}
|
||||
|
||||
{{/each}}
|
||||
|
||||
// oneof enums
|
||||
{{#each oneof}}
|
||||
public {{../name}}.{{Name}}OneofCase {{Name}}Case => _impl.{{Name}}Case;
|
||||
{{/each}}
|
||||
|
||||
public {{name}}Immutable with(
|
||||
// Arguments
|
||||
|
||||
@@ -142,7 +142,7 @@ size_t LoggerHub::consume_log_recs()
|
||||
size_t consumed = 0;
|
||||
for (size_t i = 0; i < me->loggers.size();i++) {
|
||||
auto &l = me->loggers[i];
|
||||
l->unqueue([&l,&to_keep,i,&consumed,this] (std::thread::id tid, bool active,
|
||||
l->unqueue([&l,&to_keep,&consumed,this] (std::thread::id tid, bool active,
|
||||
size_t dropped_msg_count,
|
||||
size_t logged_msg_count,
|
||||
std::vector<LogRec> &msgs) {
|
||||
|
||||
@@ -203,7 +203,7 @@ TEST_CASE("Quickbus Pubsub Tests","[quickbus]")
|
||||
bool sub2_got_a = false;
|
||||
bool sub2_got_b = false;
|
||||
auto f2 = p2.get_future();
|
||||
TableSubscriber sub2 (qb,equal_topic(Topic("A")),[&p2,&sub2_got_b,&sub2_got_a] (TableEvent const&ev) {
|
||||
TableSubscriber sub2 (qb,equal_topic(Topic("A")),[&sub2_got_b,&sub2_got_a] (TableEvent const&ev) {
|
||||
if (ev.event_type == TableEvent::TABLE_UPDATED) {
|
||||
REQUIRE(ev.update);
|
||||
REQUIRE(ev.update->size() == 1);
|
||||
|
||||
@@ -29,7 +29,7 @@ message Order {
|
||||
}
|
||||
TimeInForce time_in_force = 50;
|
||||
uint64 timestamp = 60;
|
||||
oneof algo_order_type {
|
||||
oneof AlgoOrderType {
|
||||
MarketOrder market_order = 100;
|
||||
LimitOrder limit_order = 110;
|
||||
StopMarketOrder stop_market_order = 120;
|
||||
@@ -144,7 +144,7 @@ message BTSShootTillHitOrder
|
||||
/// Only support a limit or market as Retry's
|
||||
/// We can make Retry a general parameter for
|
||||
/// every order
|
||||
oneof native_order_type
|
||||
oneof NativeOrderType
|
||||
{
|
||||
MarketOrder market_order = 10;
|
||||
LimitOrder limit_order = 20;
|
||||
@@ -171,7 +171,7 @@ message BTSWithATickParameters
|
||||
message BTSWithATickOrder
|
||||
{
|
||||
BTSWithATickParameters order_parameters = 10;
|
||||
oneof native_order_type
|
||||
oneof NativeOrderType
|
||||
{
|
||||
LimitOrder limit_order = 20;
|
||||
}
|
||||
@@ -202,7 +202,7 @@ message BTSTimedWindowParameters
|
||||
message BTSTimedWindowOrder
|
||||
{
|
||||
BTSTimedWindowParameters order_parameters = 10;
|
||||
oneof native_order_type
|
||||
oneof NativeOrderType
|
||||
{
|
||||
MarketOrder market_order = 20;
|
||||
LimitOrder limit_order = 30;
|
||||
@@ -245,12 +245,12 @@ When the market penetrates the trigger price, a limit order is sent "payup" tick
|
||||
message BTSStopOrder
|
||||
{
|
||||
PriceTrigger price_trigger = 10;
|
||||
oneof native_trigger_order_type
|
||||
oneof NativeTriggerOrderType
|
||||
{
|
||||
MarketOrder market_order = 20;
|
||||
LimitOrder limit_order = 30;
|
||||
}
|
||||
oneof trigger_order_price
|
||||
oneof TriggerOrderPrice
|
||||
{
|
||||
PriceOffset payup = 40;
|
||||
double price = 50;
|
||||
@@ -269,12 +269,12 @@ Opposite of BTS Stop (Both in terms of where the order is placed, and how it tra
|
||||
message BTSIfTouchedOrder
|
||||
{
|
||||
PriceTrigger price_trigger = 10;
|
||||
oneof native_trigger_order_type
|
||||
oneof NativeTriggerOrderType
|
||||
{
|
||||
MarketOrder market_order = 20;
|
||||
LimitOrder limit_order = 30;
|
||||
}
|
||||
oneof order_price
|
||||
oneof OrderPrice
|
||||
{
|
||||
PriceOffset payup = 40;
|
||||
double price = 50;
|
||||
@@ -293,7 +293,7 @@ previous has been filled.
|
||||
message BTSIcebergOrder
|
||||
{
|
||||
QuantityMeasure display_quantity = 10;
|
||||
oneof child_order_offset
|
||||
oneof ChildOrderOffset
|
||||
{
|
||||
PriceOffset market_offset = 20;
|
||||
double diff_from_last_fill = 30;
|
||||
@@ -312,7 +312,7 @@ message BTSTimeSliceOrder
|
||||
{
|
||||
double interval = 10;
|
||||
QuantityMeasure display_quantity = 20;
|
||||
oneof child_order_type
|
||||
oneof ChildOrderType
|
||||
{
|
||||
MarketOrder market_order = 30;
|
||||
LimitOrder limit_order = 40;
|
||||
@@ -320,7 +320,7 @@ message BTSTimeSliceOrder
|
||||
PriceOffset child_order_offset = 50;
|
||||
/// the earlier order can either be left, or its
|
||||
/// price moved toward the inside market by payup_ticks
|
||||
oneof left_over_action
|
||||
oneof LeftOverAction
|
||||
{
|
||||
bool leave = 60;
|
||||
double payup_ticks = 70;
|
||||
@@ -343,12 +343,12 @@ ii. If the stop order is trigerred, the Limit order is cancelled
|
||||
message BTSOCOOrder
|
||||
{
|
||||
PriceTrigger price_trigger = 10;
|
||||
oneof native_trigger_order_type
|
||||
oneof NativeTriggerOrderType
|
||||
{
|
||||
MarketOrder market_order = 20;
|
||||
LimitOrder limit_order = 30;
|
||||
}
|
||||
oneof order_price
|
||||
oneof OrderPrice
|
||||
{
|
||||
PriceOffset payup = 40;
|
||||
double price = 50;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <string>
|
||||
#include <google/protobuf/text_format.h>
|
||||
#include "lib/utils/datetime.h"
|
||||
#include "lib/utils/bts_assert.h"
|
||||
|
||||
#include "bts_export.h"
|
||||
|
||||
@@ -24,6 +25,13 @@ template <class T> bool from_string(const std::string &str, T*out)
|
||||
return google::protobuf::TextFormat::ParseFromString (str,out);
|
||||
}
|
||||
|
||||
template <class T> T from_string(const std::string &str)
|
||||
{
|
||||
T result;
|
||||
bts_assert(google::protobuf::TextFormat::ParseFromString (str,&result));
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
set(sources ;cmds/Benchmark.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/Help.cpp;cmds/Md.cpp;cmds/Run.cpp;cmds/RunSim.cpp;cmds/Test.cpp;cmds/TestCeloxica.cpp;cmds/TestOrderman.cpp;event_grid/EventNode.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/Market.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/store_tests.cpp;main.cpp;md/platforms/celoxica/CXListener.cpp;md/platforms/celoxica/CXMain.cpp;md/platforms/celoxica/tests/cx_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/MDP3Utils.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;orderman/components/FillRecorder.cpp;orderman/components/Gateway.cpp;orderman/components/MDSource.cpp;orderman/components/NativeOrderMan.cpp;orderman/components/OrderRecorder.cpp;orderman/components/SpreaderOrderMan.cpp;orderman/events/ExecutionReport.cpp;orderman/events/NativeOrderStateChange.cpp;orderman/events/SpreaderOrderStateChange.cpp;orderman/events/TimeChange.cpp;orderman/native_orders/NativeOrder.cpp;orderman/native_orders/NativeOrderBuilder.cpp;orderman/native_orders/NativeOrderFactory.cpp;orderman/persistence/FillDB.cpp;orderman/persistence/OrderDB.cpp;orderman/persistence/gen_order_id.cpp;orderman/service/OrderServiceServer.cpp;orderman/spreader_orders/SpreaderOrder.cpp;orderman/spreader_orders/SpreaderOrderBase.cpp;orderman/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp;orderman/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp;orderman/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp;orderman/spreader_orders/spreader_states/SpreaderWaitingForFirstConnStateWorker.cpp;orderman/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp;orderman/tests/spreader_order_tests.cpp;orderman/utils/fix_order_codec.cpp;orderman/utils/orderman_utils.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/tests/PersistenceServiceTests.cpp;risk_limits/IRiskLimitObserver.cpp;risk_limits/RiskLimitManager.cpp;risk_limits/RiskLimiter.cpp;risk_limits/AccountRiskLimiter.cpp;risk_limits/SymbolKey.cpp;risk_limits/tests/RiskLimitsTests.cpp;securities/SecurityDB.cpp;spreader/SingleFillHedger.cpp;spreader/SingleLegQuoter.cpp;spreader/hedger/hedger_states/HedgerEndStateWorker.cpp;spreader/hedger/hedger_states/HedgerStartStateWorker.cpp;spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp;spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp;spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp;spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp;spreader/quoter/quoter_states/QuoterEndStateWorker.cpp;spreader/quoter/quoter_states/QuoterStartStateWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForCancelAckFinalStateWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForCancelAckReturnStateWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp;spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp;testing/catch_test_runner.cpp;user/UserServiceServer.cpp)
|
||||
set(sources ;cmds/Benchmark.cpp;cmds/CmdRegistry.cpp;cmds/ConfigCheck.cpp;cmds/Help.cpp;cmds/Md.cpp;cmds/Run.cpp;cmds/RunSim.cpp;cmds/Test.cpp;cmds/TestCeloxica.cpp;cmds/TestOrderman.cpp;event_grid/EventNode.cpp;exchange_sim/ExchangeSim.cpp;exchange_sim/ExchangeSimApplication.cpp;exchange_sim/Market.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/store_tests.cpp;main.cpp;md/platforms/celoxica/CXListener.cpp;md/platforms/celoxica/CXMain.cpp;md/platforms/celoxica/tests/cx_tests.cpp;md/platforms/mdp3_onixs/MDP3Listener.cpp;md/platforms/mdp3_onixs/MDP3Main.cpp;md/platforms/mdp3_onixs/MDP3Utils.cpp;md/platforms/mdp3_onixs/tests/mdp3_tests.cpp;md/run_md.cpp;orderman/components/FillRecorder.cpp;orderman/components/Gateway.cpp;orderman/components/MDSource.cpp;orderman/components/NativeOrderMan.cpp;orderman/components/OrderRecorder.cpp;orderman/components/SpreaderOrderMan.cpp;orderman/events/ExecutionReport.cpp;orderman/events/NativeOrderStateChange.cpp;orderman/events/SpreaderOrderStateChange.cpp;orderman/events/TimeChange.cpp;orderman/native_orders/NativeOrder.cpp;orderman/native_orders/NativeOrderBuilder.cpp;orderman/native_orders/NativeOrderFactory.cpp;orderman/persistence/FillDB.cpp;orderman/persistence/OrderDB.cpp;orderman/persistence/gen_order_id.cpp;orderman/service/OrderServiceServer.cpp;orderman/spreader_orders/SpreaderOrder.cpp;orderman/spreader_orders/SpreaderOrderBase.cpp;orderman/spreader_orders/spreader_states/SpreaderEndStateWorker.cpp;orderman/spreader_orders/spreader_states/SpreaderStartStateWorker.cpp;orderman/spreader_orders/spreader_states/SpreaderWaitingForCancelAllStateWorker.cpp;orderman/spreader_orders/spreader_states/SpreaderWaitingForFirstConnStateWorker.cpp;orderman/spreader_orders/spreader_states/SpreaderWorkingStateWorker.cpp;orderman/tests/spreader_order_tests.cpp;orderman/utils/fix_order_codec.cpp;orderman/utils/orderman_utils.cpp;persistence/IStore.cpp;persistence/PersistenceServiceServer.cpp;persistence/SqliteStore.cpp;persistence/tests/PersistenceServiceTests.cpp;risk_limits/IRiskLimitObserver.cpp;risk_limits/RiskLimitManager.cpp;risk_limits/RiskLimiter.cpp;risk_limits/SharedRiskLimiter.cpp;risk_limits/SymbolKey.cpp;risk_limits/tests/RiskLimitsTests.cpp;securities/SecurityDB.cpp;spreader/SingleFillHedger.cpp;spreader/SingleLegQuoter.cpp;spreader/hedger/hedger_states/HedgerEndStateWorker.cpp;spreader/hedger/hedger_states/HedgerStartStateWorker.cpp;spreader/hedger/hedger_states/HedgerWaitingForCancelAckStateWorker.cpp;spreader/hedger/hedger_states/HedgerWaitingForFirstAckCancelledStateWorker.cpp;spreader/hedger/hedger_states/HedgerWaitingForFirstAckStateWorker.cpp;spreader/hedger/hedger_states/HedgerWorkingStateWorker.cpp;spreader/quoter/quoter_states/QuoterEndStateWorker.cpp;spreader/quoter/quoter_states/QuoterStartStateWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForCancelAckFinalStateWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForCancelAckReturnStateWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForFirstAckCancelledWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForFirstAckWorker.cpp;spreader/quoter/quoter_states/QuoterWaitingForSizeStateWorker.cpp;spreader/quoter/quoter_states/QuoterWorkingStateWorker.cpp;testing/catch_test_runner.cpp;user/AccountServiceServer.cpp;user/UserServiceServer.cpp;user/tests/UserAndAccountTests.cpp)
|
||||
@@ -1,49 +1,201 @@
|
||||
#include "Benchmark.h"
|
||||
#include "lib/utils/PBUtils.h"
|
||||
#include "server/sparkd/cmds/CmdRegistry.h"
|
||||
#include <iostream>
|
||||
#include "server/sparkd/orderman/native_orders/NativeOrder.h"
|
||||
#include "lib/utils/Puid.h"
|
||||
#include "server/sparkd/orderman/persistence/gen_order_id.h"
|
||||
#include "lib/api/services/OrderService.pb.h"
|
||||
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <iostream>
|
||||
#include <mutex>
|
||||
|
||||
namespace bts {
|
||||
namespace cmd {
|
||||
|
||||
static void BM_StringCreation(benchmark::State& state) {
|
||||
auto sec_str = " id: 3\n"
|
||||
" symbol: \"ES\"\n"
|
||||
" exchange: VENUE_GLBX\n"
|
||||
" contract_spec {\n"
|
||||
" low_tick: 0.25\n"
|
||||
" high_tick: 0.25\n"
|
||||
" cash_per_point: 50\n"
|
||||
" price_multiplier: 0.01\n"
|
||||
" }\n"
|
||||
" future {\n"
|
||||
" expiration_year: 2018\n"
|
||||
" expiration_month: 9\n"
|
||||
" expiration_day: 1\n"
|
||||
" }\n"
|
||||
" glbx {\n"
|
||||
" exchange_id: 57287\n"
|
||||
" security_desc: \"ESU8\"\n"
|
||||
" cfi_code: \"FFIXSX\"\n"
|
||||
" cme_symbol: \"ES\"\n"
|
||||
" }\n";
|
||||
|
||||
auto order_str = " order_key: 189285\n"
|
||||
" timestamp {\n"
|
||||
" seconds: 1509644176\n"
|
||||
" nanos: 717250000\n"
|
||||
" }\n"
|
||||
" native {\n"
|
||||
" account_name: \"BTS \"\n"
|
||||
" operator_id: \"BTS \"\n"
|
||||
" security_key: 3\n"
|
||||
" side: SIDE_BUY\n"
|
||||
" time_in_force: TIF_DAY\n"
|
||||
" manual_order_indicator: MOI_YES\n"
|
||||
" order_type: OT_LIMIT\n"
|
||||
" price: 2500\n"
|
||||
" order_quantity: 12\n"
|
||||
" }\n"
|
||||
" customer_or_firm: COF_FIRM\n"
|
||||
" cti_code: CTI_CTI1\n"
|
||||
" order_status: OS_UNACKNOWLEDGED\n";
|
||||
|
||||
static void create_native_order_from_header(benchmark::State &state) {
|
||||
|
||||
auto sec = utils::pb::from_string<api::Security>(sec_str);
|
||||
auto order_state =
|
||||
utils::pb::from_string<api::orderman::OrderState>(order_str);
|
||||
auto &native = order_state.native();
|
||||
|
||||
auto header = orderman::NativeOrderHeader {
|
||||
orderman::null_order_key(),
|
||||
orderman::null_order_key(),
|
||||
api::orderman::COK_UNDEFINED,
|
||||
&sec,
|
||||
orderman::to<orderman::AccountName>(native.account_name()),
|
||||
orderman::to<orderman::OperatorID>(native.operator_id()),
|
||||
native.side(),
|
||||
native.time_in_force(),
|
||||
native.order_type(),
|
||||
native.manual_order_indicator(),
|
||||
order_state.customer_or_firm(),
|
||||
order_state.cti_code()
|
||||
};
|
||||
for (auto _ : state) {
|
||||
std::string empty_string;
|
||||
benchmark::DoNotOptimize(empty_string.size());
|
||||
orderman::NativeOrder n(header);
|
||||
benchmark::DoNotOptimize(n.can_be_canceled());
|
||||
}
|
||||
}
|
||||
BENCHMARK(create_native_order_from_header);
|
||||
|
||||
// Register the function as a benchmark
|
||||
BENCHMARK(BM_StringCreation);
|
||||
static void compare_native_order_header(benchmark::State &state) {
|
||||
|
||||
// Define another benchmark
|
||||
static void BM_StringCopy(benchmark::State& state) {
|
||||
std::string x = "hello";
|
||||
auto sec = utils::pb::from_string<api::Security>(sec_str);
|
||||
auto order_state =
|
||||
utils::pb::from_string<api::orderman::OrderState>(order_str);
|
||||
auto &native = order_state.native();
|
||||
|
||||
auto header = orderman::NativeOrderHeader {
|
||||
orderman::null_order_key(),
|
||||
orderman::null_order_key(),
|
||||
api::orderman::COK_UNDEFINED,
|
||||
&sec,
|
||||
orderman::to<orderman::AccountName>(native.account_name()),
|
||||
orderman::to<orderman::OperatorID>(native.operator_id()),
|
||||
native.side(),
|
||||
native.time_in_force(),
|
||||
native.order_type(),
|
||||
native.manual_order_indicator(),
|
||||
order_state.customer_or_firm(),
|
||||
order_state.cti_code()
|
||||
};
|
||||
auto header2 = header;
|
||||
int i = 0;
|
||||
auto n = 0;
|
||||
for (auto _ : state) {
|
||||
std::string copy(x);
|
||||
benchmark::DoNotOptimize(copy.size());
|
||||
header2.side = (api::Side) ((int)header.side + i);
|
||||
benchmark::DoNotOptimize(n += (header == header2));
|
||||
}
|
||||
}
|
||||
BENCHMARK(BM_StringCopy);
|
||||
BENCHMARK(compare_native_order_header);
|
||||
|
||||
int Benchmark::execute(std::vector<std::string> const &args)
|
||||
{
|
||||
static void create_native_order_from_state(benchmark::State &state) {
|
||||
|
||||
auto sec = utils::pb::from_string<api::Security>(sec_str);
|
||||
auto order_state = utils::pb::from_string<api::orderman::OrderState>(order_str);
|
||||
for (auto _ : state) {
|
||||
orderman::NativeOrder n(sec, order_state);
|
||||
benchmark::DoNotOptimize(n.can_be_canceled());
|
||||
}
|
||||
}
|
||||
BENCHMARK(create_native_order_from_state);
|
||||
|
||||
static void create_native_order_header(benchmark::State &state) {
|
||||
|
||||
auto sec = utils::pb::from_string<api::Security>(sec_str);
|
||||
auto order_state =
|
||||
utils::pb::from_string<api::orderman::OrderState>(order_str);
|
||||
auto &native = order_state.native();
|
||||
|
||||
for (auto _ : state) {
|
||||
auto header = orderman::NativeOrderHeader {
|
||||
orderman::null_order_key(),
|
||||
orderman::null_order_key(),
|
||||
api::orderman::COK_UNDEFINED,
|
||||
&sec,
|
||||
orderman::to<orderman::AccountName>(native.account_name()),
|
||||
orderman::to<orderman::OperatorID>(native.operator_id()),
|
||||
native.side(),
|
||||
native.time_in_force(),
|
||||
native.order_type(),
|
||||
native.manual_order_indicator(),
|
||||
order_state.customer_or_firm(),
|
||||
order_state.cti_code()
|
||||
};
|
||||
benchmark::DoNotOptimize(header.order_key == orderman::null_order_key());
|
||||
}
|
||||
}
|
||||
BENCHMARK(create_native_order_header);
|
||||
|
||||
static void gen_id(benchmark::State &state) {
|
||||
std::string scope = "benchmark";
|
||||
|
||||
for (auto _ : state) {
|
||||
auto id = utils::reserve_ids(scope,1);
|
||||
benchmark::DoNotOptimize(id+1>0);
|
||||
}
|
||||
|
||||
}
|
||||
BENCHMARK(gen_id);
|
||||
|
||||
static void mutex_lock_unlock(benchmark::State &state) {
|
||||
int i = 0;
|
||||
std::mutex lock;
|
||||
for (auto _ : state) {
|
||||
std::lock_guard<std::mutex> l(lock);
|
||||
benchmark::DoNotOptimize(i++);
|
||||
}
|
||||
}
|
||||
BENCHMARK(mutex_lock_unlock);
|
||||
|
||||
static void spin_lock_unlock(benchmark::State &state) {
|
||||
int i = 0;
|
||||
std::atomic_flag _mutex = ATOMIC_FLAG_INIT;
|
||||
for (auto _ : state) {
|
||||
while (_mutex.test_and_set(std::memory_order_acquire));
|
||||
benchmark::DoNotOptimize(i++);
|
||||
_mutex.clear(std::memory_order_release);
|
||||
}
|
||||
}
|
||||
BENCHMARK(spin_lock_unlock);
|
||||
|
||||
int Benchmark::execute(std::vector<std::string> const &args) {
|
||||
bts_assert(args.size() < 100);
|
||||
int argc = args.size();
|
||||
char *argv[100];
|
||||
for (size_t i = 0; i < args.size();i++)
|
||||
argv[i] = (char*) args[i].c_str();
|
||||
for (size_t i = 0; i < args.size(); i++)
|
||||
argv[i] = (char *)args[i].c_str();
|
||||
|
||||
benchmark::Initialize(&argc, argv);
|
||||
benchmark::RunSpecifiedBenchmarks();
|
||||
return 0;
|
||||
}
|
||||
|
||||
std::string Benchmark::help ()
|
||||
{
|
||||
return "Run micro-benchmarks";
|
||||
|
||||
std::string Benchmark::help() { return "Run micro-benchmarks"; }
|
||||
}
|
||||
|
||||
}}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@
|
||||
#include <vector>
|
||||
#include "lib/utils/bts_assert.h"
|
||||
|
||||
#define BEGIN_CMD
|
||||
#define REGISTER(CMD) bts::cmd::CmdRegistry::register_cmd<bts::cmd::CMD>(#CMD)
|
||||
#define END_CMD return bts::cmd::CmdRegistry::dispatch(argc, argv)
|
||||
|
||||
namespace bts {
|
||||
namespace cmd {
|
||||
|
||||
|
||||
@@ -110,7 +110,6 @@ public:
|
||||
|
||||
void write (WriterCursor &cursor)
|
||||
{
|
||||
WriterCursor::Loc dummy_result;
|
||||
CountField::write (cursor,(int) size ());
|
||||
for (auto &el : _elements)
|
||||
el.write (cursor);
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#include <netinet/tcp.h>
|
||||
#include <fstream>
|
||||
#include <unistd.h>
|
||||
#include <sys/uio.h>
|
||||
|
||||
namespace bts {
|
||||
namespace jetfix {
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
#include "lib/logging/logging.h"
|
||||
#include "lib/os/os.h"
|
||||
#include "lib/utils/init_spark_lib.h"
|
||||
#include "server/sparkd/cmds/CmdRegistry.h"
|
||||
|
||||
#define BEGIN_CMD
|
||||
#define REGISTER(CMD) bts::cmd::CmdRegistry::register_cmd<bts::cmd::CMD>(#CMD)
|
||||
#define END_CMD return bts::cmd::CmdRegistry::dispatch(argc, argv)
|
||||
|
||||
// to add a command add the header here and the the REGISTER call below
|
||||
// don't touch this file except to add commands.
|
||||
#include "server/sparkd/cmds/Benchmark.h"
|
||||
@@ -21,7 +16,6 @@
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
using namespace bts;
|
||||
|
||||
os::set_thread_name("main");
|
||||
utils::init_spark_lib();
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ class MDP3Listener :
|
||||
{
|
||||
public:
|
||||
MDP3Listener(CMESecurityIndex& index, md2::MDProducer&, md2::SecurityIDRecorder&, co2::SettlementRecorder&, std::vector<md2::MDProducerChannel>, utils::Dispatcher&);
|
||||
~MDP3Listener();
|
||||
virtual ~MDP3Listener();
|
||||
|
||||
//
|
||||
// Warnings/Errors/Info
|
||||
|
||||
@@ -0,0 +1,622 @@
|
||||
#!/usr/bin/python
|
||||
|
||||
import os
|
||||
import re
|
||||
import fileinput
|
||||
import sys
|
||||
import collections
|
||||
import csv
|
||||
import datetime
|
||||
import time
|
||||
import copy
|
||||
import itertools
|
||||
import argparse
|
||||
|
||||
# region fix record processing
|
||||
|
||||
valid_message_types = {
|
||||
'D': 'NEW ORDER',
|
||||
'G': 'MODIFY',
|
||||
'F': 'CANCEL',
|
||||
'8': 'EXECUTION',
|
||||
'i': 'MASS QUOTE',
|
||||
'R': 'QUOTE REQUEST',
|
||||
'b': 'QUOTE ACK',
|
||||
'Z': 'MASS QUOTE CANCEL',
|
||||
# 'c': 'SECURITY DEFINITION REQUEST',
|
||||
'3': 'SESSION LEVEL REJECT',
|
||||
'j': 'BUSINESS LEVEL REJECT',
|
||||
'9': 'CANCEL REJECT',
|
||||
'CA': 'ORDER MASS ACTION REQUEST',
|
||||
'BZ': 'ORDER MASS ACTION REPORT'
|
||||
}
|
||||
|
||||
valid_order_types = {
|
||||
'1': 'Market order (with protection)',
|
||||
'2': 'Limit order',
|
||||
'3': 'Stop order (with protection)',
|
||||
'4': 'Stop-Limit order',
|
||||
'K': 'Market-Limit order'
|
||||
}
|
||||
|
||||
valid_order_status = {
|
||||
'0': 'NEW ORDER ACK',
|
||||
'1': 'PARTIAL FILL',
|
||||
'2': 'COMPLETE FILL',
|
||||
'4': 'CANCEL ACK',
|
||||
'5': 'MODIFY ACK',
|
||||
'8': 'ORDER REJECTED',
|
||||
'C': 'EXPIRED',
|
||||
'H': 'TRADE CANCEL',
|
||||
'U': 'CANCEL REJECTED'
|
||||
}
|
||||
|
||||
valid_sides = {
|
||||
'1': 'BUY',
|
||||
'2': 'SELL'
|
||||
}
|
||||
|
||||
# Range of values from tag 59 here:
|
||||
# https://www.cmegroup.com/confluence/display/EPICSANDBOX/New+Order
|
||||
valid_order_qualifier = {
|
||||
'0': 'DAY',
|
||||
'1': 'GTC',
|
||||
'3': 'FAK',
|
||||
'6': 'GTD'
|
||||
}
|
||||
|
||||
valid_quote_ack_status = {
|
||||
'0': 'Accepted',
|
||||
'1': 'Cancel per instrument accepted',
|
||||
'3': 'Cancel per Instrument Group accepted',
|
||||
'4': 'Cancel All accepted',
|
||||
'A': 'Cancel Hard Disconnect accepted',
|
||||
'B': 'Cancel Client Logout accepted',
|
||||
'C': 'Cancel GCC Eliminated All accepted',
|
||||
'D': 'Cancel GCC Eliminated Group accepted',
|
||||
'E': 'Expired accepted',
|
||||
'F': 'Cancel per Market Maker Protection accepted',
|
||||
'H': 'Cancel due to Self-Trade Prevention accepted',
|
||||
'5': 'Rejected'
|
||||
}
|
||||
|
||||
|
||||
def is_an_audited_quote_message(fix_record):
|
||||
if fix_record['35'] == 'b':
|
||||
if '297' in fix_record and fix_record['297'] in valid_quote_ack_status:
|
||||
return True
|
||||
else: return False
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
valid_quote_reject_reason = {
|
||||
'1': 'Unknown Symbol',
|
||||
'2': 'Exchange (Security) closed',
|
||||
'3': 'Quote request exceeds limit',
|
||||
'5': 'Unknown quote',
|
||||
'6': 'Duplicate quote',
|
||||
'7': 'Invalid bid/ask spread',
|
||||
'8': 'Invalid price',
|
||||
'9': 'Not authorized to quote security',
|
||||
'20': 'Too many rejects and cancel instrument group',
|
||||
'98': 'Market maker protection',
|
||||
'99': 'Missing account number or other reason'
|
||||
}
|
||||
|
||||
|
||||
def getter(field_name):
|
||||
def result(fix_record):
|
||||
if field_name in fix_record:
|
||||
return fix_record[field_name]
|
||||
else:
|
||||
return None
|
||||
return result
|
||||
|
||||
|
||||
func_table = {}
|
||||
|
||||
|
||||
def direction(fix_record):
|
||||
if fix_record['49'] == 'CME':
|
||||
return "FROM CME"
|
||||
else:
|
||||
return "TO CME"
|
||||
|
||||
|
||||
func_table[5] = getter('7928')
|
||||
|
||||
|
||||
def account_number(fix_record):
|
||||
if '9771' in fix_record:
|
||||
return fix_record['9771']
|
||||
elif '1' in fix_record:
|
||||
return fix_record['1']
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
func_table[6] = account_number
|
||||
|
||||
|
||||
def session_id(fix_record):
|
||||
if func_table[3] == 'TO CME':
|
||||
return fix_record['49'][:3]
|
||||
else: # FROM CME
|
||||
return fix_record['56'][:3]
|
||||
|
||||
|
||||
func_table[7] = session_id
|
||||
|
||||
|
||||
def execution_firm_id(fix_record):
|
||||
if func_table[3] == 'TO CME':
|
||||
return fix_record['49'][3:6]
|
||||
else: # FROM CME
|
||||
return fix_record['56'][3:6]
|
||||
|
||||
|
||||
func_table[8] = execution_firm_id
|
||||
func_table[9] = getter('1028')
|
||||
|
||||
|
||||
def message_type(fix_record):
|
||||
if '35' in fix_record:
|
||||
tag_35 = fix_record['35']
|
||||
if func_table[3] == 'TO CME':
|
||||
if tag_35 == 'Z':
|
||||
return tag_35 + '\\' + fix_record['298']
|
||||
else:
|
||||
return tag_35
|
||||
else: # FROM CME
|
||||
if tag_35 == '8':
|
||||
return tag_35 + '\\' + fix_record['39']
|
||||
elif tag_35 == 'b':
|
||||
return tag_35 + '\\' + fix_record['297']
|
||||
elif tag_35 == '9':
|
||||
return tag_35 + '\\' + fix_record['434']
|
||||
else:
|
||||
return tag_35
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
func_table[10] = message_type
|
||||
func_table[11] = getter('9702')
|
||||
func_table[12] = getter('204')
|
||||
func_table[13] = getter('17')
|
||||
# func_table[14]=getter('none')
|
||||
func_table[15] = getter('11')
|
||||
func_table[16] = getter('527')
|
||||
|
||||
|
||||
def instrument_description(fix_record):
|
||||
if '107' in fix_record:
|
||||
return fix_record['107']
|
||||
elif '9774' in fix_record:
|
||||
return fix_record['9774']
|
||||
elif '55' in fix_record:
|
||||
return fix_record['55']
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
func_table[17]=instrument_description
|
||||
|
||||
|
||||
def market_segment_id(fix_record):
|
||||
if func_table[3] == 'TO CME':
|
||||
return fix_record['57']
|
||||
else:
|
||||
return fix_record['50']
|
||||
|
||||
|
||||
func_table[18] = market_segment_id
|
||||
func_table[19] = getter('11')
|
||||
func_table[20] = getter('37')
|
||||
|
||||
|
||||
def buy_sell_indicator(fix_record):
|
||||
if '54' in fix_record:
|
||||
tag_54 = fix_record['54']
|
||||
if tag_54 == '1':
|
||||
return 'B'
|
||||
elif tag_54 == '2':
|
||||
return 'S'
|
||||
else:
|
||||
return None
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
# func_table[21]=buy_sell_indicator
|
||||
func_table[21] = getter('54')
|
||||
|
||||
|
||||
def quantity(fix_record):
|
||||
if '32' in fix_record:
|
||||
return fix_record['32']
|
||||
elif '38' in fix_record:
|
||||
return fix_record['38']
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
func_table[22] = quantity
|
||||
func_table[23] = getter('44')
|
||||
func_table[24] = getter('99')
|
||||
|
||||
|
||||
def order_type(fix_record):
|
||||
if '40' in fix_record and fix_record['40'] in valid_order_types:
|
||||
return valid_order_types[fix_record['40']]
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
# func_table[25]=order_type
|
||||
func_table[25] = getter('40')
|
||||
|
||||
|
||||
def order_qualifier(fix_record):
|
||||
if '59' in fix_record and fix_record['59'] in valid_order_qualifier:
|
||||
return valid_order_qualifier[fix_record['59']]
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
# func_table[26]=order_qualifier
|
||||
func_table[26] = getter('59')
|
||||
func_table[27] = getter('9768')
|
||||
func_table[28] = getter('210')
|
||||
func_table[29] = getter('110')
|
||||
|
||||
|
||||
def country_of_origin(fix_record):
|
||||
if '142' in fix_record:
|
||||
# return '\'' + fix_record['142'] + '\''
|
||||
return fix_record['142'].replace(",", "")
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
func_table[30] = country_of_origin
|
||||
func_table[31] = getter('31')
|
||||
func_table[32] = getter('32')
|
||||
func_table[33] = getter('14')
|
||||
func_table[34] = getter('151')
|
||||
func_table[35] = getter('1057')
|
||||
func_table[36] = getter('378')
|
||||
|
||||
|
||||
def strip_comment_of_comma(fix_record):
|
||||
if '58' in fix_record:
|
||||
# Execution Report - Reject
|
||||
if '103' in fix_record:
|
||||
return fix_record['103'] + ':' + fix_record['58'].replace(",", "")
|
||||
# Cancel or Cancel-Replace Reject
|
||||
elif '102' in fix_record:
|
||||
return fix_record['102'] + ':' + fix_record['58'].replace(",", "")
|
||||
# No reject code
|
||||
else:
|
||||
return fix_record['58'].replace(",", "")
|
||||
elif '368' in fix_record:
|
||||
# QuoteEntryRejectReason
|
||||
return fix_record['368'].replace(",", "")
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
func_table[37] = strip_comment_of_comma
|
||||
func_table[38] = getter('9772')
|
||||
func_table[39] = getter('548')
|
||||
func_table[40] = getter('131')
|
||||
func_table[41] = getter('117')
|
||||
func_table[42] = getter('299')
|
||||
func_table[43] = getter('132')
|
||||
func_table[44] = getter('134')
|
||||
func_table[45] = getter('133')
|
||||
func_table[46] = getter('135')
|
||||
|
||||
# endregion
|
||||
|
||||
# region audit message template
|
||||
audit_message_templates = {}
|
||||
# New Order & RFC
|
||||
audit_message_templates['D'] = [range(1,13), range(14,16), range(17,20), range(21, 27), range(28,31), [39]]
|
||||
audit_message_templates['s'] = [range(1,13), range(14,16), range(17,20), range(21, 27), range(28,31), [39]]
|
||||
# Order Cancel Request
|
||||
audit_message_templates['F'] = [range(1,5), range(6,11), range(14,16), range(17,22), [30]]
|
||||
# Order Modifiction
|
||||
audit_message_templates['G'] = [range(1,13), range(14,16), range(17,31)]
|
||||
# Execution Report - Ack
|
||||
audit_message_templates['8\\0'] = [range(1,11), range(13,16), range(17,27), range(28,30), [39]]
|
||||
# Execution Report - Fill Notice - Partial & Complete
|
||||
audit_message_templates['8\\1'] = [range(1,11), range(13,22), range(31,36), [39]]
|
||||
audit_message_templates['8\\2'] = [range(1,11), range(13,22), range(31,36), [39]]
|
||||
# Execution Report - Cancel Confirmation
|
||||
audit_message_templates['8\\4'] = [range(1,11), range(13,16), range(17,22), [36], [39]]
|
||||
# Execution Report - Modification Confirmation
|
||||
audit_message_templates['8\\5'] = [range(1,11), range(13,16), range(17,27), range(28,30), [39]]
|
||||
# Execution Report - Trade Cancel Confirmation
|
||||
audit_message_templates['8\\H'] = [range(1,11), range(13,22), range(31,33)]
|
||||
# Execution Report - Elimination Notice
|
||||
audit_message_templates['8\\C'] = [range(1,11), range(13,16), range(17,22), range(33,35)]
|
||||
# Execution Report - Reject
|
||||
audit_message_templates['8\\8'] = [range(1,11), range(13,16), range(17,22), [37]]
|
||||
# Session-Level Reject
|
||||
audit_message_templates['3'] = [range(1,5), range(7,11), range(14,16), [18], [37]]
|
||||
# Business-Level Reject
|
||||
audit_message_templates['j'] = [range(1,5), range(7,11), range(14,16), [18], [37]]
|
||||
# Cancel or Cancel-Replace Reject
|
||||
audit_message_templates['9\\1'] = [range(1,5), range(6,11), range(13,16), range(18,21), [37]]
|
||||
# Mass Quote
|
||||
audit_message_templates['i'] = [range(1,13), range(17,19), [30], range(40,47)]
|
||||
# Mass Quote - Ack
|
||||
audit_message_templates['b\\0'] = [range(1,11), [18], range(37,39), range(41,43)]
|
||||
# Mass Quote - Reject
|
||||
audit_message_templates['b\\5'] = [range(1,11), [18], range(37,39), [41]]
|
||||
# Mass Quote - Cancel - Per Instrument & Per Instrument Group & All Quotes
|
||||
audit_message_templates['Z\\1'] = [range(1,6), range(7,11), range(17,19), [41]]
|
||||
audit_message_templates['Z\\3'] = [range(1,6), range(7,11), range(17,19), [41]]
|
||||
audit_message_templates['Z\\4'] = [range(1,6), range(7,11), range(17,19), [41]]
|
||||
# Mass Quote Cancel Ack - various kinds
|
||||
audit_message_templates['b\\1'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\3'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\4'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\A'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\B'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\C'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\D'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\E'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\F'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
audit_message_templates['b\\H'] = [range(1,6), range(7,11), range(17,19), range(37,39), range(41,43)]
|
||||
# Mass Quote Cancel - Reject
|
||||
# This shares the same key as as Mass Quote - Reject. The only difference in the template is that here we exclude
|
||||
# position 6.
|
||||
# Skipping for now since Spark will not quote; would need to have some other part to key off of as well
|
||||
# Request For Quote (RFQ)
|
||||
audit_message_templates['R'] = [range(1,6), range(7,11), [14], range(17,19), [21], [30], [40]]
|
||||
# Quote Acknowledgement (RFQ)
|
||||
# This shares the same key as as Mass Quote - Ack and Mass Quote - Reject
|
||||
# Skipping for now since Spark will not RFQ; would need to have some other part to key off of as well
|
||||
# Order Mass Action Request
|
||||
audit_message_templates['CA\\1'] = [range(1,11), [14], range(17,20), [21], range(25,27), [30]]
|
||||
audit_message_templates['CA\\9'] = [range(1,11), [14], range(17,20), [21], range(25,27), [30]]
|
||||
audit_message_templates['CA\\10'] = [range(1,11), [14], range(17,20), [21], range(25,27), [30]]
|
||||
# Order Mass Action Report
|
||||
audit_message_templates['BZ\\1'] = [range(1,11), range(14,16), range(17,23), range(25,27), [30]]
|
||||
audit_message_templates['BZ\\9'] = [range(1,11), range(14,16), range(17,23), range(25,27), [30]]
|
||||
audit_message_templates['BZ\\10'] = [range(1,11), range(14,16), range(17,23), range(25,27), [30]]
|
||||
# endregion
|
||||
|
||||
header_cols = ['Sending Timestamps',
|
||||
'Receiving Timestamps',
|
||||
'Message Direction',
|
||||
'Operator ID',
|
||||
'Self-Match Prevention ID',
|
||||
'Account Number',
|
||||
'Session ID',
|
||||
'Executing Firm ID',
|
||||
'Manual Order Identifier',
|
||||
'Message Type',
|
||||
'Customer Type Indicator',
|
||||
'Origin',
|
||||
'CME Globex Message ID',
|
||||
'Message Link ID',
|
||||
'Order Flow ID',
|
||||
'Spread/Leg Link ID',
|
||||
'Instrument Description',
|
||||
'Market Segment ID',
|
||||
'Client Order ID',
|
||||
'CME Globex Order ID',
|
||||
'Buy/Sell Indicator',
|
||||
'Quantity',
|
||||
'Limit Price',
|
||||
'Stop Price',
|
||||
'Order Type',
|
||||
'Order Qualifier',
|
||||
'IFM Flag',
|
||||
'Display Quantity',
|
||||
'Minimum Quantity',
|
||||
'Country of Origin',
|
||||
'Fill Price',
|
||||
'Fill Quantity',
|
||||
'Cumulative Quantity',
|
||||
'Remaining Quantity',
|
||||
'Aggressor Flag',
|
||||
'Source of Cancellation',
|
||||
'Reject Reason',
|
||||
'Processed Quotes',
|
||||
'Cross ID',
|
||||
'Quote Request ID',
|
||||
'Message Quote ID',
|
||||
'Quote Entry ID',
|
||||
'Bid Price',
|
||||
'Bid Size',
|
||||
'Offer Price',
|
||||
'Offer Size']
|
||||
excluded_from_client_lines = ['Self-Match Prevention ID',
|
||||
'Session ID',
|
||||
'Executing Firm ID',
|
||||
'Manual Order Identifier',
|
||||
'Customer Type Indicator',
|
||||
'Origin','CME Globex Message ID',
|
||||
'Spread/Leg Link ID',
|
||||
'Market Segment ID',
|
||||
'CME Globex Order ID',
|
||||
'Source of Cancellation',
|
||||
'Processed Quotes',
|
||||
'Cross ID',
|
||||
'Quote Request ID',
|
||||
'Message Quote ID',
|
||||
'Quote Entry ID']
|
||||
|
||||
|
||||
def parse_fix_line(line):
|
||||
ts = line[:21]
|
||||
fix_line = line[24:].split('\1')
|
||||
result = {}
|
||||
result['timestamp'] = ts
|
||||
for fix_field in fix_line:
|
||||
rx = r"(?P<tag>\d+)?=(?P<value>.*)"
|
||||
match = re.match(rx,fix_field)
|
||||
if match:
|
||||
result[match.group('tag')] = match.group('value')
|
||||
return result
|
||||
|
||||
|
||||
def create_client_dict(exchange_dict, parsed_fix_record):
|
||||
# replicate the exchange line with all existing fields
|
||||
client_line_dict = copy.deepcopy(exchange_dict)
|
||||
|
||||
if (exchange_dict['Message Direction'] == 'TO CME'):
|
||||
client_line_dict['Receiving Timestamps'] = exchange_dict['Sending Timestamps']
|
||||
client_line_dict['Sending Timestamps'] = None
|
||||
client_line_dict['Message Direction'] = 'FROM CLIENT'
|
||||
client_line_dict['Message Type'] = valid_message_types[parsed_fix_record['35']]
|
||||
else:
|
||||
client_line_dict['Sending Timestamps'] = exchange_dict['Receiving Timestamps']
|
||||
client_line_dict['Receiving Timestamps'] = None
|
||||
client_line_dict['Message Direction'] = 'TO CLIENT'
|
||||
client_line_dict['Message Type'] = valid_order_status[parsed_fix_record['39']]
|
||||
|
||||
# clear out client fiends not required for audit
|
||||
for k in excluded_from_client_lines:
|
||||
client_line_dict[k] = None
|
||||
|
||||
# Replace client lines with string descriptions to make them more readable
|
||||
if '40' in parsed_fix_record:
|
||||
client_line_dict['Order Type'] = valid_order_types[parsed_fix_record['40']]
|
||||
else:
|
||||
client_line_dict['Order Type'] = None
|
||||
if '54' in parsed_fix_record:
|
||||
client_line_dict['Buy/Sell Indicator'] = valid_sides[parsed_fix_record['54']]
|
||||
else:
|
||||
client_line_dict['Buy/Sell Indicator'] = None
|
||||
if '59' in parsed_fix_record:
|
||||
client_line_dict['Order Qualifier'] = valid_order_qualifier[parsed_fix_record['59']]
|
||||
else:
|
||||
client_line_dict['Order Qualifier'] = None
|
||||
return client_line_dict
|
||||
|
||||
|
||||
def write_output_csv():
|
||||
session_name = os.path.splitext(os.path.basename(args.quickfix_log))[0]
|
||||
# with statement guarantees file closure regardless of matter how the block exists
|
||||
output_file_name = "{0}_{1}_audittrail_{2:%Y%m%d}.csv".format("CME", session_name, args.date)
|
||||
with open(output_file_name, 'wb') as outfile:
|
||||
writer = csv.DictWriter(outfile, fieldnames=header_cols)
|
||||
writer.writeheader()
|
||||
writer.writerows(audit_entries)
|
||||
|
||||
|
||||
def write_csv_to_console():
|
||||
console_writer = csv.DictWriter(sys.stdout, fieldnames=header_cols)
|
||||
console_writer.writeheader()
|
||||
console_writer.writerows(audit_entries)
|
||||
|
||||
|
||||
def create_base_audit_entry(line_dict):
|
||||
func_table[3] = direction(parsed_fix_record)
|
||||
if func_table[3] == "TO CME":
|
||||
func_table[4] = getter('50')(parsed_fix_record)
|
||||
line_dict['Sending Timestamps'] = parsed_fix_record['timestamp']
|
||||
else:
|
||||
func_table[4] = getter('57')(parsed_fix_record)
|
||||
line_dict['Receiving Timestamps'] = parsed_fix_record['timestamp']
|
||||
line_dict['Message Direction'] = func_table[3]
|
||||
line_dict['Operator ID'] = func_table[4]
|
||||
# iterate through the whole function table for a fix line to generate an audit line
|
||||
for field in range(5, 14):
|
||||
value = func_table[field](parsed_fix_record)
|
||||
if value:
|
||||
line_dict[line_dict.keys()[field - 1]] = value.rstrip()
|
||||
line_dict['Message Link ID'] = line_number
|
||||
for field in range(15, 47):
|
||||
value = func_table[field](parsed_fix_record)
|
||||
if value:
|
||||
line_dict[line_dict.keys()[field - 1]] = value.rstrip()
|
||||
|
||||
|
||||
def enforce_template_contrainsts(line_dict):
|
||||
# clear out composed audit fields that are not necessary in the particular message type
|
||||
if line_dict['Message Type'] in audit_message_templates:
|
||||
# 1-based, hence the +1 when comparing vs index
|
||||
positions_to_keep = list(itertools.chain.from_iterable(
|
||||
audit_message_templates[line_dict['Message Type']]))
|
||||
for index, (key, value) in enumerate(line_dict.items()):
|
||||
if index + 1 not in positions_to_keep:
|
||||
line_dict[key] = None
|
||||
|
||||
|
||||
def create_client_entries(line_dict):
|
||||
if args.server_lines_only:
|
||||
audit_entries.append(line_dict)
|
||||
else:
|
||||
client_line_dict = create_client_dict(line_dict, parsed_fix_record)
|
||||
if line_dict['Message Direction'] == 'TO CME':
|
||||
audit_entries.append(client_line_dict)
|
||||
audit_entries.append(line_dict)
|
||||
else:
|
||||
audit_entries.append(line_dict)
|
||||
audit_entries.append(client_line_dict)
|
||||
|
||||
|
||||
def create_audit_line_from_fix_line():
|
||||
line_dict = collections.OrderedDict.fromkeys(header_cols)
|
||||
create_base_audit_entry(line_dict)
|
||||
enforce_template_contrainsts(line_dict)
|
||||
create_client_entries(line_dict)
|
||||
|
||||
|
||||
def valid_file(f):
|
||||
if not os.path.exists(f):
|
||||
# Argparse uses the ArgumentTypeError to give a rejection message like:
|
||||
# error: argument input: x does not exist
|
||||
raise argparse.ArgumentTypeError("{0} does not exist".format(f))
|
||||
return f
|
||||
|
||||
|
||||
def valid_date(s):
|
||||
try:
|
||||
return datetime.datetime.strptime(s, "%Y%m%d")
|
||||
except ValueError:
|
||||
raise argparse.ArgumentTypeError("Not a valid date: '{0}'.".format(s))
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("quickfix_log", help="the quickfix log[.gz] you wish to process", type=valid_file)
|
||||
parser.add_argument("-d", "--date", help="the date you wish to parse from the log, specified as YYYYmmdd",
|
||||
default=datetime.datetime.today().strftime("%Y%m%d"), type=valid_date)
|
||||
parser.add_argument("-s", "--server_lines_only",
|
||||
help="does not produce any TO/FROM CLIENT logs, useful for testing in CERT", action="store_true")
|
||||
args = parser.parse_args()
|
||||
|
||||
input_as_datetime = args.date
|
||||
trade_day_start = input_as_datetime - datetime.timedelta(days=1) + datetime.timedelta(hours=16, minutes=30)
|
||||
trade_day_utc_start = time.gmtime((time.mktime(trade_day_start.timetuple())))
|
||||
trade_day_end = input_as_datetime + datetime.timedelta(hours=16)
|
||||
trade_day_utc_end = time.gmtime((time.mktime(trade_day_end.timetuple())))
|
||||
|
||||
file_opener = None
|
||||
if args.quickfix_log.endswith(".gz"):
|
||||
import gzip
|
||||
file_opener = gzip.open
|
||||
else:
|
||||
file_opener = open
|
||||
|
||||
audit_entries = []
|
||||
line_number = 0
|
||||
with file_opener(args.quickfix_log) as input_file:
|
||||
for line in input_file:
|
||||
line_timestamp = time.strptime(line[:21], "%Y%m%d-%H:%M:%S.%f")
|
||||
if trade_day_utc_start <= line_timestamp <= trade_day_utc_end:
|
||||
parsed_fix_record = parse_fix_line(line)
|
||||
# if (record['35'] in valid_message_types and record['35'] != 'b') or (is_an_audited_quote_message(record)):
|
||||
if parsed_fix_record['35'] in valid_message_types:
|
||||
line_number = line_number + 1
|
||||
create_audit_line_from_fix_line()
|
||||
|
||||
write_output_csv()
|
||||
write_csv_to_console()
|
||||
@@ -11,32 +11,68 @@
|
||||
- [[https://www.cmegroup.com/confluence/display/EPICSANDBOX/Execution+Report+-+Trade+Cancel][Trade Cancel]]
|
||||
- [[https://www.cmegroup.com/confluence/display/EPICSANDBOX/Order%2BCancel%2BReject][Cancel Reject]]
|
||||
* Fields used
|
||||
| Field | Needed to create | Needed to update | Needed to cancel | Recoverable | Needed for Display | Lifecyle |
|
||||
|--------------------+------------------+------------------+------------------+-------------+--------------------+--------------|
|
||||
| security | Y | Y | Y | Y | Y | const,~null |
|
||||
| account | Y | Y | Y | Y | Y | const,~null |
|
||||
| operatorid | Y | Y | Y | Y | N | const,~null |
|
||||
| orderkey | Y | Y | Y | Y | Y | const,~null |
|
||||
| side | Y | Y | Y | Y | Y | const,~null |
|
||||
| time_in_force | Y | Y | N | Y | Y | const,~null |
|
||||
| customer_or_firm | Y | Y | N | N | Y | const,~null |
|
||||
| cti_code | Y | Y | N | N | Y | const,~null |
|
||||
| login | N | N | N | N | Y | const,~null |
|
||||
|--------------------+------------------+------------------+------------------+-------------+--------------------+--------------|
|
||||
| manual_order_indic | Y | Y | Y | Y | Y | ~const,~null |
|
||||
| order_type | Y | Y | N | Y | Y | ~const,~null |
|
||||
| price | Y | Y | N | Y | Y | ~const,~null |
|
||||
| quantity | Y | Y | N | Y | Y | ~const,~null |
|
||||
| time | Y | Y | Y | Y | Y | ~const,~null |
|
||||
| exchange_order_id | N | Y | Y | Y | N | const,null |
|
||||
| avg_fill_price | N | N | N | Y | Y | ~const,null |
|
||||
| filled_quantity | N | N | N | Y | Y | ~const,null |
|
||||
| remaining_quantity | N | N | N | Y | Y | ~const,null |
|
||||
| reject_msg | N | N | N | Y | Y | ~const,null |
|
||||
| Field | create | update | cancel | recoverable | display | Lifecyle |
|
||||
|--------------------+--------+--------+--------+-------------+---------+--------------|
|
||||
| security | Y | Y | Y | Y | Y | const,~null |
|
||||
| account | Y | Y | Y | Y | Y | const,~null |
|
||||
| operatorid | Y | Y | Y | Y | Y | const,~null |
|
||||
| orderkey | Y | Y | Y | Y | Y | const,~null |
|
||||
| side | Y | Y | Y | Y | Y | const,~null |
|
||||
| time_in_force | Y | Y | N | Y | Y | const,~null |
|
||||
| customer_or_firm | Y | Y | N | N | Y | const,~null |
|
||||
| cti_code | Y | Y | N | N | Y | const,~null |
|
||||
| manual_order_indic | Y | Y | Y | Y | Y | const,~null |
|
||||
| order_type | Y | Y | N | Y | Y | const,~null |
|
||||
|--------------------+--------+--------+--------+-------------+---------+--------------|
|
||||
| price | Y | Y | N | Y | Y | ~const,~null |
|
||||
| quantity | Y | Y | N | Y | Y | ~const,~null |
|
||||
| time | Y | Y | Y | Y | Y | ~const,~null |
|
||||
| exchange_order_id | N | Y | Y | Y | Y | const,null |
|
||||
| avg_fill_price | N | N | N | Y | Y | ~const,null |
|
||||
| filled_quantity | N | N | N | Y | Y | ~const,null |
|
||||
| remaining_quantity | N | N | N | Y | Y | ~const,null |
|
||||
| reject_msg | N | N | N | Y | Y | ~const,null |
|
||||
|
||||
** OrderDefinition
|
||||
Set by the user at creation time, unchangeable after that
|
||||
| orderkey |
|
||||
| parent_order_key |
|
||||
| child_kind |
|
||||
| security |
|
||||
| account |
|
||||
| operatorid |
|
||||
| side |
|
||||
| time_in_force |
|
||||
| order_type |
|
||||
| manual_order_indicator |
|
||||
| customer_or_firm |
|
||||
| cti_code |
|
||||
** OrderParameters
|
||||
Changeable by user, reported by exchange
|
||||
| price |
|
||||
| quantity |
|
||||
** OrderUpdate
|
||||
Reported by the exchange
|
||||
| price |
|
||||
| quantity |
|
||||
| last_fill_price |
|
||||
| avg_fill_price |
|
||||
| filled_quantity |
|
||||
| order_status |
|
||||
| exchange_order_id |
|
||||
| reject_msg |
|
||||
|
||||
** OrderState
|
||||
OrderDefinition + OrderParameters + (OrderUpdate)
|
||||
** OrderCreation
|
||||
OrderDefinition + OrderParameters
|
||||
** OrderUpdate
|
||||
orderkey + OrderParameters
|
||||
** OrderCancel
|
||||
orderkey
|
||||
* Order Chain trace
|
||||
** NewOrder
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
BeginString = FIX.4.2 8=FIX.4.2
|
||||
BodyLength = 271 9=271
|
||||
MsgType = NewOrderSingle 35=D
|
||||
@@ -69,7 +105,7 @@ SecurityExchange = GLBX 207=GLBX
|
||||
7928 = 8056218 7928=8056218
|
||||
9702 = 2 9702=2
|
||||
CheckSum = 127 10=127
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
BeginString = FIX.4.2 8=FIX.4.2
|
||||
BodyLength = 334 9=334
|
||||
MsgType = ExecutionReport 35=8
|
||||
@@ -108,7 +144,7 @@ ExpireDate = 20161102 432=20161102
|
||||
7928 = 8056218 7928=8056218
|
||||
CheckSum = 038 10=038
|
||||
** Cancel
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
BeginString = FIX.4.2 8=FIX.4.2
|
||||
BodyLength = 327 9=327
|
||||
MsgType = OrderCancelRequest 35=F
|
||||
@@ -142,7 +178,7 @@ SecurityExchange = GLBX 207=GLBX
|
||||
9702 = 2 9702=2
|
||||
9717 = 2KjMkw-1C22h9-001v8Q 9717=2KjMkw-1C22h9-001v8Q
|
||||
CheckSum = 186 10=186
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
BeginString = FIX.4.2 8=FIX.4.2
|
||||
BodyLength = 379 9=379
|
||||
MsgType = ExecutionReport 35=8
|
||||
@@ -182,7 +218,7 @@ ExpireDate = 20161102 432=20161102
|
||||
9717 = 2KjMkw-1C22h9-001v8Q 9717=2KjMkw-1C22h9-001v8Q
|
||||
CheckSum = 033 10=033
|
||||
** Cancel/Replace
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
BeginString = FIX.4.2 8=FIX.4.2
|
||||
BodyLength = 344 9=344
|
||||
MsgType = OrderCancelReplaceRequest 35=G
|
||||
@@ -219,7 +255,7 @@ SecurityExchange = GLBX 207=GLBX
|
||||
9717 = 2KjMkw-1C22gp-001v8P 9717=2KjMkw-1C22gp-001v8P
|
||||
9768 = Y 9768=Y
|
||||
CheckSum = 065 10=065
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
=-=-=-=-=-=-==-=-=-=-=-=-==-=-=-=-=-=-=
|
||||
BeginString = FIX.4.2 8=FIX.4.2
|
||||
BodyLength = 379 9=379
|
||||
MsgType = ExecutionReport 35=8
|
||||
@@ -259,13 +295,6 @@ ExpireDate = 20161102 432=20161102
|
||||
9717 = 2KjMkw-1C22gp-001v8P 9717=2KjMkw-1C22gp-001v8P
|
||||
CheckSum = 151 10=151
|
||||
|
||||
* Order fields
|
||||
- SenderSubID
|
||||
- Account
|
||||
- ClOrdID
|
||||
- OrdType
|
||||
- Side
|
||||
- Security
|
||||
* Open Issues
|
||||
- Shell has ugly menus
|
||||
- Self match protection
|
||||
@@ -288,6 +317,8 @@ CheckSum = 151 10=151
|
||||
- simpler wiring
|
||||
- less indirection in dispatch
|
||||
- consider passing lambdas around
|
||||
* Reference
|
||||
10.96.25.29
|
||||
* Notes on "A guide to spread trading futures"
|
||||
- Spread trading exploits correlations between securities and mean
|
||||
reversion
|
||||
@@ -335,3 +366,5 @@ CheckSum = 151 10=151
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ namespace orderman {
|
||||
class NativeOrderMan;
|
||||
class NativeOrder
|
||||
{
|
||||
protected:
|
||||
public:
|
||||
// orders can only be built by special factory classes
|
||||
friend class NativeOrderFactory;
|
||||
friend class NativeOrderBuilder;
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
namespace bts {
|
||||
namespace orderman {
|
||||
|
||||
const auto order_batch_sz = 100;
|
||||
const auto order_batch_sz = 10;
|
||||
|
||||
struct NativeOrderBuilder::PImpl
|
||||
{
|
||||
|
||||
@@ -118,14 +118,21 @@ void NativeOrderFactory::refill(uint32_t at_least_these)
|
||||
|
||||
void NativeOrderFactory::do_work()
|
||||
{
|
||||
int64_t need_these = 0;
|
||||
std::vector<NativeOrderBuilder*> builders;
|
||||
int64_t need_these = 0;
|
||||
{
|
||||
std::lock_guard<std::mutex> l(me->lock);
|
||||
need_these = key_batch_size - me->free_order_ids.size();
|
||||
builders.reserve(me->builders.size());
|
||||
for (auto &b : me->builders)
|
||||
builders.push_back(b.get());
|
||||
}
|
||||
|
||||
if (need_these > 0)
|
||||
refill(need_these);
|
||||
|
||||
for(auto b : builders)
|
||||
b->do_work();
|
||||
}
|
||||
|
||||
|
||||
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user