Replay streams + TC2 position
This commit is contained in:
1 parent
9140888b54
commit
6950de82ff
6 files changed
+252
-11
No files matched your search
@@ -6,6 +6,7 @@ using System.Collections.Generic;
|
||||
using BCG;
|
||||
using Bts.DataStreamCore;
|
||||
using bts.BlueOrb;
|
||||
using bts;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks active DSL subscriptions and shared DSLStream instances. Multiple clients
|
||||
@@ -44,8 +45,11 @@ public sealed class DSLBookkeeper : IDSLBookkeeper {
|
||||
|
||||
var dsl_key = _normalize_dsl(dsl);
|
||||
if (!queries_by_dsl.TryGetValue(dsl_key, out var query_state)) {
|
||||
_log_lifecycle($"DSLBookkeeper.Subscribe client_id: {client_id} creating new DSLStream dsl: {dsl_key}");
|
||||
query_state = _create_query_state(dsl_key);
|
||||
queries_by_dsl.Add(dsl_key, query_state);
|
||||
} else {
|
||||
_log_lifecycle($"DSLBookkeeper.Subscribe client_id: {client_id} reusing existing DSLStream subscription_count: {query_state.subscription_ids.Count} dsl: {dsl_key}");
|
||||
}
|
||||
|
||||
var subscription_id = Guid.NewGuid();
|
||||
@@ -65,6 +69,7 @@ public sealed class DSLBookkeeper : IDSLBookkeeper {
|
||||
}
|
||||
client_subscriptions.Add(subscription_id);
|
||||
|
||||
_log_lifecycle($"DSLBookkeeper.Subscribe client_id: {client_id} subscription_id: {subscription_id} active_subscriptions_for_dsl: {query_state.subscription_ids.Count} dsl: {dsl_key}");
|
||||
return subscription_id;
|
||||
}
|
||||
}
|
||||
@@ -138,6 +143,7 @@ public sealed class DSLBookkeeper : IDSLBookkeeper {
|
||||
}
|
||||
|
||||
QueryState _create_query_state(string dsl_key) {
|
||||
_log_lifecycle($"DSLBookkeeper._create_query_state creating DSLStream dsl: {dsl_key}");
|
||||
var stream = new DSLStream(dsl_key);
|
||||
var query_state = new QueryState {
|
||||
dsl = dsl_key,
|
||||
@@ -175,7 +181,9 @@ public sealed class DSLBookkeeper : IDSLBookkeeper {
|
||||
|
||||
if (queries_by_dsl.TryGetValue(subscription_state.dsl_key, out var query_state)) {
|
||||
query_state.subscription_ids.Remove(subscription_id);
|
||||
_log_lifecycle($"DSLBookkeeper.Unsubscribe subscription_id: {subscription_id} client_id: {subscription_state.client_id} remaining_subscriptions_for_dsl: {query_state.subscription_ids.Count} dsl: {subscription_state.dsl_key}");
|
||||
if (query_state.subscription_ids.Count == 0) {
|
||||
_log_lifecycle($"DSLBookkeeper.Unsubscribe garbage collecting DSLStream; last subscription removed dsl: {subscription_state.dsl_key}");
|
||||
_dispose_query_state(query_state);
|
||||
queries_by_dsl.Remove(subscription_state.dsl_key);
|
||||
}
|
||||
@@ -186,6 +194,7 @@ public sealed class DSLBookkeeper : IDSLBookkeeper {
|
||||
dsl.Trim();
|
||||
|
||||
static void _dispose_query_state(QueryState query_state) {
|
||||
_log_lifecycle($"DSLBookkeeper._dispose_query_state disposing DSLStream dsl: {query_state.dsl} pending_packets: {query_state.pending_packets.Count} subscription_count: {query_state.subscription_ids.Count}");
|
||||
if (query_state.stream_handler is not null) {
|
||||
query_state.stream.onChange -= query_state.stream_handler;
|
||||
query_state.stream_handler = null;
|
||||
@@ -194,6 +203,11 @@ public sealed class DSLBookkeeper : IDSLBookkeeper {
|
||||
query_state.pending_packets.Clear();
|
||||
}
|
||||
|
||||
static void _log_lifecycle(string message) {
|
||||
Console.WriteLine(message);
|
||||
Log.Gen.info(message);
|
||||
}
|
||||
|
||||
void _throw_if_disposed() {
|
||||
if (disposed) {
|
||||
throw new ObjectDisposedException(nameof(DSLBookkeeper));
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
[DataStreamUserRespresentation("LiveFuturesTradeStream")]
|
||||
public class LiveFuturesTradeStream : ViewStream {
|
||||
public LiveFuturesTradeStream(string future_target) {
|
||||
var rs = new ReplayFutureLiveTradeStream(future_target);
|
||||
mySetRealSource(rs);
|
||||
var rs = new ReplayWithBasesetFutureLiveTradeStream(future_target, 250);
|
||||
mySetRealSource(rs);
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -7,7 +7,6 @@
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
[DataStreamUserRespresentation("ReplayFutureLiveTradeStream")]
|
||||
public class ReplayFutureLiveTradeStream : ViewStream, BCG.Utilities.General.IWorker {
|
||||
private class LastFireTime {
|
||||
public DateTime last_fireitme_file = DateTime.MinValue;
|
||||
@@ -40,7 +39,7 @@
|
||||
Tuple.Create("contract", TypeCode.String),
|
||||
Tuple.Create("trade_size", TypeCode.Double),
|
||||
Tuple.Create("trade_price", TypeCode.Double),
|
||||
Tuple.Create("aggressor_side", TypeCode.String));
|
||||
Tuple.Create("aggressor_side", TypeCode.String));
|
||||
rs = new MapStream(rs, s => schema_out,
|
||||
r =>
|
||||
new BlueRow(schema_out, r["id"], /*r.get<string>("ts_event")*/iso_8601_now(), r.get<string>("symbol"),
|
||||
@@ -94,4 +93,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
namespace bts.BlueOrb {
|
||||
using BCG;
|
||||
|
||||
using Spark.Core.Diagnostics;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
static class ReplayWithBasesetFutureLiveTradeRowCache {
|
||||
static readonly object lock_obj = new();
|
||||
static readonly Dictionary<string, List<IBlueRow>> rows_by_file_path = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public static List<IBlueRow> GetRows(string file_path) {
|
||||
lock (lock_obj) {
|
||||
if (!rows_by_file_path.TryGetValue(file_path, out var rows)) {
|
||||
Log.Gen.info($"ReplayWithBasesetFutureLiveTradeRowCache loading rows file_path: {file_path}");
|
||||
var loaded_rows = BCG.CSVReaderStream.LoadFile(file_path);
|
||||
rows = loaded_rows
|
||||
.OfType<IBlueRow>()
|
||||
.OrderBy(r => r.get<string>("ts_event"))
|
||||
.ToList();
|
||||
rows_by_file_path.Add(file_path, rows);
|
||||
Log.Gen.info($"ReplayWithBasesetFutureLiveTradeRowCache cached rows count: {rows.Count} file_path: {file_path}");
|
||||
} else {
|
||||
Log.Gen.info($"ReplayWithBasesetFutureLiveTradeRowCache reusing cached rows count: {rows.Count} file_path: {file_path}");
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[DataStreamUserRespresentation("ReplayWithBasesetFutureLiveTradeStream")]
|
||||
public class ReplayWithBasesetFutureLiveTradeStream : ViewStream, BCG.Utilities.General.IWorker {
|
||||
private class LastFireTime {
|
||||
public DateTime last_fireitme_file = DateTime.MinValue;
|
||||
public DateTime last_firetime_clock = DateTime.MinValue;
|
||||
}
|
||||
|
||||
private class RowsWithPointer {
|
||||
public List<IBlueRow>? rows;
|
||||
public int pointer;
|
||||
}
|
||||
|
||||
readonly ViewStreamDatabase? _vsd;
|
||||
readonly ContractUtils.FutureContinousContract? _fcc;
|
||||
readonly int _baseset_size;
|
||||
readonly LastFireTime _last_fire_time = new();
|
||||
readonly RowsWithPointer _rows = new();
|
||||
bool _is_worker_registered;
|
||||
|
||||
public ReplayWithBasesetFutureLiveTradeStream(string continous_contract, int baseset_size) {
|
||||
ViewStream rs = new ReplayWithBasesetFutureLiveTradeStream(continous_contract, baseset_size, true);
|
||||
IBlueTableSchema schema_out = BlueDataUtility.form_schema("BBO",
|
||||
Tuple.Create("id", TypeCode.Int32),
|
||||
Tuple.Create("ts_event", TypeCode.String),
|
||||
Tuple.Create("contract", TypeCode.String),
|
||||
Tuple.Create("trade_size", TypeCode.Double),
|
||||
Tuple.Create("trade_price", TypeCode.Double),
|
||||
Tuple.Create("aggressor_side", TypeCode.String));
|
||||
rs = new MapStream(rs, s => schema_out,
|
||||
r =>
|
||||
new BlueRow(schema_out, r["id"], r.get<string>("ts_event"), r.get<string>("symbol"),
|
||||
r.get<double>("size"), r.get<double>("price"),
|
||||
r.get<string>("side").StartsWith("B") ? "BUY" : (r.get<string>("side").StartsWith("A") ? "SELL" : "NONE")));
|
||||
rs = new TimeSeriesStream(rs);
|
||||
mySetRealSource(rs);
|
||||
}
|
||||
|
||||
private ReplayWithBasesetFutureLiveTradeStream(string continous_contract, int baseset_size, bool noop)
|
||||
: this(ViewStreamDatabase.instance, new ContractUtils.FutureContract(continous_contract), baseset_size) { }
|
||||
|
||||
public ReplayWithBasesetFutureLiveTradeStream(ViewStreamDatabase vsd, ContractUtils.FutureContract fc, int baseset_size) {
|
||||
if (baseset_size < 0) {
|
||||
throw new ArgumentOutOfRangeException(nameof(baseset_size), "baseset_size cannot be negative.");
|
||||
}
|
||||
|
||||
var fcc = fc.continous_constract;
|
||||
Log.assert(fcc != null);
|
||||
_vsd = vsd;
|
||||
_fcc = fcc;
|
||||
_baseset_size = baseset_size;
|
||||
}
|
||||
|
||||
protected override void myOnFirstSubscriber() {
|
||||
Log.notnull(_vsd);
|
||||
Log.notnull(_fcc);
|
||||
var file_path = Path.Combine(SQLiteHelper.location, $"trades_{_fcc.Symbol}.csv");
|
||||
_rows.rows = ReplayWithBasesetFutureLiveTradeRowCache.GetRows(file_path);
|
||||
_rows.pointer = 0;
|
||||
|
||||
_fire_baseset();
|
||||
|
||||
if (_rows.pointer < _rows.rows.Count) {
|
||||
ExceptionAssert.NotNull(_vsd).addWorker(this);
|
||||
_is_worker_registered = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void myOnLastSubscriber() {
|
||||
if (_is_worker_registered) {
|
||||
ExceptionAssert.NotNull(_vsd).removeWorker(this);
|
||||
_is_worker_registered = false;
|
||||
}
|
||||
}
|
||||
|
||||
public void doWork() {
|
||||
var rows = ExceptionAssert.NotNull(_rows.rows);
|
||||
if (_rows.pointer >= rows.Count) {
|
||||
return;
|
||||
}
|
||||
|
||||
IBlueRow cand_row = rows[_rows.pointer];
|
||||
string cand_ts_event = cand_row.get<string>("ts_event");
|
||||
DateTime cand_ts_event_dt = DateTime.Parse(cand_ts_event, null, System.Globalization.DateTimeStyles.RoundtripKind);
|
||||
TimeSpan cand_ts_span_file = cand_ts_event_dt - _last_fire_time.last_fireitme_file;
|
||||
TimeSpan ts_clock = DateTime.Now - _last_fire_time.last_firetime_clock;
|
||||
if (ts_clock >= cand_ts_span_file) {
|
||||
_rows.pointer++;
|
||||
_last_fire_time.last_firetime_clock = DateTime.Now;
|
||||
_last_fire_time.last_fireitme_file = cand_ts_event_dt;
|
||||
BlueTable bt_out = new BlueTable(cand_row.schema);
|
||||
bt_out.addRow(_with_ts_event(cand_row, _format_iso_8601_utc(DateTime.UtcNow)));
|
||||
var dp_out = BlueDataUtility.build_dp(bt_out, myLastValue as IDataPacket);
|
||||
myFireEvent(dp_out);
|
||||
}
|
||||
}
|
||||
|
||||
void _fire_baseset() {
|
||||
var rows = ExceptionAssert.NotNull(_rows.rows);
|
||||
int base_count = Math.Min(_baseset_size, rows.Count);
|
||||
if (base_count == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
BlueTable bt_out = new BlueTable(rows[0].schema);
|
||||
string last_ts_event = rows[base_count - 1].get<string>("ts_event");
|
||||
DateTime last_file_ts = DateTime.Parse(last_ts_event, null, System.Globalization.DateTimeStyles.RoundtripKind).ToUniversalTime();
|
||||
DateTime base_end_ts = DateTime.UtcNow;
|
||||
TimeSpan rebase_offset = base_end_ts - last_file_ts;
|
||||
|
||||
for (int i = 0; i < base_count; i++) {
|
||||
string row_ts_event = rows[i].get<string>("ts_event");
|
||||
DateTime row_file_ts = DateTime.Parse(row_ts_event, null, System.Globalization.DateTimeStyles.RoundtripKind).ToUniversalTime();
|
||||
bt_out.addRow(_with_ts_event(rows[i], _format_iso_8601_utc(row_file_ts + rebase_offset)));
|
||||
}
|
||||
|
||||
_rows.pointer = base_count;
|
||||
|
||||
_last_fire_time.last_fireitme_file = last_file_ts;
|
||||
_last_fire_time.last_firetime_clock = DateTime.Now;
|
||||
|
||||
var dp_out = BlueDataUtility.build_dp(bt_out, myLastValue as IDataPacket);
|
||||
myFireEvent(dp_out);
|
||||
}
|
||||
|
||||
static IBlueRow _with_ts_event(IBlueRow row, string ts_event) {
|
||||
var out_row = new MutableBlueRow(row.schema);
|
||||
foreach (ColumnInfo ci in row.schema.columnInfo) {
|
||||
out_row.setValue(ci.colName, ci.colName == "ts_event" ? ts_event : row[ci.colNo]);
|
||||
}
|
||||
return out_row;
|
||||
}
|
||||
|
||||
static string _format_iso_8601_utc(DateTime utc_ts) {
|
||||
utc_ts = utc_ts.ToUniversalTime();
|
||||
long nanoseconds = utc_ts.Ticks % TimeSpan.TicksPerSecond * 100;
|
||||
string formatted = utc_ts.ToString("yyyy-MM-ddTHH:mm:ss");
|
||||
formatted += $".{nanoseconds:D9}Z";
|
||||
return formatted;
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
-2
@@ -228,7 +228,7 @@ namespace BlueOrb.Operators.Signal {
|
||||
string schema_info_json)
|
||||
:
|
||||
this(price_stream,
|
||||
Enum.Parse<BarType>(bar_type),
|
||||
_parse_bar_type(bar_type),
|
||||
bar_size,
|
||||
true,
|
||||
_parse_and_validate_schema_info_json(schema_info_json)) {
|
||||
@@ -242,7 +242,7 @@ namespace BlueOrb.Operators.Signal {
|
||||
string timestamp_col)
|
||||
:
|
||||
this(price_stream,
|
||||
Enum.Parse<BarType>(bar_type),
|
||||
_parse_bar_type(bar_type),
|
||||
bar_size,
|
||||
true,
|
||||
_create_and_validate_schema_info(price_col, volume_col, timestamp_col)) {
|
||||
@@ -272,6 +272,39 @@ namespace BlueOrb.Operators.Signal {
|
||||
}
|
||||
|
||||
|
||||
static BarType _parse_bar_type(string bar_type) {
|
||||
if (string.IsNullOrWhiteSpace(bar_type)) {
|
||||
throw new ArgumentException("bar_type cannot be null or empty.", nameof(bar_type));
|
||||
}
|
||||
|
||||
var normalized = bar_type.Trim();
|
||||
if (Enum.TryParse<BarType>(normalized, ignoreCase: true, out var exact_match)) {
|
||||
return exact_match;
|
||||
}
|
||||
|
||||
BarType? substring_match = null;
|
||||
foreach (var candidate in Enum.GetValues<BarType>()) {
|
||||
var candidate_name = candidate.ToString();
|
||||
bool is_match =
|
||||
candidate_name.Contains(normalized, StringComparison.OrdinalIgnoreCase) ||
|
||||
normalized.Contains(candidate_name, StringComparison.OrdinalIgnoreCase);
|
||||
if (!is_match) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (substring_match is not null) {
|
||||
throw new ArgumentException($"bar_type '{bar_type}' is ambiguous.", nameof(bar_type));
|
||||
}
|
||||
substring_match = candidate;
|
||||
}
|
||||
|
||||
if (substring_match is not null) {
|
||||
return substring_match.Value;
|
||||
}
|
||||
|
||||
throw new ArgumentException($"Unknown bar_type '{bar_type}'.", nameof(bar_type));
|
||||
}
|
||||
|
||||
static BarBuilderSchemaInfo _parse_and_validate_schema_info_json(string schema_info_json) {
|
||||
if (string.IsNullOrWhiteSpace(schema_info_json)) {
|
||||
throw new ArgumentException("schema_info_json cannot be null or empty.", nameof(schema_info_json));
|
||||
|
||||
@@ -24,6 +24,7 @@ namespace BCG {
|
||||
private readonly ITag<OptionTheoInterpolationData> _in_bb_precomputed_sparse_theos_tag;
|
||||
private readonly ITag<IDictionary<NMSheetExpiration, double>> _in_bb_vol_shift_tag;
|
||||
private readonly ITag<NMSheetSettings> _in_bb_sheet_settings_tag;
|
||||
private readonly ITag<IEnumerable<ITradeLogRow>> _in_bb_trade_log_tag = SparkTags.TradeLogTag;
|
||||
private readonly ITag<VolSurfaceNonVolInput> _in_exp_param_tag = SparkTags.VolSurfaceNonVolInputTag;
|
||||
private readonly ITag<bool> _in_bb_main_sheet_visibility_tag;
|
||||
private ITag<SparkTags.Nothing> _in_bb_onefive_value_tag = SparkTags.TC2Tags.VoidTag,
|
||||
@@ -31,7 +32,6 @@ namespace BCG {
|
||||
_in_bb_symbol_theo_shift_tag = SparkTags.TC2Tags.VoidTag,
|
||||
_in_bb_rollover_data_tag = SparkTags.TC2Tags.VoidTag,
|
||||
_in_bb_presaved_aw2_theos_tag = SparkTags.TC2Tags.VoidTag,
|
||||
_in_bb_position_tag = SparkTags.TC2Tags.VoidTag,
|
||||
_in_bb_option_driver_detailed_price_tag = SparkTags.TC2Tags.VoidTag;
|
||||
private readonly NMSheetSymbol _nmsheet_symbol;
|
||||
private Action<Pair<NMSheetSymbol, NMSheetSingleOptionData>> _cb;
|
||||
@@ -76,7 +76,7 @@ namespace BCG {
|
||||
_threaded_bb.subscribe(_in_bb_rollover_data_tag);
|
||||
_threaded_bb.subscribe(_in_bb_presaved_aw2_theos_tag);
|
||||
_threaded_bb.subscribe(_in_exp_param_tag);
|
||||
_threaded_bb.subscribe(_in_bb_position_tag);
|
||||
_threaded_bb.subscribe(_in_bb_trade_log_tag);
|
||||
_threaded_bb.subscribe(_in_bb_sheet_settings_tag);
|
||||
_threaded_bb.subscribe(_in_bb_onefive_value_tag);
|
||||
_threaded_bb.subscribe(_in_bb_qs_tag);
|
||||
@@ -87,7 +87,7 @@ namespace BCG {
|
||||
private void _react_to_bb(object tag, object value) {
|
||||
if (_in_bb_main_sheet_request_tag.Equals(tag) || _in_bb_secmap_tag.Equals(tag) || _in_bb_live_theos_tag.Equals(tag) || /*_in_bb_live_driver_bbo_tag.Equals(tag) ||*/ _in_bb_precomputed_sparse_theos_tag.Equals(tag) ||
|
||||
_in_bb_vol_shift_tag.Equals(tag) || _in_bb_symbol_theo_shift_tag.Equals(tag) || _in_exp_param_tag.Equals(tag) || _in_bb_presaved_aw2_theos_tag.Equals(tag) ||
|
||||
_in_bb_position_tag.Equals(tag) || _in_bb_rollover_data_tag.Equals(tag) || _in_bb_sheet_settings_tag.Equals(tag) || _in_bb_qs_tag.Equals(tag) ||
|
||||
_in_bb_trade_log_tag.Equals(tag) || _in_bb_rollover_data_tag.Equals(tag) || _in_bb_sheet_settings_tag.Equals(tag) || _in_bb_qs_tag.Equals(tag) ||
|
||||
_in_bb_main_sheet_visibility_tag.Equals(tag))
|
||||
_compute_and_fire();
|
||||
}
|
||||
@@ -255,7 +255,28 @@ namespace BCG {
|
||||
}
|
||||
|
||||
private ExpStrikeKeyedData<Tuple<double, double>> _get_position_map() {
|
||||
return new ExpStrikeKeyedData<Tuple<double, double>>();
|
||||
var sheet_settings = _threaded_bb.read_state(_in_bb_sheet_settings_tag);
|
||||
var risk_account_text = sheet_settings?.setting_layout?.risk_account ?? string.Empty;
|
||||
var risk_accounts = risk_account_text
|
||||
.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
|
||||
.Select(a => a.Trim())
|
||||
.Where(a => !string.IsNullOrEmpty(a))
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var trades = _threaded_bb.read_state(_in_bb_trade_log_tag) ?? Enumerable.Empty<ITradeLogRow>();
|
||||
var option_trades = trades.Where(t =>
|
||||
t.is_active &&
|
||||
t.security_type == SecurityType.Option &&
|
||||
t.symbol == _nmsheet_symbol.option_name &&
|
||||
t.venue == _nmsheet_symbol.option_exchange &&
|
||||
(risk_accounts.Count == 0 || risk_accounts.Contains(t.account)));
|
||||
var pos_data = SecurityPositionData.from_trades(option_trades);
|
||||
var rv = new ExpStrikeKeyedData<Tuple<double, double>>();
|
||||
foreach (var (sec_exp, strike_map) in pos_data.option_pos_map) {
|
||||
foreach (var (strike, strike_pos) in strike_map) {
|
||||
rv.set_data(sec_exp.expiration, strike, Tuple.Create(strike_pos.call, strike_pos.put));
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
private double _get_onefive() {
|
||||
|
||||
Reference in new issue
Block a user