refactor: Hide md client behind interface, create via Dep Injection
This commit is contained in:
1 parent
8af9d13802
commit
cd291b7a0d
39 files changed
+424
-377
No files matched your search
@@ -1,11 +1,11 @@
|
||||
namespace bts.BlueOrb {
|
||||
using BCG;
|
||||
|
||||
using bts.md;
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
[DataStreamUserRespresentation(false)]
|
||||
public class LiveFuturesBooktream : ViewStream {
|
||||
public LiveFuturesBooktream(string future_target, MarketDataClient mdClient) {
|
||||
public LiveFuturesBooktream(string future_target, IMarketDataClient mdClient) {
|
||||
ViewStream contract_str = new LiveFuturesContractStream(future_target, mdClient);
|
||||
ViewStream bbo_str = new BookStream(mdClient);
|
||||
ViewStream rs = new SimpleJoinStream(contract_str, "sec_key", bbo_str, "sec_key");
|
||||
|
||||
+3
-4
@@ -1,14 +1,13 @@
|
||||
namespace bts.BlueOrb {
|
||||
using System;
|
||||
|
||||
using BCG;
|
||||
|
||||
using bts.api;
|
||||
using bts.md;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
[DataStreamUserRespresentation("LiveFuturesContractStream")]
|
||||
public class LiveFuturesContractStream : ViewStream {
|
||||
public LiveFuturesContractStream(string target, MarketDataClient mdClient) {
|
||||
public LiveFuturesContractStream(string target, IMarketDataClient mdClient) {
|
||||
var fc = new ContractUtils.FutureContract(target);
|
||||
// temporary
|
||||
ViewStream ins_str = new InstrumentsStream(mdClient);
|
||||
|
||||
+3
-3
@@ -1,15 +1,15 @@
|
||||
namespace bts.BlueOrb {
|
||||
using BCG;
|
||||
using System;
|
||||
using bts.md;
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
[DataStreamUserRespresentation(false)]
|
||||
/// This stream is now created by <see cref="Bts.SharedStreams.StreamFactories.SpatialArbScoreStreamFactory"/>
|
||||
public class SpatialArbScoreStream : ViewStream {
|
||||
public SpatialArbScoreStream(MarketDataClient mdClient, int window_sz_secs, int sample_period_sz)
|
||||
public SpatialArbScoreStream(IMarketDataClient mdClient, int window_sz_secs, int sample_period_sz)
|
||||
: this(mdClient, TimeSpan.FromSeconds(window_sz_secs), TimeSpan.FromSeconds(sample_period_sz), ViewStreamDatabase.instance) { }
|
||||
|
||||
public SpatialArbScoreStream(MarketDataClient mdClient, TimeSpan window_sz, TimeSpan sample_period, ViewStreamDatabase vsd) {
|
||||
public SpatialArbScoreStream(IMarketDataClient mdClient, TimeSpan window_sz, TimeSpan sample_period, ViewStreamDatabase vsd) {
|
||||
ViewStream rs = new SpatialArbStatsStream(mdClient, window_sz, sample_period, vsd);
|
||||
rs = new ThrottleStream(rs, TimeSpan.FromSeconds(1), vsd);
|
||||
rs = new SortStream(rs, "-n_trade_ticks");
|
||||
|
||||
+5
-5
@@ -1,10 +1,10 @@
|
||||
namespace bts.BlueOrb {
|
||||
using BCG;
|
||||
|
||||
using bts.md;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@@ -20,15 +20,15 @@
|
||||
private ViewStream _bbo_stream;
|
||||
private readonly TimeSpan _window_sz, _sampling_period_sz;
|
||||
|
||||
public SpatialArbStatsStream(MarketDataClient mdClient, int window_sz_seconds, int sampling_period_sz_seconds)
|
||||
public SpatialArbStatsStream(IMarketDataClient mdClient, int window_sz_seconds, int sampling_period_sz_seconds)
|
||||
: this(mdClient, TimeSpan.FromSeconds(window_sz_seconds), TimeSpan.FromSeconds(sampling_period_sz_seconds), ViewStreamDatabase.instance) { }
|
||||
|
||||
public SpatialArbStatsStream(MarketDataClient mdClient, TimeSpan window_sz, TimeSpan sampling_period_sz, ViewStreamDatabase vsd) {
|
||||
public SpatialArbStatsStream(IMarketDataClient mdClient, TimeSpan window_sz, TimeSpan sampling_period_sz, ViewStreamDatabase vsd) {
|
||||
_vsd = vsd;
|
||||
_window_sz = window_sz;
|
||||
_sampling_period_sz = sampling_period_sz;
|
||||
_spatial_pairs_stream = new SpatialFuturePairsStream(mdClient, vsd);
|
||||
_bbo_stream = new BBOStream(vsd);
|
||||
_bbo_stream = new BBOStream(mdClient, vsd);
|
||||
}
|
||||
|
||||
protected override void myOnFirstSubscriber() {
|
||||
|
||||
+4
-3
@@ -2,10 +2,11 @@
|
||||
using BCG;
|
||||
|
||||
using bts.api;
|
||||
using bts.md;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@@ -15,10 +16,10 @@
|
||||
private ViewStream _main_stream;
|
||||
private IBlueTableSchema _schema;
|
||||
private HashSet<string> _key_map = new HashSet<string>();
|
||||
public SpatialFuturePairsStream(MarketDataClient mdClient)
|
||||
public SpatialFuturePairsStream(IMarketDataClient mdClient)
|
||||
: this(mdClient, ViewStreamDatabase.instance) { }
|
||||
|
||||
public SpatialFuturePairsStream(MarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
public SpatialFuturePairsStream(IMarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
_main_stream = new InstrumentsStream(mdClient, vsd);
|
||||
_main_stream = new FilterStream(_main_stream, "sec_type='Future'");
|
||||
_schema = new BlueTableSchema("SpatialFutures", new ColumnInfo("id", 0, TypeCode.Int32));
|
||||
|
||||
+6
-3
@@ -3,6 +3,8 @@ namespace bts.BlueOrb {
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
using System.Diagnostics;
|
||||
|
||||
public class SpreadPerformanceStream : ViewStream {
|
||||
@@ -12,13 +14,14 @@ namespace bts.BlueOrb {
|
||||
private readonly double _buy_threshold, _sell_threshold, _flat_threshold;
|
||||
private ViewStream _bbo_stream;
|
||||
public SpreadPerformanceStream(string s1, string s2, double w1, double w2, int window_secs,
|
||||
double buy_threshold, double sell_threshold, double flat_threshold)
|
||||
: this(s1, s2, w1, w2, window_secs, buy_threshold, sell_threshold, flat_threshold, ViewStreamDatabase.instance) { }
|
||||
double buy_threshold, double sell_threshold, double flat_threshold, IMarketDataClient mdClient)
|
||||
: this(s1, s2, w1, w2, window_secs, buy_threshold, sell_threshold, flat_threshold, mdClient, ViewStreamDatabase.instance) { }
|
||||
|
||||
public SpreadPerformanceStream(string s1, string s2, double w1, double w2, int window_secs,
|
||||
double buy_threshold, double sell_threshold, double flat_threshold,
|
||||
IMarketDataClient mdClient,
|
||||
ViewStreamDatabase vsd) {
|
||||
_bbo_stream = new BBOStream(vsd);
|
||||
_bbo_stream = new BBOStream(mdClient, vsd);
|
||||
_schema = BlueDataUtility.form_schema("SpreadPerformance", Tuple.Create("id", TypeCode.Int32),
|
||||
Tuple.Create("t0", TypeCode.DateTime),
|
||||
Tuple.Create("t1", TypeCode.DateTime),
|
||||
|
||||
+7
-4
@@ -1,16 +1,19 @@
|
||||
namespace bts.BlueOrb{
|
||||
using BCG;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
public class SpreadStatArbsWeightLinearRegressionStream : ViewStream {
|
||||
private IBlueTableSchema _schema;
|
||||
private ViewStream _leg_price_stream;
|
||||
private readonly double _window_secs;
|
||||
private readonly string _s1, _s2;
|
||||
|
||||
public SpreadStatArbsWeightLinearRegressionStream(string s1, string s2, double window_secs, double sample_period_secs)
|
||||
: this(s1, s2, window_secs, sample_period_secs, ViewStreamDatabase.instance) { }
|
||||
public SpreadStatArbsWeightLinearRegressionStream(string s1, string s2, double window_secs, double sample_period_secs, IMarketDataClient mdClient)
|
||||
: this(s1, s2, window_secs, sample_period_secs, mdClient, ViewStreamDatabase.instance) { }
|
||||
|
||||
|
||||
public SpreadStatArbsWeightLinearRegressionStream(string s1, string s2, double window_secs, double sample_period_secs, ViewStreamDatabase vsd) {
|
||||
public SpreadStatArbsWeightLinearRegressionStream(string s1, string s2, double window_secs, double sample_period_secs, IMarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
_window_secs = window_secs;
|
||||
_s1 = s1;
|
||||
_s2 = s2;
|
||||
@@ -25,7 +28,7 @@ namespace bts.BlueOrb{
|
||||
Tuple.Create("s2", TypeCode.String),
|
||||
Tuple.Create("w2", TypeCode.String));
|
||||
|
||||
_leg_price_stream = new TimeSeriesStream(new SyntheticSpreadLegsStream(s1, s2));
|
||||
_leg_price_stream = new TimeSeriesStream(new SyntheticSpreadLegsStream(s1, s2, mdClient));
|
||||
_leg_price_stream = new ThrottleStream(_leg_price_stream, TimeSpan.FromSeconds(1), vsd);
|
||||
}
|
||||
|
||||
|
||||
+4
-2
@@ -3,6 +3,8 @@
|
||||
|
||||
using MathNet.Numerics.LinearAlgebra.Factorization;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
@@ -17,8 +19,8 @@
|
||||
private readonly IBlueTableSchema _schema;
|
||||
private readonly TimeSpan _window_sz;
|
||||
private readonly string _spread;
|
||||
public SpreadStatsStream(string s1, string s2, double w1, double w2, int rolling_window_sz_seconds, int window_sampling_sz_secs)
|
||||
: this(s1, s2, w1, w2, rolling_window_sz_seconds, window_sampling_sz_secs, new BBOStream(ViewStreamDatabase.instance), ViewStreamDatabase.instance) { }
|
||||
public SpreadStatsStream(string s1, string s2, double w1, double w2, int rolling_window_sz_seconds, int window_sampling_sz_secs, IMarketDataClient mdClient)
|
||||
: this(s1, s2, w1, w2, rolling_window_sz_seconds, window_sampling_sz_secs, new BBOStream(mdClient, ViewStreamDatabase.instance), ViewStreamDatabase.instance) { }
|
||||
public SpreadStatsStream(string s1, string s2, double w1, double w2, int rolling_window_sz_seconds, int window_sampling_sz_secs, ViewStream bbo_stream, ViewStreamDatabase vsd) {
|
||||
_window_sz = TimeSpan.FromSeconds(rolling_window_sz_seconds);
|
||||
_spread = $"{w1} X {s1} - {w2} X {s2}";
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
namespace bts.BlueOrb {
|
||||
using BCG.Utilities.General;
|
||||
|
||||
using bts.md;
|
||||
using BCG;
|
||||
using Spark.Core.Reactive;
|
||||
|
||||
@@ -107,7 +106,7 @@ namespace bts.BlueOrb {
|
||||
private DateTime _last_poll_time = DateTime.MinValue;
|
||||
private ViewStreamDatabase? _vsd;
|
||||
IReadOnlyDictionary<SecurityKey, BookTuple>? _cached_state = null;
|
||||
MarketDataClient? _md_client;
|
||||
readonly IMarketDataClient _md_client;
|
||||
internal static IBlueTableSchema _bbo_schema = BlueDataUtility.form_schema("bbo",
|
||||
Tuple.Create("id", TypeCode.Int32),
|
||||
Tuple.Create("sec_key", TypeCode.UInt32),
|
||||
@@ -120,14 +119,13 @@ namespace bts.BlueOrb {
|
||||
IDisposable? subscription;
|
||||
|
||||
// TODO: add cons for symbol, exchange etc
|
||||
public BBOStream()
|
||||
: this(ViewStreamDatabase.instance) {
|
||||
}
|
||||
public BBOStream(IMarketDataClient mdClient)
|
||||
: this(mdClient, ViewStreamDatabase.instance) { }
|
||||
|
||||
public BBOStream(ViewStreamDatabase vsd) {
|
||||
public BBOStream(IMarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
bts.Log.Gen.info("BBOStream.cons");
|
||||
_vsd = vsd;
|
||||
_md_client = new MarketDataClient(new MDSource(TimeSpan.FromSeconds(0.5)));
|
||||
_md_client = mdClient;
|
||||
//FakeBBOStream rs = new FakeBBOStream("Future", "CME", "ES", 5000, 0.25, vsd);
|
||||
//mySetRealSource(rs);
|
||||
}
|
||||
@@ -135,7 +133,7 @@ namespace bts.BlueOrb {
|
||||
protected override void myOnFirstSubscriber() {
|
||||
Log.isnull(subscription);
|
||||
_vsd?.addWorker(this);
|
||||
subscription = _md_client?.books().Subscribe(_on_books);
|
||||
subscription = _md_client.Books(null).Subscribe(_on_books);
|
||||
}
|
||||
|
||||
private void _log_updates(TableUpdate<BookTuple, uint> update) {
|
||||
|
||||
@@ -3,7 +3,6 @@ namespace bts.BlueOrb{
|
||||
using BCG;
|
||||
|
||||
using bts;
|
||||
using bts.md;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
@@ -27,7 +26,7 @@ namespace bts.BlueOrb{
|
||||
private ViewStreamDatabase _vsd;
|
||||
private int _id = 0;
|
||||
IReadOnlyDictionary<SecurityKey, BookTuple>? _cached_state = null;
|
||||
MarketDataClient _md_client;
|
||||
IMarketDataClient _md_client;
|
||||
readonly Stopwatch _timer = new();
|
||||
private readonly IBlueTableSchema _bbo_schema = BlueDataUtility.form_schema("books",
|
||||
Tuple.Create("id", TypeCode.Int32),
|
||||
@@ -41,10 +40,10 @@ namespace bts.BlueOrb{
|
||||
IDisposable? subscription;
|
||||
|
||||
// TODO: add cons for symbol, exchange etc
|
||||
public BookStream(MarketDataClient mdClient)
|
||||
public BookStream(IMarketDataClient mdClient)
|
||||
: this(mdClient, ViewStreamDatabase.instance) { }
|
||||
|
||||
public BookStream(MarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
public BookStream(IMarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
bts.Log.Gen.info("BookStream.cons");
|
||||
_vsd = vsd;
|
||||
_md_client = mdClient;
|
||||
@@ -53,7 +52,7 @@ namespace bts.BlueOrb{
|
||||
protected override void myOnFirstSubscriber() {
|
||||
Log.isnull(subscription);
|
||||
_vsd.addWorker(this);
|
||||
subscription = _md_client.books().Subscribe(_on_books);
|
||||
subscription = _md_client.Books().Subscribe(_on_books);
|
||||
}
|
||||
|
||||
private void _log_updates(TableUpdate<BookTuple, uint> update) {
|
||||
|
||||
@@ -3,12 +3,12 @@ namespace bts.BlueOrb {
|
||||
|
||||
using bts;
|
||||
using bts.api;
|
||||
using bts.md;
|
||||
|
||||
using BCG;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
@@ -18,6 +18,7 @@ namespace bts.BlueOrb {
|
||||
using System.Collections.Generic;
|
||||
|
||||
using System.Reactive.Linq;
|
||||
using bts.api.core;
|
||||
|
||||
[DataStreamUserRespresentation("InstrumentsStream")]
|
||||
public class InstrumentsStream : ViewStream, IWorker {
|
||||
@@ -25,7 +26,7 @@ namespace bts.BlueOrb {
|
||||
private DateTime _last_poll_time = DateTime.MinValue;
|
||||
private ViewStreamDatabase _vsd;
|
||||
IReadOnlyDictionary<uint, SecurityImmutable>? _cached_state;
|
||||
MarketDataClient _md_client;
|
||||
IMarketDataClient _md_client;
|
||||
private bool _dirty = false;
|
||||
private readonly IBlueTableSchema _instrument_schema = BlueDataUtility.form_schema("instruments",
|
||||
Tuple.Create("id", TypeCode.Int32),
|
||||
@@ -43,10 +44,10 @@ namespace bts.BlueOrb {
|
||||
IDisposable? subscription;
|
||||
|
||||
// TODO: add cons for symbol, exchange etc
|
||||
public InstrumentsStream(MarketDataClient mdClient)
|
||||
public InstrumentsStream(IMarketDataClient mdClient)
|
||||
: this(mdClient, ViewStreamDatabase.instance) { }
|
||||
|
||||
public InstrumentsStream(MarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
public InstrumentsStream(IMarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
bts.Log.Gen.info("InstrumentsStream.cons");
|
||||
_vsd = vsd;
|
||||
_md_client = mdClient;
|
||||
@@ -55,7 +56,7 @@ namespace bts.BlueOrb {
|
||||
protected override void myOnFirstSubscriber() {
|
||||
Log.isnull(subscription);
|
||||
_vsd.addWorker(this);
|
||||
subscription = _md_client.securities().Subscribe(_on_instruments);
|
||||
subscription = _md_client.Securities().Subscribe(_on_instruments);
|
||||
}
|
||||
|
||||
private void _log_updates(IReadOnlyDictionary<uint, SecurityImmutable> state) {
|
||||
@@ -64,7 +65,8 @@ namespace bts.BlueOrb {
|
||||
}
|
||||
}
|
||||
|
||||
private void _on_instruments(IReadOnlyDictionary<uint, SecurityImmutable> state) {
|
||||
private void _on_instruments(TableUpdate<SecurityImmutable, uint> table) {
|
||||
var state = table.state;
|
||||
_dirty = true;
|
||||
//_log_updates(state);
|
||||
// just cacching in here, will populate the rows in _poll_scan and fire the datapacket
|
||||
|
||||
@@ -3,10 +3,10 @@ namespace BCG {
|
||||
|
||||
using bts;
|
||||
using bts.api.core;
|
||||
using bts.md;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
|
||||
@@ -14,7 +14,6 @@ namespace BCG {
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
[DataStreamUserRespresentation("price_stats")]
|
||||
public class PriceStatsStream : ViewStream, IWorker {
|
||||
@@ -23,7 +22,7 @@ namespace BCG {
|
||||
private ViewStreamDatabase _vsd;
|
||||
private int _id = 0;
|
||||
IReadOnlyDictionary<uint, PriceStats>? _cached_state = null;
|
||||
MarketDataClient _md_client;
|
||||
IMarketDataClient _md_client;
|
||||
private bool _dirty = false;
|
||||
private readonly IBlueTableSchema _pstats_scheam = BlueDataUtility.form_schema("bbo",
|
||||
Tuple.Create("id", TypeCode.Int32),
|
||||
@@ -36,10 +35,10 @@ namespace BCG {
|
||||
IDisposable? subscription;
|
||||
|
||||
// TODO: add cons for symbol, exchange etc
|
||||
public PriceStatsStream(MarketDataClient mdClient)
|
||||
public PriceStatsStream(IMarketDataClient mdClient)
|
||||
: this(mdClient, ViewStreamDatabase.instance) { }
|
||||
|
||||
public PriceStatsStream(MarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
public PriceStatsStream(IMarketDataClient mdClient, ViewStreamDatabase vsd) {
|
||||
bts.Log.Gen.info("PriceStatsStream.cons");
|
||||
_md_client = mdClient;
|
||||
_vsd = vsd;
|
||||
@@ -48,7 +47,7 @@ namespace BCG {
|
||||
protected override void myOnFirstSubscriber() {
|
||||
Log.isnull(subscription);
|
||||
_vsd.addWorker(this);
|
||||
subscription = _md_client.price_stats().Subscribe(_on_price_stats);
|
||||
subscription = _md_client.PriceStats().Subscribe(_on_price_stats);
|
||||
}
|
||||
|
||||
private void _log_updates(TableUpdate<PriceStats, uint> update) {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using BCG;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
namespace bts.BlueOrb {
|
||||
/*
|
||||
----------------------------------------------------------------------
|
||||
@@ -36,8 +38,8 @@ namespace bts.BlueOrb {
|
||||
// this is useful for operations like finding weights, that need leg market data organized together succintly.
|
||||
public class SyntheticSpreadLegsStream : ViewStream
|
||||
{
|
||||
public SyntheticSpreadLegsStream(string s1, string s2) :
|
||||
this(s1, s2, new BBOStream(ViewStreamDatabase.instance), ViewStreamDatabase.instance) {}
|
||||
public SyntheticSpreadLegsStream(string s1, string s2, IMarketDataClient mdClient) :
|
||||
this(s1, s2, new BBOStream(mdClient, ViewStreamDatabase.instance), ViewStreamDatabase.instance) {}
|
||||
|
||||
public SyntheticSpreadLegsStream(string s1, string s2, ViewStream bbo_stream, ViewStreamDatabase vsb)
|
||||
{
|
||||
@@ -45,7 +47,7 @@ namespace bts.BlueOrb {
|
||||
ViewStream vs2;
|
||||
ViewStream rs;
|
||||
|
||||
vs1 = new FilterStream (new BBOStream (),
|
||||
vs1 = new FilterStream (bbo_stream,
|
||||
$"sec = '{s1}'");
|
||||
vs1 = new AddColumnsStream (vs1,
|
||||
"ljc:0");
|
||||
@@ -63,8 +65,8 @@ namespace bts.BlueOrb {
|
||||
}
|
||||
}
|
||||
public class SyntheticSpreadStream : ViewStream{
|
||||
public SyntheticSpreadStream (string s1, string s2, double w1, double w2)
|
||||
: this(s1, s2, w1, w2, new BBOStream(ViewStreamDatabase.instance), ViewStreamDatabase.instance){}
|
||||
public SyntheticSpreadStream (string s1, string s2, double w1, double w2, IMarketDataClient mdClient)
|
||||
: this(s1, s2, w1, w2, new BBOStream(mdClient, ViewStreamDatabase.instance), ViewStreamDatabase.instance){}
|
||||
public SyntheticSpreadStream (string s1, string s2, double w1, double w2, ViewStream bbo_stream, ViewStreamDatabase vsd){
|
||||
ViewStream rs = new SyntheticSpreadLegsStream(s1, s2, bbo_stream, vsd);
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@ namespace BCG {
|
||||
using BCG.Utilities.General;
|
||||
|
||||
using bts.api;
|
||||
using bts.md;
|
||||
|
||||
using mbts.spark;
|
||||
|
||||
@@ -26,7 +25,7 @@ namespace BCG {
|
||||
private ViewStreamDatabase _vsd;
|
||||
private int _id = 0;
|
||||
//IReadOnlyDictionary<uint, SecurityImmutable> _cached_state = null;
|
||||
MarketDataClient _md_client;
|
||||
IMarketDataClient _md_client;
|
||||
private bool _dirty = false;
|
||||
private ConcurrentQueue<TradeInfo> _cached_trades = new ConcurrentQueue<TradeInfo>();
|
||||
private CircularRowCollection _circulare_table;
|
||||
@@ -40,22 +39,20 @@ namespace BCG {
|
||||
Tuple.Create("price", TypeCode.Double),
|
||||
Tuple.Create("qty", TypeCode.UInt32),
|
||||
Tuple.Create("aggressor", TypeCode.String));
|
||||
public TimeSalesStream(int buffer_size)
|
||||
: this(buffer_size, ViewStreamDatabase.instance) {
|
||||
public TimeSalesStream(IMarketDataClient mdClient, int buffer_size)
|
||||
: this(mdClient, buffer_size, ViewStreamDatabase.instance) { }
|
||||
|
||||
}
|
||||
|
||||
public TimeSalesStream(int buffer_size, ViewStreamDatabase vsd) {
|
||||
public TimeSalesStream(IMarketDataClient mdClient, int buffer_size, ViewStreamDatabase vsd) {
|
||||
_buffer_size = buffer_size;
|
||||
_circulare_table = new CircularRowCollection(_schema, buffer_size);
|
||||
bts.Log.Gen.info("TimeSalesStream.cons");
|
||||
_vsd = vsd;
|
||||
_md_client = new MarketDataClient(new MDSource(TimeSpan.FromSeconds(0.5)));
|
||||
_md_client = mdClient;
|
||||
}
|
||||
|
||||
protected override void myOnFirstSubscriber() {
|
||||
_vsd.addWorker(this);
|
||||
_md_client.trades(new TradesSubscriptionFilter()).Subscribe(_on_trades);
|
||||
_md_client.Trades(null).Subscribe(_on_trades);
|
||||
//_md_client.trades(null).Subscribe(_on_trades);
|
||||
|
||||
}
|
||||
@@ -101,4 +98,4 @@ namespace BCG {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,21 +9,23 @@ using Bts.DataStreamCore;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
using System;
|
||||
|
||||
public class BookStreamFactory : DataStreamFactory {
|
||||
public BookStreamFactory(MarketDataClient? mdClient, ILogger<BookStreamFactory> logger) {
|
||||
public BookStreamFactory(IMarketDataClient? mdClient, ILogger<BookStreamFactory> logger) {
|
||||
this.Add<BookStreamParams>("book", CreateBook, logger);
|
||||
this.Add<BookStreamParams>(new[] { "bbo", "LiveBBOStream" }, CreateBbo, logger);
|
||||
|
||||
ViewStream? CreateBook(BookStreamParams streamParams) =>
|
||||
mdClient?.books(streamParams.GetSecurityCriteria())
|
||||
mdClient?.Books(streamParams.GetSecurityCriteria())
|
||||
?.AsDataPackets(streamParams.GetSchemaBuilder().BookTupleAdapter())
|
||||
?.AsViewStream()
|
||||
?? throw new InvalidOperationException("Live md not available");
|
||||
|
||||
ViewStream? CreateBbo(BookStreamParams streamParams) =>
|
||||
mdClient?.books(streamParams.GetSecurityCriteria())
|
||||
mdClient?.Books(streamParams.GetSecurityCriteria())
|
||||
?.AsDataPackets(streamParams.GetSchemaBuilder().BboAdapter())
|
||||
?.AsViewStream()
|
||||
?? throw new InvalidOperationException("Live md not available");
|
||||
|
||||
@@ -2,9 +2,7 @@ namespace Bts.SharedStreams.StreamFactories;
|
||||
|
||||
using BCG;
|
||||
|
||||
using bts.api.core;
|
||||
using bts.BlueOrb;
|
||||
using bts.md;
|
||||
|
||||
using Bts.DataStream;
|
||||
using Bts.DataStreamCore;
|
||||
@@ -12,14 +10,15 @@ using Bts.SharedStreams.MarketData;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
class InstrumentStreamFactory : DataStreamFactory {
|
||||
public InstrumentStreamFactory(MarketDataClient mdClient, ILogger<InstrumentStreamFactory> logger) {
|
||||
public InstrumentStreamFactory(IMarketDataClient mdClient, ILogger<InstrumentStreamFactory> logger) {
|
||||
this.Add<InstrumentStreamParams>("instrument", CreateInstrument, logger);
|
||||
this.Add<LiveFutureContractStreamParams>(new[] { "liveFutures", "liveFuturesContract", "LiveFuturesContractStream" }, CreateLiveFutureContract, logger);
|
||||
|
||||
ViewStream? CreateInstrument(InstrumentStreamParams streamParams) =>
|
||||
mdClient.securities(streamParams.GetSecurityCriteria())
|
||||
.Table(s => s.Id)
|
||||
mdClient.Securities(streamParams.GetSecurityCriteria())
|
||||
.AsDataPackets(streamParams.GetSchemaBuilder().SecurityAdapter())
|
||||
.AsViewStream();
|
||||
|
||||
|
||||
@@ -8,13 +8,13 @@ public class InstrumentStreamParams {
|
||||
[StreamArgument(RegexNames = new[] { WellKnownStreamArgumentAliases.VenueRegex })]
|
||||
public Venue? Venue { get; set; }
|
||||
|
||||
[StreamArgument(RegexNames = new[] { WellKnownStreamArgumentAliases.Symbol })]
|
||||
[StreamArgument(RegexNames = new[] { WellKnownStreamArgumentAliases.SymbolRegex })]
|
||||
public string? Symbol { get; set; }
|
||||
|
||||
[StreamArgument(RegexNames = new[] { WellKnownStreamArgumentAliases.SecurityType })]
|
||||
[StreamArgument(RegexNames = new[] { WellKnownStreamArgumentAliases.SecurityTypeRegex })]
|
||||
public SecurityType? Type { get; set; }
|
||||
|
||||
[StreamArgument(RegexNames = new[] { WellKnownStreamArgumentAliases.SecurityType })]
|
||||
[StreamArgument(RegexNames = new[] { WellKnownStreamArgumentAliases.SecurityNameRegex })]
|
||||
public string? Name { get; set; }
|
||||
|
||||
[StreamArgument("legs", "nLegs", "numLegs")]
|
||||
|
||||
@@ -25,12 +25,12 @@ using System.Reactive.Linq;
|
||||
|
||||
public class SpreadBookStreamFactory : IDataStreamFactory {
|
||||
readonly ILogger logger;
|
||||
readonly MarketDataClient? mdClient;
|
||||
readonly IMarketDataClient? mdClient;
|
||||
|
||||
public SpreadBookStreamFactory(ILogger<SpreadBookStreamFactory> logger)
|
||||
: this(null, logger) { }
|
||||
|
||||
public SpreadBookStreamFactory(MarketDataClient? mdClient, ILogger<SpreadBookStreamFactory> logger) {
|
||||
public SpreadBookStreamFactory(IMarketDataClient? mdClient, ILogger<SpreadBookStreamFactory> logger) {
|
||||
this.logger = logger;
|
||||
this.mdClient = mdClient;
|
||||
}
|
||||
@@ -40,7 +40,7 @@ public class SpreadBookStreamFactory : IDataStreamFactory {
|
||||
throw new InvalidOperationException("Live md not available");
|
||||
}
|
||||
var secDefs = args.Legs.ToList();
|
||||
var calcDataSource = mdClient.securities_incremental(IncludeSec).Select(upd => {
|
||||
var calcDataSource = mdClient.Securities(IncludeSec).Select(upd => {
|
||||
var legs = new List<(SecurityImmutable Sec, double Qty)>();
|
||||
foreach (var sd in secDefs) {
|
||||
if (upd.state.Values.TryGetFirst(IsMatch, out var sec)) {
|
||||
@@ -52,7 +52,7 @@ public class SpreadBookStreamFactory : IDataStreamFactory {
|
||||
}
|
||||
return legs;
|
||||
});
|
||||
return calcDataSource.SelectSeries(legs => createSpreadBook(legs, mdClient.books(IncludeSec)))
|
||||
return calcDataSource.SelectSeries(legs => createSpreadBook(legs, mdClient.Books(IncludeSec)))
|
||||
.Scan(
|
||||
TableUpdate<SpreadBookRow, int>.mk_empty(r => (int)r.SecurityId),
|
||||
(lastOut, bk) => lastOut.state.Count == 0
|
||||
|
||||
@@ -38,7 +38,6 @@ namespace bts {
|
||||
readonly TimeSpan _relay_throttle;
|
||||
readonly TimeSpan _output_throttle;
|
||||
readonly List<IDisposable> _resources = new(2);
|
||||
readonly Lazy<MarketDataClient> client;
|
||||
|
||||
[ImportingConstructor]
|
||||
public MDDaemon(
|
||||
@@ -73,7 +72,6 @@ namespace bts {
|
||||
_output_throttle = output_throttle;
|
||||
_security_metadata = security_metadata;
|
||||
_md_source_backing = new(() => new(UserDataPermissions.Create(_user.Value), _relay_throttle, _output_throttle));
|
||||
client = new(() => new(_md_source));
|
||||
}
|
||||
|
||||
public int priority => 55;
|
||||
@@ -81,9 +79,6 @@ namespace bts {
|
||||
[Export]
|
||||
public MDConsumer consumer => _md_source.consumer;
|
||||
|
||||
[Export]
|
||||
public Lazy<MarketDataClient> Client => client;
|
||||
|
||||
MDSource _md_source => _md_source_backing.Value;
|
||||
IBus _bus => _bus_backing.Value;
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
using bts.api;
|
||||
using bts.spark;
|
||||
|
||||
using mbts.co2;
|
||||
using mbts.persist;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core.Data;
|
||||
using Spark.Trading;
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
[ImportingConstructor]
|
||||
public MarketShellModule(
|
||||
IBus bus,
|
||||
MDConsumer consumer,
|
||||
IMarketDataClient mdClient,
|
||||
UserSettingsHub settings_hub,
|
||||
OrdersModel orders_model,
|
||||
IPositionModel position_model,
|
||||
@@ -32,7 +32,7 @@
|
||||
new MarketViewWindowFactory(
|
||||
this, bus, settings_hub, orders_model, position_model, sec_meta_store),
|
||||
new OptionsViewWindowFactory(this, orders_model, bus),
|
||||
new TimeAndSalesWindowFactory(this, bus, consumer, settings_hub),
|
||||
new TimeAndSalesWindowFactory(this, bus, mdClient, settings_hub),
|
||||
};
|
||||
|
||||
public string name => "Market";
|
||||
|
||||
@@ -5,8 +5,6 @@
|
||||
using bts.spark;
|
||||
using bts.view;
|
||||
|
||||
using mbts;
|
||||
using mbts.co2;
|
||||
using mbts.persist;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
@@ -15,6 +13,7 @@
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
|
||||
@@ -35,12 +34,11 @@
|
||||
// likely some dpi issue)
|
||||
const double _VERTICAL_SCROLLBAR_OVERLAP = 9;
|
||||
|
||||
static readonly TimeSpan _trade_poll_interval = TimeSpan.FromSeconds(0.4);
|
||||
static int _window_id_counter = 0;
|
||||
|
||||
readonly string _window_id = $"{WINDOW_TYPE_NAME}_{Interlocked.Increment(ref _window_id_counter)}";
|
||||
[DisallowNull]
|
||||
readonly MDConsumer _consumer;
|
||||
readonly IMarketDataClient mdClient;
|
||||
[DisallowNull]
|
||||
readonly IWindowSettingsManager<GridSettings> _settings_manager;
|
||||
readonly bool _can_pause_updates;
|
||||
@@ -56,7 +54,7 @@
|
||||
public TimeAndSalesWindow(
|
||||
[DisallowNull] TimeAndSalesWindowFactory factory,
|
||||
[DisallowNull] IBus bus,
|
||||
[DisallowNull] MDConsumer consumer,
|
||||
[DisallowNull] IMarketDataClient mdClient,
|
||||
[DisallowNull] TimeAndSalesSettings state,
|
||||
[DisallowNull] IWindowSettingsManager<GridSettings> settings_manager,
|
||||
bool can_pause_updates,
|
||||
@@ -68,7 +66,7 @@
|
||||
if (bus is null) {
|
||||
throw new ArgumentNullException(nameof(bus));
|
||||
}
|
||||
_consumer = consumer ?? throw new ArgumentNullException(nameof(consumer));
|
||||
this.mdClient = mdClient ?? throw new ArgumentNullException(nameof(mdClient));
|
||||
_state = state ?? throw new ArgumentNullException(nameof(state));
|
||||
if (_state.security_criteria is null) {
|
||||
_state = _state.with(new SecurityCriteria());
|
||||
@@ -197,8 +195,7 @@
|
||||
var sec_mds_src = security_criteria_src
|
||||
.StartWith(() => _security_criteria)
|
||||
.SelectSeries(sc => sc.subscribe_md_map(all_sec_mds_src));
|
||||
var trades_source = TradesSource.create(
|
||||
_consumer, sec_mds_src, _trade_poll_interval);
|
||||
var trades_source = mdClient.Trades(null);
|
||||
trades_source = TradesSource.with_greeks(trades_source, _bus.subscribe(SparkTags.Greeks));
|
||||
trades_source = TradesSource.with_volume(
|
||||
trades_source, _bus.subscribe(SparkTags.SecuritiesTag));
|
||||
|
||||
@@ -2,39 +2,30 @@
|
||||
using bts.api;
|
||||
using bts.shell.time_and_sales;
|
||||
|
||||
using mbts;
|
||||
using mbts.co2;
|
||||
using mbts.config;
|
||||
using mbts.persist;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.settings;
|
||||
|
||||
using Spark.Api.Domain;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reactive.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
class TimeAndSalesWindowFactory : ShellWindowFactory<TimeAndSalesSettings> {
|
||||
readonly IBus _bus;
|
||||
readonly MDConsumer _consumer;
|
||||
readonly IMarketDataClient mdClient;
|
||||
readonly UserSettingsHub _settings_hub;
|
||||
|
||||
IReadOnlyDictionary<uint, SecurityMD> _securities = new Dictionary<uint, SecurityMD>();
|
||||
|
||||
public TimeAndSalesWindowFactory(
|
||||
IShellModule module, IBus bus, MDConsumer consumer, UserSettingsHub settings_hub)
|
||||
IShellModule module, IBus bus, IMarketDataClient mdClient, UserSettingsHub settings_hub)
|
||||
: base(module, TimeAndSalesWindow.WINDOW_TYPE_NAME) {
|
||||
_bus = bus;
|
||||
_consumer = consumer;
|
||||
this.mdClient = mdClient;
|
||||
_settings_hub = settings_hub;
|
||||
_dispose = Disposable.Create(
|
||||
bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s),
|
||||
bus.subscribe(SparkTags.ShowTimeAndSalesTag).OnDispatcher().Subscribe(show)
|
||||
);
|
||||
_dispose = bus.subscribe(SparkTags.ShowTimeAndSalesTag).OnDispatcher().Subscribe(show);
|
||||
}
|
||||
|
||||
public override Task<IShellWindow> load(TimeAndSalesSettings state) {
|
||||
@@ -46,7 +37,7 @@
|
||||
var win = new TimeAndSalesWindow(
|
||||
this,
|
||||
_bus,
|
||||
_consumer,
|
||||
mdClient,
|
||||
state,
|
||||
settings_man,
|
||||
conf.CanPauseUpdates,
|
||||
|
||||
@@ -9,6 +9,7 @@ using mbts.ui.shell;
|
||||
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core;
|
||||
using Spark.Core.Services;
|
||||
|
||||
@@ -23,14 +24,22 @@ class SparkAppService : IHostedService {
|
||||
readonly ISparkLoginGuiService loginService;
|
||||
readonly Api.IServiceProvider serviceProvider;
|
||||
readonly ServiceContext internalServiceContext;
|
||||
readonly IMarketDataClient marketDataClient;
|
||||
SparkApp? sparkApp;
|
||||
|
||||
public SparkAppService(
|
||||
ISparkConfigLoader sparkConfigLoader, ISparkLoginGuiService loginService, Api.IServiceProvider serviceProvider, ServiceContext internalServiceContext, IEnumerable<IDataStreamFactory> streamFactories) {
|
||||
ISparkConfigLoader sparkConfigLoader,
|
||||
ISparkLoginGuiService loginService,
|
||||
Api.IServiceProvider serviceProvider,
|
||||
ServiceContext internalServiceContext,
|
||||
IMarketDataClient marketDataClient,
|
||||
IEnumerable<IDataStreamFactory> streamFactories
|
||||
) {
|
||||
this.sparkConfigLoader = sparkConfigLoader;
|
||||
this.loginService = loginService;
|
||||
this.serviceProvider = serviceProvider;
|
||||
this.internalServiceContext = internalServiceContext;
|
||||
this.marketDataClient = marketDataClient;
|
||||
this.streamFactories = new(streamFactories);
|
||||
}
|
||||
|
||||
@@ -50,6 +59,7 @@ class SparkAppService : IHostedService {
|
||||
StreamFactories = streamFactories,
|
||||
ServiceProvider = serviceProvider,
|
||||
InternalServiceContext = internalServiceContext,
|
||||
MarketDataClient = marketDataClient,
|
||||
UserTuple = loginResult.user.assert_value(),
|
||||
Workspace = workspace,
|
||||
Token = token,
|
||||
|
||||
@@ -54,7 +54,7 @@ class SparkLoginGuiService : IHostedService, ISparkLoginGuiService {
|
||||
void OnLoggedIn() {
|
||||
var (userName, userId, token) = model.get_user();
|
||||
var workspace = model.get_workspace();
|
||||
loginTcs.SetResult((new LoginResult() { user = new(userId, userName), success = true }, token, workspace));
|
||||
loginTcs.SetResult((new LoginResult() { user = new(userId, userName), Token = token, success = true, }, token, workspace));
|
||||
view.Close();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -31,7 +31,7 @@ public static class SparkServices {
|
||||
.AddMarketDataStreams();
|
||||
var pubSubCfg = configurationSection.GetSection("PubSub");
|
||||
if (pubSubCfg is not null && pubSubCfg.GetValue("Enabled", true)) {
|
||||
services.AddPubSubClient(configurationSection.GetSection("PubSub"))
|
||||
services.AddPubSubClient(pubSubCfg)
|
||||
.AddPubTableBroker()
|
||||
.AddRemoteQueryManager()
|
||||
.AddTableStreams();
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
using mbts.config;
|
||||
using mbts.ui.extensions;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Services;
|
||||
|
||||
@@ -36,6 +37,7 @@
|
||||
public ISparkConfigLoader ConfigLoader { get; set; }
|
||||
public IEnumerable<IDataStreamFactory> StreamFactories { get; set; }
|
||||
public ServiceContext InternalServiceContext { get; set; }
|
||||
public IMarketDataClient MarketDataClient { get; set; }
|
||||
public Spark.Api.IServiceProvider ServiceProvider { get; set; }
|
||||
public UserTuple UserTuple { get; set; }
|
||||
public AuthTokenImmutable? Token { get; set; }
|
||||
@@ -135,7 +137,7 @@
|
||||
ConfigLoader = ConfigLoader,
|
||||
StreamFactories = StreamFactories,
|
||||
};
|
||||
_model.Initialize(ServiceProvider, InternalServiceContext);
|
||||
_model.Initialize(ServiceProvider, InternalServiceContext, MarketDataClient);
|
||||
if (Configuration.get<bts.config.ShellRenderMode>().SoftwareOnly) {
|
||||
System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace mbts.ui.shell {
|
||||
|
||||
using mbts.ui.native;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core.Services;
|
||||
|
||||
using System;
|
||||
@@ -39,6 +40,7 @@ namespace mbts.ui.shell {
|
||||
public IEnumerable<IDataStreamFactory> StreamFactories { get; set; }
|
||||
public bts.api.core.ServiceContext InternalServiceContext { get; set; }
|
||||
public Spark.Api.IServiceProvider ServiceProvider { get; set; }
|
||||
public IMarketDataClient MarketDataClient { get; set; }
|
||||
public UserTuple UserTuple { get; set; }
|
||||
public bts.api.AuthTokenImmutable? Token { get; set; }
|
||||
public string Workspace { get; set; }
|
||||
@@ -84,6 +86,7 @@ namespace mbts.ui.shell {
|
||||
StreamFactories = StreamFactories,
|
||||
InternalServiceContext = InternalServiceContext,
|
||||
ServiceProvider = ServiceProvider,
|
||||
MarketDataClient = MarketDataClient,
|
||||
UserTuple = UserTuple,
|
||||
Workspace = Workspace,
|
||||
Token = Token,
|
||||
|
||||
@@ -15,7 +15,14 @@
|
||||
},
|
||||
"EnableAdmin": true,
|
||||
"EnableOrders": true,
|
||||
"EnablePosition": true
|
||||
"EnablePosition": true,
|
||||
"MarketData": {
|
||||
"NumDepthLevels": 5,
|
||||
"HotPollInterval": "00:00:00.1",
|
||||
"ColdPollInterval": "00:00:01",
|
||||
"RelayThrottle": "00:00:00.1",
|
||||
"SecurityOutputInterval": "00:00:01"
|
||||
}
|
||||
},
|
||||
"MasterWorker": {
|
||||
"Interval": "00:00:00.1"
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
|
||||
using Spark;
|
||||
using Spark.Api.Data;
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Api.Reactive;
|
||||
using Spark.Core.Data;
|
||||
using Spark.Core.Services;
|
||||
@@ -48,6 +49,12 @@
|
||||
public ISparkConfigLoader ConfigLoader { get; set; }
|
||||
}
|
||||
|
||||
[Export]
|
||||
public class MarketDataClientExporter {
|
||||
[Export]
|
||||
public IMarketDataClient MarketDataClient { get; set; }
|
||||
}
|
||||
|
||||
[Export]
|
||||
public class StreamFactoryExporter {
|
||||
[Export]
|
||||
@@ -83,9 +90,10 @@
|
||||
public string Workspace { get; set; }
|
||||
public ISparkConfigLoader ConfigLoader { get; set; }
|
||||
public IEnumerable<IDataStreamFactory> StreamFactories { get; set; }
|
||||
public IMarketDataClient MarketDataClient { get; set; }
|
||||
|
||||
public void Initialize(Spark.Api.IServiceProvider serviceProvider, ServiceContext internalServiceContext) {
|
||||
PerformMEFComposition(serviceProvider, internalServiceContext);
|
||||
public void Initialize(Spark.Api.IServiceProvider serviceProvider, ServiceContext internalServiceContext, IMarketDataClient mdClient) {
|
||||
PerformMEFComposition(serviceProvider, internalServiceContext, mdClient);
|
||||
InitInitializers();
|
||||
}
|
||||
|
||||
@@ -124,7 +132,7 @@
|
||||
return value;
|
||||
}
|
||||
|
||||
void PerformMEFComposition(Spark.Api.IServiceProvider serviceProvider, ServiceContext internalServiceContext) {
|
||||
void PerformMEFComposition(Spark.Api.IServiceProvider serviceProvider, ServiceContext internalServiceContext, IMarketDataClient mdClient) {
|
||||
Log.Ui.info($"Generating MEF dependencies for the shell" +
|
||||
$"({typeof(IInitializable)}s, {typeof(IShellModule)}s, " +
|
||||
$"{typeof(IShellDaemon)}s, etc.)");
|
||||
@@ -137,6 +145,8 @@
|
||||
credentials.Token_Export = Token_Export;
|
||||
credentials.Workspace = Workspace;
|
||||
credentials.ConfigLoader = ConfigLoader;
|
||||
var mdClientExporter = container.GetExport<MarketDataClientExporter>();
|
||||
mdClientExporter.MarketDataClient = mdClient;
|
||||
container.GetExport<StreamFactoryExporter>().StreamFactories = StreamFactories;
|
||||
container.SatisfyImports(this);
|
||||
} catch (ReflectionTypeLoadException rtlex) {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
#nullable enable
|
||||
namespace Spark.Api.MarketData;
|
||||
|
||||
using bts.api;
|
||||
using bts.api.core;
|
||||
|
||||
using mbts.spark;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public interface IMarketDataClient {
|
||||
IObservable<TableUpdate<SecurityImmutable, uint>> Securities(Func<SecurityImmutable, bool>? includeSecurity);
|
||||
IObservable<TableUpdate<BookTuple, uint>> Books(Func<SecurityImmutable, bool>? includeSecurity);
|
||||
IObservable<IList<TradeInfo>> Trades(Func<SecurityImmutable, bool>? includeSecurity);
|
||||
IObservable<TableUpdate<PriceStats, uint>> PriceStats(Func<SecurityImmutable, bool>? includeSecurity);
|
||||
IObservable<TableUpdate<PriceTicker, uint>> PriceTicker(Func<SecurityImmutable, bool>? includeSecurity);
|
||||
}
|
||||
|
||||
public static class MarketDataClientExtensions {
|
||||
public static IObservable<TableUpdate<SecurityImmutable, uint>> Securities(this IMarketDataClient marketDataClient) =>
|
||||
marketDataClient.Securities(null);
|
||||
|
||||
public static IObservable<TableUpdate<SecurityImmutable, uint>> Securities(this IMarketDataClient marketDataClient, SecurityCriteria? securityCriteria) =>
|
||||
marketDataClient.Securities(securityCriteria?.is_defined() ?? false ? securityCriteria.includes : null);
|
||||
|
||||
public static IObservable<TableUpdate<BookTuple, uint>> Books(this IMarketDataClient marketDataClient) =>
|
||||
marketDataClient.Books(null);
|
||||
|
||||
public static IObservable<TableUpdate<BookTuple, uint>> Books(this IMarketDataClient marketDataClient, SecurityCriteria? securityCriteria) =>
|
||||
marketDataClient.Books(securityCriteria?.is_defined() ?? false ? securityCriteria.includes : null);
|
||||
|
||||
public static IObservable<IList<TradeInfo>> Trades(this IMarketDataClient marketDataClient) =>
|
||||
marketDataClient.Trades(null);
|
||||
|
||||
public static IObservable<IList<TradeInfo>> Trades(this IMarketDataClient marketDataClient, SecurityCriteria? securityCriteria) =>
|
||||
marketDataClient.Trades(securityCriteria?.is_defined() ?? false ? securityCriteria.includes : null);
|
||||
|
||||
public static IObservable<TableUpdate<PriceStats, uint>> PriceStats(this IMarketDataClient marketDataClient) =>
|
||||
marketDataClient.PriceStats(null);
|
||||
|
||||
public static IObservable<TableUpdate<PriceStats, uint>> PriceStats(this IMarketDataClient marketDataClient, SecurityCriteria? securityCriteria) =>
|
||||
marketDataClient.PriceStats(securityCriteria?.is_defined() ?? false ? securityCriteria.includes : null);
|
||||
|
||||
public static IObservable<TableUpdate<PriceTicker, uint>> PriceTicker(this IMarketDataClient marketDataClient) =>
|
||||
marketDataClient.PriceTicker(null);
|
||||
|
||||
public static IObservable<TableUpdate<PriceTicker, uint>> PriceTicker(this IMarketDataClient marketDataClient, SecurityCriteria? securityCriteria) =>
|
||||
marketDataClient.PriceTicker(securityCriteria?.is_defined() ?? false ? securityCriteria.includes : null);
|
||||
}
|
||||
@@ -1,245 +1,210 @@
|
||||
#nullable enable
|
||||
namespace bts.md {
|
||||
using bts.api;
|
||||
using bts.api.core;
|
||||
using bts.collections;
|
||||
using bts.utils;
|
||||
namespace Spark.Api.Services;
|
||||
|
||||
using mbts;
|
||||
using mbts.co2;
|
||||
using mbts.spark;
|
||||
using bts;
|
||||
using bts.api;
|
||||
using bts.api.core;
|
||||
using bts.co2;
|
||||
using bts.collections;
|
||||
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core;
|
||||
using Spark.Core.Reactive;
|
||||
using mbts;
|
||||
using mbts.co2;
|
||||
using mbts.spark;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
public class MarketDataClient {
|
||||
readonly MDSource _source;
|
||||
readonly TimeSpan _poll_interval;
|
||||
readonly TimeSpan _slow_poll_interval;
|
||||
readonly uint _num_depth_levels;
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
using Spark.Core.Services;
|
||||
|
||||
public MarketDataClient(MDSource source)
|
||||
: this(source, 5, TimeSpan.FromSeconds(0.1), TimeSpan.FromSeconds(1)) { }
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
public MarketDataClient(
|
||||
MDSource source,
|
||||
uint num_depth_levels,
|
||||
TimeSpan poll_interval,
|
||||
TimeSpan slow_poll_interval) {
|
||||
_source = source;
|
||||
_poll_interval = poll_interval;
|
||||
if (slow_poll_interval < poll_interval) {
|
||||
Log.Api.warn("MarketDataClient 'slow_poll_interval' smaller than 'poll_interval'");
|
||||
}
|
||||
_slow_poll_interval = slow_poll_interval;
|
||||
_num_depth_levels = num_depth_levels;
|
||||
}
|
||||
public class MarketDataClient : IMarketDataClient {
|
||||
readonly ISubject<MDConsumer> mdConsumerSrc = new ReplaySubject<MDConsumer>(1);
|
||||
readonly IObservable<ConcurrentDictionary<uint, SecurityMD>> securitiesSrc;
|
||||
readonly List<IDisposable> _resources = new();
|
||||
readonly MarketDataConfig config;
|
||||
// The Co2RelayControl manages the grpc subscription to md under the hood (in c++).
|
||||
// Even though it's not directly used by this class, we store it in a member var to
|
||||
// keep the subscription alive.
|
||||
Co2RelayControl? relay;
|
||||
volatile bool isDisposed;
|
||||
|
||||
public IObservable<IReadOnlyDictionary<uint, SecurityImmutable>> securities(
|
||||
SecurityCriteria? criteria = null) =>
|
||||
criteria.subscribe(_source.subscribe_securities())
|
||||
.Select(secs => secs.ToDictionary(s => s.Id));
|
||||
public MarketDataClient(ISparkConfigLoader configLoader, ISparkdLoginService loginService, IUserDataPermissions userDataPermissions, IOptions<MarketDataConfig> config)
|
||||
: this(configLoader, loginService, userDataPermissions, config.Value) { }
|
||||
|
||||
public IObservable<TableUpdate<SecurityImmutable, uint>> securities_incremental(SecurityCriteria? criteria = null) =>
|
||||
securities_incremental(criteria is null ? null : criteria.includes);
|
||||
|
||||
public IObservable<TableUpdate<SecurityImmutable, uint>> securities_incremental(Func<SecurityImmutable, bool>? filter) {
|
||||
var secs_src = _source.subscribe_securities().ToSelector(
|
||||
sec_mds => MappedDictionary.create(sec_mds, s => s.security));
|
||||
if (filter is not null) {
|
||||
secs_src = secs_src.extend(
|
||||
secs => new FilteredDictionary<uint, SecurityImmutable>(secs, filter));
|
||||
}
|
||||
return secs_src.Table(s => s.Id);
|
||||
}
|
||||
|
||||
public IObservable<TableUpdate<BookTuple, uint>> books(SecurityCriteria? criteria = null) =>
|
||||
books(criteria is null || !criteria.is_defined() ? null :
|
||||
new Func<SecurityImmutable, bool>(s => criteria.includes(s)));
|
||||
|
||||
public IObservable<TableUpdate<BookTuple, uint>> books(Func<SecurityImmutable, bool>? filter) {
|
||||
// This MDSource's IObservable provides callbacks when a security is added or removed, but
|
||||
// doesn't detect book changes. To avoid maintaining complicated state, create a brand new
|
||||
// IObservable of book updates whenever the securities change.
|
||||
var secs = _source.subscribe_securities();
|
||||
var filtered_secs = filter is null ?
|
||||
secs.Select(mds => mds.Values) :
|
||||
secs.Select(mds => mds.Values.Where(md => filter(md.security)));
|
||||
return filtered_secs.Select(fixed_sec_market_data).FlattenTableSeries();
|
||||
|
||||
IObservable<TableUpdate<BookTuple, uint>> fixed_sec_market_data(
|
||||
IEnumerable<SecurityMD> security_mds) {
|
||||
// Convert 'security_mds' to a list of PollableBooks.
|
||||
var cached_books = security_mds
|
||||
.Select(s => new PollableBook(s, _num_depth_levels))
|
||||
.ToList();
|
||||
|
||||
return Observable.Interval(_poll_interval).Scan(
|
||||
TableUpdate<BookTuple, uint>.mk_empty(get_sec_id),
|
||||
poll_books);
|
||||
|
||||
uint get_sec_id(BookTuple book) =>
|
||||
book.security.Id;
|
||||
|
||||
TableUpdate<BookTuple, uint> poll_books(TableUpdate<BookTuple, uint> table, long _) {
|
||||
var bd = table.to_builder();
|
||||
foreach (var cbook in cached_books) {
|
||||
if (cbook.poll_changes()) {
|
||||
bd.add_or_update(cbook.to_book_tuple());
|
||||
public MarketDataClient(ISparkConfigLoader configLoader, ISparkdLoginService loginService, IUserDataPermissions userDataPermissions, MarketDataConfig config) {
|
||||
this.config = config;
|
||||
_resources.Add(mdConsumerSrc
|
||||
.CombineLatest(Observable.FromAsync(() => loginService.LoginAsync().AsTask()))
|
||||
.Subscribe(tup => {
|
||||
var (consumer, loginRes) = tup;
|
||||
Log.notnull(loginRes.Token);
|
||||
var relay = new Co2RelayControl(consumer, config.RelayThrottle);
|
||||
relay.preload_securities((MDRequest.Types.Flags)0xff).ignore();
|
||||
relay.set_token(loginRes.Token.Value);
|
||||
this.relay = relay;
|
||||
}));
|
||||
securitiesSrc = mdConsumerSrc
|
||||
.SelectSeries(consumer => Log.notnull(consumer.on_security)
|
||||
.Buffer(config.SecurityPollInterval)
|
||||
.Select(buffer => buffer.SelectMany(_ => _).Where(SecFilter))
|
||||
.Where(buffer => buffer.Any())
|
||||
.Scan(
|
||||
new ConcurrentDictionary<uint, SecurityMD>(),
|
||||
(cache, new_secs) => {
|
||||
foreach (var sec in new_secs) {
|
||||
var sec_md = new SecurityMD(new(sec.security), sec.handle);
|
||||
cache.AddOrUpdate(sec.security.Id, sec_md, (_, _) => sec_md);
|
||||
}
|
||||
}
|
||||
return bd.to_table();
|
||||
return cache;
|
||||
}))
|
||||
.Replay(1)
|
||||
.ToObservable();
|
||||
// Log md errors
|
||||
_resources.Add(securitiesSrc.Subscribe(_ => { }, e => Log.Md.error(e.ToString())));
|
||||
// Init the consumer in background. Once it's ready, md will start flowing.
|
||||
Task.Run(InitConsumer).ignore();
|
||||
|
||||
bool SecFilter(SecurityAndHandle sec) =>
|
||||
sec.security.ContractCase != Security.ContractOneofCase.Synthetic ||
|
||||
userDataPermissions.Allow(sec.security.Synthetic.UserId);
|
||||
|
||||
void InitConsumer() {
|
||||
// Wait until config has been loaded before creating the MDConsumer (otherwise it
|
||||
// loads the default symbols, instead of those from the config server).
|
||||
var configTask = configLoader.InitializeAsync(CancellationToken.None);
|
||||
var lastLogTime = DateTime.MinValue;
|
||||
var logInterval = TimeSpan.FromSeconds(1);
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
for (var sw = Stopwatch.StartNew(); !configTask.IsCompleted; Thread.Sleep(100)) {
|
||||
if (isDisposed) {
|
||||
mdConsumerSrc.OnCompleted();
|
||||
return;
|
||||
}
|
||||
if (stopwatch.Elapsed > logInterval) {
|
||||
Log.Api.warn($"MarketDataService waiting for config");
|
||||
stopwatch.Restart();
|
||||
}
|
||||
}
|
||||
mdConsumerSrc.OnNext(new());
|
||||
}
|
||||
}
|
||||
|
||||
public IObservable<IList<TradeInfo>> trades(TradesSubscriptionFilter filter) {
|
||||
var sec_mds = filter.security_criteria == null ?
|
||||
_source.subscribe_securities() :
|
||||
filter.security_criteria.subscribe_md_map(_source.subscribe_securities());
|
||||
return TradesSource.create(_source.consumer, sec_mds, _poll_interval);
|
||||
public IObservable<TableUpdate<SecurityImmutable, uint>> Securities(Func<SecurityImmutable, bool>? includeSecurity) {
|
||||
var src = securitiesSrc.ToSelector(secMds => MappedDictionary.create(secMds, s => s.security));
|
||||
if (includeSecurity is not null) {
|
||||
src = src.extend(secs => new FilteredDictionary<uint, SecurityImmutable>(secs, includeSecurity));
|
||||
}
|
||||
return src.Table(s => s.Id);
|
||||
}
|
||||
|
||||
public IObservable<TableUpdate<PriceTicker, uint>> price_ticker(
|
||||
SecurityCriteria? criteria = null) {
|
||||
// This MDSource's IObservable provides callbacks when a security is added or removed, but
|
||||
// doesn't detect ticker changes. To avoid maintaining complicated state, create a brand new
|
||||
// IObservable of ticker updates whenever the securities change.
|
||||
return criteria.subscribe_md(_source.subscribe_securities())
|
||||
.Select(fixed_sec_price_tickers)
|
||||
.FlattenTableSeries();
|
||||
public IObservable<TableUpdate<BookTuple, uint>> Books(Func<SecurityImmutable, bool>? includeSecurity) {
|
||||
// This MDSource's IObservable provides callbacks when a security is added or removed, but
|
||||
// doesn't detect book changes. To avoid maintaining complicated state, create a brand new
|
||||
// IObservable of book updates whenever the securities change.
|
||||
var filteredSecs = includeSecurity is null ?
|
||||
securitiesSrc.Select(mds => mds.Values) :
|
||||
securitiesSrc.Select(mds => mds.Values.Where(md => includeSecurity(md.security)));
|
||||
return filteredSecs.Select(fixed_sec_market_data).FlattenTableSeries();
|
||||
|
||||
IObservable<TableUpdate<PriceTicker, uint>> fixed_sec_price_tickers(
|
||||
IEnumerable<SecurityMD> security_mds) {
|
||||
// Convert 'security_mds' to a list of PollablePriceTickers.
|
||||
var cached_tickers = security_mds
|
||||
.Select(s => new PollablePriceTicker(s))
|
||||
.ToList();
|
||||
IObservable<TableUpdate<BookTuple, uint>> fixed_sec_market_data(
|
||||
IEnumerable<SecurityMD> security_mds) {
|
||||
// Convert 'security_mds' to a list of PollableBooks.
|
||||
var cached_books = security_mds
|
||||
.Select(s => new PollableBook(s, config.NumDepthLevels))
|
||||
.ToList();
|
||||
|
||||
return Observable.Interval(_poll_interval).Scan(
|
||||
TableUpdate<PriceTicker, uint>.mk_empty(get_sec_id),
|
||||
poll_tickers);
|
||||
return Observable.Interval(config.HotPollInterval).Scan(
|
||||
TableUpdate<BookTuple, uint>.mk_empty(GetSecId),
|
||||
PollBooks);
|
||||
|
||||
uint get_sec_id(PriceTicker ticker) =>
|
||||
ticker.security.Id;
|
||||
uint GetSecId(BookTuple book) =>
|
||||
book.security.Id;
|
||||
|
||||
TableUpdate<PriceTicker, uint> poll_tickers(TableUpdate<PriceTicker, uint> table, long _) {
|
||||
bool is_first_update = table.state.Count == 0;
|
||||
var bd = table.to_builder();
|
||||
foreach (var cticker in cached_tickers) {
|
||||
if (cticker.poll_changes() || is_first_update) {
|
||||
bd.add_or_update(cticker.to_ticker());
|
||||
}
|
||||
TableUpdate<BookTuple, uint> PollBooks(TableUpdate<BookTuple, uint> table, long _) {
|
||||
var bd = table.to_builder();
|
||||
foreach (var cbook in cached_books) {
|
||||
if (cbook.poll_changes()) {
|
||||
bd.add_or_update(cbook.to_book_tuple());
|
||||
}
|
||||
return bd.to_table();
|
||||
}
|
||||
return bd.to_table();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IObservable<TableUpdate<PriceStats, uint>> price_stats(
|
||||
SecurityCriteria? criteria = null) {
|
||||
// This MDSource's IObservable provides callbacks when a security is added or removed, but
|
||||
// doesn't detect stats changes. To avoid maintaining complicated state, create a brand new
|
||||
// IObservable of stats updates whenever the securities change.
|
||||
return criteria.subscribe_md(_source.subscribe_securities())
|
||||
.Select(fixed_sec_price_stats)
|
||||
.FlattenTableSeries();
|
||||
|
||||
IObservable<TableUpdate<PriceStats, uint>> fixed_sec_price_stats(
|
||||
IEnumerable<SecurityMD> security_mds) {
|
||||
// Convert 'security_mds' to a list of PollablePriceStats.
|
||||
var cached_statss = security_mds
|
||||
.Select(s => new PollablePriceStats(s))
|
||||
.ToList();
|
||||
|
||||
return Observable.Interval(_slow_poll_interval).Scan(
|
||||
TableUpdate<PriceStats, uint>.mk_empty(get_sec_id),
|
||||
poll_stats);
|
||||
|
||||
uint get_sec_id(PriceStats stats) =>
|
||||
stats.security.Id;
|
||||
|
||||
TableUpdate<PriceStats, uint> poll_stats(TableUpdate<PriceStats, uint> table, long _) {
|
||||
bool is_first_update = table.state.Count == 0;
|
||||
var bd = table.to_builder();
|
||||
foreach (var cstats in cached_statss) {
|
||||
if (cstats.poll_changes() || is_first_update) {
|
||||
bd.add_or_update(cstats.to_stats());
|
||||
}
|
||||
public IObservable<IList<TradeInfo>> Trades(Func<SecurityImmutable, bool>? includeSecurity) {
|
||||
IObservable<IReadOnlyDictionary<uint, SecurityMD>> filteredSecs = includeSecurity is null ?
|
||||
securitiesSrc :
|
||||
securitiesSrc.Select(mds => new FilteredDictionary<uint, SecurityMD>(mds, md => includeSecurity(md.security)));
|
||||
return mdConsumerSrc.SelectSeries(consumer => securitiesSrc.Scan(
|
||||
(channels: ImmutableDictionary<ProductImmutable, ChannelConsumer>.Empty, active: new List<ChannelConsumer>(0)),
|
||||
(channel_data, map) => {
|
||||
var (channels, active) = channel_data;
|
||||
var products = map.Values.Select(s => s.security.product()).Distinct();
|
||||
active = new List<ChannelConsumer>();
|
||||
foreach (var p in products) {
|
||||
if (!channels.TryGetValue(p, out var c)) {
|
||||
c = new ChannelConsumer(
|
||||
consumer.get_channel(p.Symbol, p.Type, p.Exchange),
|
||||
map.Values.Where(s => s.security.product().Equals(p)));
|
||||
channels = channels.Add(p, c);
|
||||
}
|
||||
return bd.to_table();
|
||||
active.Add(c);
|
||||
}
|
||||
}
|
||||
return (channels, active);
|
||||
})
|
||||
.SelectSeries(channel_data => {
|
||||
var (channels, active) = channel_data;
|
||||
return Observable.Interval(config.TradePollInterval)
|
||||
.Select(_ => active.SelectMany(c => c.read_trades()).ToList())
|
||||
.Where(trades => trades.Count > 0);
|
||||
}));
|
||||
}
|
||||
|
||||
public IObservable<TableUpdate<PriceStats, uint>> PriceStats(Func<SecurityImmutable, bool>? includeSecurity) {
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public IObservable<TableUpdate<PriceTicker, uint>> PriceTicker(Func<SecurityImmutable, bool>? includeSecurity) {
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
GC.SuppressFinalize(this);
|
||||
isDisposed = true;
|
||||
_resources.DisposeAll(true);
|
||||
}
|
||||
|
||||
class ChannelConsumer {
|
||||
readonly MDConsumerChannel _channel;
|
||||
readonly Dictionary<uint, SecurityMD> _security_mds = new(0);
|
||||
long _cursor = 0;
|
||||
|
||||
public ChannelConsumer(MDConsumerChannel channel) =>
|
||||
_channel = channel;
|
||||
|
||||
public ChannelConsumer(MDConsumerChannel channel, IEnumerable<SecurityMD> security_mds) {
|
||||
_channel = channel;
|
||||
_security_mds = security_mds.ToDictionaryCrushed(s => s.id);
|
||||
}
|
||||
|
||||
class PollablePriceTicker {
|
||||
readonly SecurityMD _security_md;
|
||||
ulong _bbo_poll_time = 0;
|
||||
ulong _last_poll_time = 0;
|
||||
NativePriceSize _bid;
|
||||
NativePriceSize _ask;
|
||||
NativePriceSize _last;
|
||||
PriceTicker _ticker;
|
||||
ulong _volume;
|
||||
|
||||
public PollablePriceTicker(SecurityMD security_md) =>
|
||||
_security_md = security_md;
|
||||
|
||||
public PriceTicker to_ticker() =>
|
||||
_ticker;
|
||||
|
||||
public bool poll_changes() {
|
||||
var md = _security_md.md;
|
||||
md.get_bbo(ref _bbo_poll_time, out _bid, out _ask);
|
||||
md.get_last_trade(ref _last_poll_time, out _last, out _, out _volume);
|
||||
return Swap.toggle_to(ref _ticker, _mk_ticker());
|
||||
}
|
||||
|
||||
PriceTicker _mk_ticker() {
|
||||
var md = _security_md.md;
|
||||
return new(
|
||||
_security_md.security,
|
||||
_security_md.quantity_display,
|
||||
md.session_high,
|
||||
md.session_low,
|
||||
_volume,
|
||||
_bid.price,
|
||||
_bid.size,
|
||||
_ask.price,
|
||||
_ask.size,
|
||||
md.fixing_price,
|
||||
_last.price,
|
||||
_last.size);
|
||||
}
|
||||
}
|
||||
|
||||
class PollablePriceStats {
|
||||
readonly SecurityMD _security_md;
|
||||
PriceStats _stats;
|
||||
|
||||
public PollablePriceStats(SecurityMD security_md) {
|
||||
_security_md = security_md;
|
||||
_stats = _mk_stats();
|
||||
}
|
||||
|
||||
public PriceStats to_stats() =>
|
||||
_stats;
|
||||
|
||||
public bool poll_changes() =>
|
||||
Swap.toggle_to(ref _stats, _mk_stats());
|
||||
PriceStats _mk_stats() {
|
||||
var md = _security_md.md;
|
||||
return new(
|
||||
_security_md.security,
|
||||
md.open_price,
|
||||
md.close_price,
|
||||
md.settlement_price);
|
||||
public IEnumerable<TradeInfo> read_trades() {
|
||||
foreach (var tm in _channel.read_trades(ref _cursor)) {
|
||||
if (tm != null && _security_mds.TryGetValue(tm.Key, out var smd))
|
||||
yield return new TradeInfo(
|
||||
smd, new TradeMessageImmutable(tm));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
#nullable enable
|
||||
namespace Spark.Api.Services;
|
||||
|
||||
using System;
|
||||
|
||||
public class MarketDataConfig {
|
||||
public uint NumDepthLevels { get; set; } = 5;
|
||||
public TimeSpan HotPollInterval { get; set; } = TimeSpan.FromSeconds(0.1);
|
||||
public TimeSpan ColdPollInterval { get; set; } = TimeSpan.FromSeconds(1);
|
||||
public TimeSpan TradePollInterval { get; set; } = TimeSpan.FromSeconds(0.4);
|
||||
public TimeSpan RelayThrottle { get; set; } = TimeSpan.FromSeconds(0.1);
|
||||
public TimeSpan SecurityPollInterval { get; set; } = TimeSpan.FromSeconds(1);
|
||||
|
||||
public static MarketDataConfig Default =>
|
||||
new() {
|
||||
NumDepthLevels = 5,
|
||||
HotPollInterval = TimeSpan.FromSeconds(0.1),
|
||||
ColdPollInterval = TimeSpan.FromSeconds(1),
|
||||
TradePollInterval = TimeSpan.FromSeconds(0.4),
|
||||
RelayThrottle = TimeSpan.FromSeconds(0.1),
|
||||
SecurityPollInterval = TimeSpan.FromSeconds(1),
|
||||
};
|
||||
}
|
||||
@@ -13,6 +13,7 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
|
||||
using Spark.Api.Admin;
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Api.Orders;
|
||||
using Spark.Api.Reactive;
|
||||
using Spark.Core.Services;
|
||||
@@ -55,8 +56,10 @@ public static class SparkApiServices {
|
||||
if (configurationSection.GetValue("EnableMarketData", true)) {
|
||||
services.AddSparkdService<MarketDataRelay>()
|
||||
.AddSingleton<IUserDataPermissions, UserDataPermissions>()
|
||||
.AddSingleton<MDSource>()
|
||||
.AddSingleton<MarketDataClient>();
|
||||
.Configure<MarketDataConfig>(configurationSection.GetSection("MarketData"))
|
||||
.AddSingleton<MarketDataClient>()
|
||||
.AddSingleton<IMarketDataClient, MarketDataClient>(sp => sp.GetRequiredService<MarketDataClient>())
|
||||
.AddSingleton<MDSource>();
|
||||
}
|
||||
if (configurationSection.GetValue("EnableAdmin", true)) {
|
||||
services.AddSparkdService<AdminService>();
|
||||
|
||||
@@ -94,7 +94,7 @@ namespace bts.api.core {
|
||||
if (result.value.IsValid) {
|
||||
_token = result.value.Token;
|
||||
user = new(result.value.UserId, username);
|
||||
return new() { reason = result.value.Reason, success = true, user = user };
|
||||
return new() { reason = result.value.Reason, success = true, user = user, Token = result.value.Token };
|
||||
} else {
|
||||
return new() { reason = result.value.Reason };
|
||||
}
|
||||
@@ -143,5 +143,6 @@ namespace bts.api.core {
|
||||
public bool success { get; init; }
|
||||
public string? reason { get; init; }
|
||||
public UserTuple? user { get; init; }
|
||||
public AuthTokenImmutable? Token { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -95,9 +95,6 @@ namespace mbts.config {
|
||||
public static ValueTask<bool> InitializeAsync(string? configSource = null) =>
|
||||
InitializeAsync(configSource, CancellationToken.None);
|
||||
|
||||
public static ValueTask<bool> InitializeAsync(CancellationToken cancellationToken) =>
|
||||
InitializeAsync(null, cancellationToken);
|
||||
|
||||
public static ValueTask<bool> InitializeAsync(string? config_source, CancellationToken cancellationToken) {
|
||||
return _state switch {
|
||||
State.OK => ValueTask.FromResult(true),
|
||||
@@ -185,18 +182,6 @@ namespace mbts.config {
|
||||
_state = State.OK;
|
||||
}
|
||||
|
||||
public static bool try_initialize(out string error) {
|
||||
_reset();
|
||||
try {
|
||||
BTS.init();
|
||||
} catch (ApplicationException e) {
|
||||
error = e.Message;
|
||||
return false;
|
||||
}
|
||||
error = string.Empty;
|
||||
return true;
|
||||
}
|
||||
|
||||
[DllImport("libspark")]
|
||||
internal static extern int run_config_query(
|
||||
string[] keysv,
|
||||
|
||||
@@ -1,25 +1,22 @@
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Concurrency;
|
||||
|
||||
using bts.api;
|
||||
using bts.api.core;
|
||||
using bts.md;
|
||||
using mbts.spark;
|
||||
using Spark.Api.MarketData;
|
||||
|
||||
namespace bts.sdk
|
||||
{
|
||||
|
||||
public class MarketDataSample : IDisposable
|
||||
{
|
||||
readonly MarketDataClient _md;
|
||||
readonly IMarketDataClient _md;
|
||||
readonly List<IDisposable> _disps = new List<IDisposable>();
|
||||
public MarketDataSample(MarketDataClient client)
|
||||
public MarketDataSample(IMarketDataClient client)
|
||||
{
|
||||
_md = client;
|
||||
}
|
||||
@@ -58,7 +55,7 @@ namespace bts.sdk
|
||||
new(new[] { ven }, new[] { st }, new[] { symbol })
|
||||
});
|
||||
|
||||
_disps.Add(_md.books(criteria).Subscribe(x =>
|
||||
_disps.Add(_md.Books(criteria).Subscribe(x =>
|
||||
{
|
||||
print_update(x.added.Concat(x.changed));
|
||||
}));
|
||||
@@ -74,7 +71,7 @@ namespace bts.sdk
|
||||
var criteria = new SecurityCriteria(new SecurityCriteriaClause[] {
|
||||
new(new[] { ven }, new[] { st }, new[] { symbol })
|
||||
});
|
||||
var md_source = _md.books(criteria)
|
||||
var md_source = _md.Books(criteria)
|
||||
.Filter(b => b.security.security_desc() == security_desc);
|
||||
_disps.Add(md_source.Subscribe(x =>
|
||||
{
|
||||
|
||||
@@ -11,6 +11,7 @@ namespace bts.sdk {
|
||||
using Microsoft.Extensions.Options;
|
||||
|
||||
using Spark.Api.Admin;
|
||||
using Spark.Api.MarketData;
|
||||
using Spark.Api.Orders;
|
||||
using Spark.Api.Reactive;
|
||||
using Spark.Api.Services;
|
||||
@@ -30,6 +31,7 @@ namespace bts.sdk {
|
||||
readonly Spark.Api.IServiceProvider sparkServiceProvider;
|
||||
readonly IUserDataPermissions userDataPermissions;
|
||||
readonly ISparkdLoginService loginService;
|
||||
readonly IMarketDataClient marketDataClient;
|
||||
|
||||
OrderService orderService;
|
||||
OrdersClient ordersClient;
|
||||
@@ -42,6 +44,7 @@ namespace bts.sdk {
|
||||
ISparkConfigLoader sparkConfigLoader,
|
||||
ISparkdLoginService loginService,
|
||||
IUserDataPermissions userDataPermissions,
|
||||
IMarketDataClient marketDataClient,
|
||||
Spark.Api.IServiceProvider sparkServiceProvider,
|
||||
OrderService orderService,
|
||||
OrdersClient ordersClient,
|
||||
@@ -50,12 +53,13 @@ namespace bts.sdk {
|
||||
AdminClient adminClient,
|
||||
MarketDataRelay mdRelay,
|
||||
IOptions<SdkSampleConfig> sdkConfig)
|
||||
: this(sparkConfigLoader, loginService, userDataPermissions, sparkServiceProvider, orderService, ordersClient, positionService, adminService, adminClient, mdRelay, sdkConfig.Value) { }
|
||||
: this(sparkConfigLoader, loginService, userDataPermissions, marketDataClient, sparkServiceProvider, orderService, ordersClient, positionService, adminService, adminClient, mdRelay, sdkConfig.Value) { }
|
||||
|
||||
public SdkSampleService(
|
||||
ISparkConfigLoader sparkConfigLoader,
|
||||
ISparkdLoginService loginService,
|
||||
IUserDataPermissions userDataPermissions,
|
||||
IMarketDataClient marketDataClient,
|
||||
Spark.Api.IServiceProvider sparkServiceProvider,
|
||||
OrderService orderService,
|
||||
OrdersClient ordersClient,
|
||||
@@ -68,6 +72,7 @@ namespace bts.sdk {
|
||||
this.loginService = loginService;
|
||||
this.sparkServiceProvider = sparkServiceProvider;
|
||||
this.userDataPermissions = userDataPermissions;
|
||||
this.marketDataClient = marketDataClient;
|
||||
this.orderService = orderService;
|
||||
this.ordersClient = ordersClient;
|
||||
this.positionService = positionService;
|
||||
@@ -100,10 +105,9 @@ namespace bts.sdk {
|
||||
|
||||
await loginService.LoginAsync();
|
||||
var md_source = new MDSource(userDataPermissions);
|
||||
var md_client = new MarketDataClient(md_source);
|
||||
using (var disp = new CompositeDisposable(md_source)) {
|
||||
if (sdkConfig.MarketData is not null) {
|
||||
var s = new MarketDataSample(md_client);
|
||||
var s = new MarketDataSample(marketDataClient);
|
||||
var mdCfg = sdkConfig.MarketData;
|
||||
s.print_security(mdCfg.Exchange, mdCfg.SecurityDesc, mdCfg.Symbol, mdCfg.SecurityDesc);
|
||||
} else if (sdkConfig.Order is not null) {
|
||||
@@ -111,7 +115,6 @@ namespace bts.sdk {
|
||||
ordersClient,
|
||||
orderService,
|
||||
adminService,
|
||||
md_client,
|
||||
md_source.subscribe_securities().Select(sec_map =>
|
||||
sec_map.ToDictionary(kv => kv.Key, kv => kv.Value.security)));
|
||||
disp.Add(os);
|
||||
|
||||
@@ -29,9 +29,10 @@ namespace bts.websocket_core {
|
||||
readonly IUserDataPermissions userDataPermissions;
|
||||
readonly IDataStreamFactory streamFactory;
|
||||
|
||||
public WebsocketDataSync(Spark.Api.IServiceProvider service_ctx, IUserDataPermissions userDataPermissions, IDataStreamFactory streamFactory) {
|
||||
public WebsocketDataSync(Spark.Api.IServiceProvider service_ctx, IMarketDataClient mdClient, IUserDataPermissions userDataPermissions, IDataStreamFactory streamFactory) {
|
||||
_service_ctx = service_ctx;
|
||||
this.userDataPermissions = userDataPermissions;
|
||||
this.mdClient = mdClient;
|
||||
this.streamFactory = streamFactory;
|
||||
adminService = service_ctx.GetService<AdminService>();
|
||||
}
|
||||
@@ -126,9 +127,9 @@ namespace bts.websocket_core {
|
||||
// }
|
||||
// }
|
||||
|
||||
MarketDataClient? mdClient;
|
||||
MarketDataClient Md_Client {
|
||||
get => Log.notnull<MarketDataClient>(mdClient);
|
||||
IMarketDataClient? mdClient;
|
||||
IMarketDataClient Md_Client {
|
||||
get => Log.notnull(mdClient);
|
||||
set {
|
||||
Log.isnull(mdClient);
|
||||
mdClient = value;
|
||||
@@ -200,7 +201,6 @@ namespace bts.websocket_core {
|
||||
Gateway = gtwy;
|
||||
clients = new ClientsStore();
|
||||
MD_Source = new MDSource(userDataPermissions);
|
||||
Md_Client = new(MD_Source);
|
||||
_securities_sub = MD_Source.subscribe_securities().Subscribe(sec_map => _securities = sec_map);
|
||||
var order_service = _service_ctx.GetService<OrderService>();
|
||||
var position_service = _service_ctx.GetService<PositionService>();
|
||||
|
||||
@@ -3,7 +3,6 @@ namespace bts.websocket_core {
|
||||
|
||||
using bts.api;
|
||||
using bts.api.orderman;
|
||||
using bts.md;
|
||||
|
||||
using Bts.DataStream;
|
||||
using Bts.DataStreamCore;
|
||||
@@ -42,7 +41,7 @@ namespace bts.websocket_core {
|
||||
public IDisposable? dis;
|
||||
public void Dispose() => dis?.Dispose();
|
||||
Action<Object> _sm;
|
||||
private MarketDataClient _MdClient;
|
||||
private IMarketDataClient _MdClient;
|
||||
private OrdersClient _OrdersClient;
|
||||
public Action subscribe;
|
||||
void set_invalid(string message) {
|
||||
@@ -63,35 +62,35 @@ namespace bts.websocket_core {
|
||||
}
|
||||
private static Action<WebsocketSubscriptionHandler> GetSecuritiesSubscriber(SecurityCriteria cri) {
|
||||
return (WebsocketSubscriptionHandler hdlr) => {
|
||||
hdlr.dis = hdlr._MdClient.securities_incremental(cri).Subscribe(
|
||||
hdlr.dis = hdlr._MdClient.Securities(cri).Subscribe(
|
||||
upd =>
|
||||
hdlr.SendMessage(WebsocketJsonParsers.to_json<SecurityImmutable, uint>(upd)));
|
||||
};
|
||||
}
|
||||
private static Action<WebsocketSubscriptionHandler> GetTradesSubscriber(TradesSubscriptionFilter cri) {
|
||||
return (WebsocketSubscriptionHandler hdlr) => {
|
||||
hdlr.dis = hdlr._MdClient.trades(cri).Subscribe(
|
||||
hdlr.dis = hdlr._MdClient.Trades(cri.security_criteria).Subscribe(
|
||||
upd =>
|
||||
hdlr.SendMessage(WebsocketJsonParsers.to_json<TradeInfo>(upd)));
|
||||
};
|
||||
}
|
||||
private static Action<WebsocketSubscriptionHandler> GetBookSubscriber(SecurityCriteria cri) {
|
||||
return (WebsocketSubscriptionHandler hdlr) => {
|
||||
hdlr.dis = hdlr._MdClient.books(cri).Subscribe(
|
||||
hdlr.dis = hdlr._MdClient.Books(cri).Subscribe(
|
||||
upd =>
|
||||
hdlr.SendMessage(WebsocketJsonParsers.to_json<BookTuple, uint>(upd)));
|
||||
};
|
||||
}
|
||||
private static Action<WebsocketSubscriptionHandler> GetPriceStatsSubscriber(SecurityCriteria cri) {
|
||||
return (WebsocketSubscriptionHandler hdlr) => {
|
||||
hdlr.dis = hdlr._MdClient.price_stats(cri).Subscribe(
|
||||
hdlr.dis = hdlr._MdClient.PriceStats(cri).Subscribe(
|
||||
upd =>
|
||||
hdlr.SendMessage(WebsocketJsonParsers.to_json<PriceStats, uint>(upd)));
|
||||
};
|
||||
}
|
||||
private static Action<WebsocketSubscriptionHandler> GetPriceTickerSubscriber(SecurityCriteria cri) {
|
||||
return (WebsocketSubscriptionHandler hdlr) => {
|
||||
hdlr.dis = hdlr._MdClient.price_ticker(cri).Subscribe(
|
||||
hdlr.dis = hdlr._MdClient.PriceTicker(cri).Subscribe(
|
||||
upd =>
|
||||
hdlr.SendMessage(WebsocketJsonParsers.to_json<PriceTicker, uint>(upd)));
|
||||
};
|
||||
@@ -305,7 +304,7 @@ namespace bts.websocket_core {
|
||||
|
||||
public static bool TryCreate(
|
||||
WebsocketRequest req,
|
||||
MarketDataClient md,
|
||||
IMarketDataClient md,
|
||||
OrdersClient oc,
|
||||
IDataStreamFactory streamFactory,
|
||||
Action<Object> sm,
|
||||
@@ -393,7 +392,7 @@ namespace bts.websocket_core {
|
||||
|
||||
private WebsocketSubscriptionHandler(
|
||||
string id,
|
||||
MarketDataClient md,
|
||||
IMarketDataClient md,
|
||||
OrdersClient oc,
|
||||
Action<Object> sm,
|
||||
Action<WebsocketSubscriptionHandler> sub) {
|
||||
|
||||
Reference in new issue
Block a user