cleanup: Fix more build warnings in DataStreamSuite

Alot more
This commit is contained in:
John Colvin committed 2026-01-11 15:15:13 -05:00
1 parent 989d103eef
commit bcd207f89e
118 files changed
+1812 -1597

No files matched your search

@@ -1,103 +1,102 @@
using bts.SilverPine;
namespace bts.BlueOrb {
using bts;
//using bts.api;
//using bts.spark;
using System;
using ZstdSharp.Unsafe;
using System.Diagnostics.CodeAnalysis;
public static class ContractUtils {
public class FutureTradableContract {
public string symbol;
public DateTime expiration;
public Exchange exchange;
public string contract_text;
}
public record FutureTradableContract(
string Symbol,
DateTime Expiration,
Exchange Exchange,
string? ContractText);
public class FutureSpreadContract {
public List<Tuple<double, FutureTradableContract>> legs;
public string symbol {
public List<Tuple<double, FutureTradableContract>> legs = new(2);
public string Symbol {
get {
return legs == null || legs.Count == 0 ? string.Empty : legs.ElementAt(0).Item2.symbol;
return legs == null || legs.Count == 0 ? string.Empty : legs.ElementAt(0).Item2.Symbol;
}
}
public string contract_text;
}
public class FutureContinousContract {
public string symbol;
public Exchange exchange;
public string? ContractText;
}
public record FutureContinousContract(string Symbol, Exchange Exchange);
// this is for all future conytracts belonging to a symbol
public class FutureWildcardContract {
public string symbol;
public Exchange exchange;
}
public record FutureWildcardContract(string Symbol, Exchange Exchange);
public class FutureContract {
public FutureWildcardContract wildcard_contract = null;
public FutureTradableContract future_tradable_contract = null;
public FutureSpreadContract spread_tradable_contract = null;
public FutureContinousContract continous_constract = null;
public FutureWildcardContract? wildcard_contract;
public FutureTradableContract? future_tradable_contract;
public FutureSpreadContract? spread_tradable_contract;
public FutureContinousContract? continous_constract;
public FutureContract(string txt) {
wildcard_contract = parse_wildcard_contract(txt);
if (wildcard_contract != null)
return;
FutureTradableContract fc = parse_future_contract(txt);
var fc = parse_future_contract(txt);
if (fc != null) {
future_tradable_contract = fc;
return;
}
FutureSpreadContract sc = parse_future_spread_contract(txt);
var sc = parse_future_spread_contract(txt);
if (sc != null) {
spread_tradable_contract = sc;
return;
}
// this is not totally true, since ParseFutureSpreadContract does not
// parse ICS spreads
continous_constract = new FutureContinousContract() { symbol = txt };
continous_constract = new(txt, Exchange.CME);
}
[MemberNotNullWhen(true, nameof(continous_constract))]
public bool is_continous_contract => continous_constract != null;
[MemberNotNullWhen(true, nameof(wildcard_contract))]
public bool is_wildcard_contract => wildcard_contract != null;
[MemberNotNullWhen(true, nameof(future_tradable_contract))]
public bool is_future_tradable_contract => future_tradable_contract != null;
[MemberNotNullWhen(true, nameof(spread_tradable_contract))]
public bool is_spread_tradable_contract => spread_tradable_contract != null;
public string symbol() {
if (wildcard_contract != null)
return wildcard_contract.symbol;
return wildcard_contract.Symbol;
if (continous_constract != null) {
return continous_constract.symbol;
return continous_constract.Symbol;
} else if (future_tradable_contract != null) {
return future_tradable_contract.symbol;
return future_tradable_contract.Symbol;
} else if (spread_tradable_contract != null) {
return spread_tradable_contract.symbol;
return spread_tradable_contract.Symbol;
}
Log.assert(false);
return string.Empty;
}
public string contract_text {
public string? contract_text {
get {
if (future_tradable_contract != null)
return future_tradable_contract.contract_text;
return future_tradable_contract.ContractText;
if (spread_tradable_contract != null)
return spread_tradable_contract.contract_text;
return spread_tradable_contract.ContractText;
return null;
}
}
}
#region Parsing
public static FutureWildcardContract parse_wildcard_contract(string contract_txt, Exchange exchange = Exchange.CME) {
public static FutureWildcardContract? parse_wildcard_contract(string contract_txt, Exchange exchange = Exchange.CME) {
if (contract_txt.EndsWith("*")) {
contract_txt = contract_txt.Replace("*", string.Empty);
return new FutureWildcardContract() {
symbol = contract_txt,
exchange = exchange
};
return new FutureWildcardContract(contract_txt, exchange);
}
return null;
}
public static FutureTradableContract parse_future_contract(string contract_txt, Exchange exchange = Exchange.CME) {
public static FutureTradableContract? parse_future_contract(string contract_txt, Exchange exchange = Exchange.CME) {
// Validate the future string length
if (!contract_txt.All(c => char.IsLetterOrDigit(c)))
return null;
@@ -143,17 +142,10 @@ namespace bts.BlueOrb {
// Create the FutureContract instance and set its properties
DateTime expiration = new DateTime(year, month, 1);
var futureContract = new FutureTradableContract {
symbol = symbol,
expiration = expiration,
exchange = exchange,
contract_text = contract_txt
};
return futureContract;
return new(symbol, expiration, exchange, contract_txt);
}
// Method to parse a futures spread, e.g. "CLX4-CLZ4"
public static FutureSpreadContract parse_future_spread_contract(string contract_txt, Exchange exchange = Exchange.CME) {
public static FutureSpreadContract? parse_future_spread_contract(string contract_txt, Exchange exchange = Exchange.CME) {
// Split the string by '-' to handle each leg
var spreadParts = contract_txt.Split('-');
if (spreadParts.Length < 2) {
@@ -201,11 +193,11 @@ namespace bts.BlueOrb {
#endregion
public static ContractType get_type(string contract_txt) {
FutureTradableContract fc = parse_future_contract(contract_txt);
var fc = parse_future_contract(contract_txt);
if (fc != null) {
return ContractType.Future;
}
FutureSpreadContract sc = parse_future_spread_contract(contract_txt);
var sc = parse_future_spread_contract(contract_txt);
if (sc != null) {
return ContractType.FutureSpread;
}
@@ -220,13 +212,13 @@ namespace bts.BlueOrb {
}
public static Tuple<ContractCategory, string> get_symbol_category(string symbol) {
FutureTradableContract fc = parse_future_contract(symbol);
var fc = parse_future_contract(symbol);
if (fc != null) {
return Tuple.Create(ContractCategory.FutureString, fc.symbol);
return Tuple.Create(ContractCategory.FutureString, fc.Symbol);
}
var sc = parse_future_spread_contract(symbol);
if (sc != null) {
return Tuple.Create(ContractCategory.FutureString, sc.symbol);
return Tuple.Create(ContractCategory.FutureString, sc.Symbol);
}
return Tuple.Create(ContractCategory.Symbol, symbol);
}
@@ -2,6 +2,7 @@ namespace bts.BlueOrb {
using bts.SilverPine;
using BCG;
using Bts.DataStreamExpressions;
public class DateTimeRange {
public readonly DateTime range_beg;
@@ -18,7 +19,7 @@ namespace bts.BlueOrb {
}
public class FutureBarsLoader {
public static string get_db_table_name(BarSize bar_size, string symbol, bool is_continous) {
public static string? get_db_table_name(BarSize bar_size, string symbol, bool is_continous) {
switch (bar_size) {
case BarSize.ONE_DAY: {
if (is_continous) {
@@ -62,7 +63,8 @@ namespace bts.BlueOrb {
beg = beg.Date;
end = end.Date.Add(new TimeSpan(23, 59, 59));
// this returns rows from beg and end inclusive
Func<string, SQLiteStream> get_sqlite_str = (table_name) => {
Func<string?, SQLiteStream> get_sqlite_str = (table_name) => {
ArgumentException.ThrowIfNullOrEmpty(table_name);
string range_beg_iso8601 = beg.ToString("yyyy-MM-ddTHH:mm:ss"),
range_end_iso8601 = end.ToString("yyyy-MM-ddTHH:mm:ss");
string sql_str = $"select * from {table_name} where ts_event >= '{range_beg_iso8601}' AND ts_event <= '{range_end_iso8601}'";
@@ -70,27 +72,27 @@ namespace bts.BlueOrb {
};
string symbol = future_contract.symbol();
if (future_contract.wildcard_contract != null) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
var table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
//rs = new DateStandardizationStream(rs, "ts_event", DateConversion.ChopTime);
mySetRealSource(rs);
return;
}
if (future_contract.wildcard_contract != null) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
var table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
//rs = new DateStandardizationStream(rs, "ts_event", DateConversion.ChopTime);
mySetRealSource(rs);
return;
}
if (future_contract.is_continous_contract) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, symbol, true);
var table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, symbol, true);
ViewStream rs = get_sqlite_str(table_name);
//rs = new DateStandardizationStream(rs, "ts_event", DateConversion.ChopTime);
mySetRealSource(rs);
return;
} else {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
var table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
//rs = new DateStandardizationStream(rs, "ts_event", DateConversion.ChopTime);
//TODO: filter it
@@ -115,7 +117,8 @@ namespace bts.BlueOrb {
// it gets the raw table with all contracts for that symbol
public FuturesHistorical1MinuteBarsStream(ContractUtils.FutureContract future_contract,
DateTimeRange dt_range) {
Func<string, SQLiteStream> get_sqlite_str = (table_name) => {
Func<string?, SQLiteStream> get_sqlite_str = (table_name) => {
ArgumentException.ThrowIfNullOrEmpty(table_name);
string range_beg_iso8601 = dt_range.range_beg.ToString("yyyy-MM-ddTHH:mm:ss"),
range_end_iso8601 = dt_range.range_end.ToString("yyyy-MM-ddTHH:mm:ss");
//string sql_str = $"select * from {table_name} where DATE(ts_event) >= '{range_beg_iso8601}' AND DATE(ts_event) <= '{range_end_iso8601}'";
@@ -124,18 +127,18 @@ namespace bts.BlueOrb {
};
string symbol = future_contract.symbol();
if (future_contract.wildcard_contract != null) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, future_contract.symbol(), false);
var table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
mySetRealSource(rs);
return;
}
if (future_contract.is_continous_contract) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, symbol, true);
var table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, symbol, true);
ViewStream rs = get_sqlite_str(table_name);
mySetRealSource(rs);
return;
} else {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, future_contract.symbol(), false);
var table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
// TODO: filter
rs = new FilterStream(rs, $"symbol = '{future_contract.contract_text}'");
@@ -1,6 +1,4 @@
namespace bts.BlueOrb {
using System;
using BCG;
using bts.api;
@@ -24,23 +22,23 @@
// wild card
if (fc.is_wildcard_contract) {
var wc_contr = fc.wildcard_contract;
ViewStream rs = new bts.BlueOrb.FilterStream(parent_str, $"symbol='{wc_contr.symbol}'");
ViewStream rs = new FilterStream(parent_str, $"symbol='{wc_contr.Symbol}'");
rs = new bts.BlueOrb.FilterStream(parent_str, $"sec_type='{SecurityType.Future}' or sec_type = '{SecurityType.Spread}'");
mySetRealSource(rs);
return;
} else if (fc.is_future_tradable_contract) {
var fut_contr = fc.future_tradable_contract;
ViewStream rs = new bts.BlueOrb.FilterStream(parent_str, $"sec='{fut_contr.contract_text}'");
ViewStream rs = new FilterStream(parent_str, $"sec='{fut_contr.ContractText}'");
mySetRealSource(rs);
return;
} else if (fc.is_spread_tradable_contract) {
var spr_contr = fc.future_tradable_contract;
ViewStream rs = new bts.BlueOrb.FilterStream(parent_str, $"sec='{spr_contr.contract_text}'");
ViewStream rs = new FilterStream(parent_str, $"sec='{spr_contr.ContractText}'");
mySetRealSource(rs);
return;
} else if (fc.is_continous_contract) {
var cont_contr = fc.continous_constract;
ViewStream rs = new bts.BlueOrb.FilterStream(parent_str, $"symbol='{cont_contr.symbol}' and sec_type='{SecurityType.Future}'");
ViewStream rs = new FilterStream(parent_str, $"symbol='{cont_contr.Symbol}' and sec_type='{SecurityType.Future}'");
rs = new bts.BlueOrb.GroupByStream(rs, () => { return new string[] { "symbol" }; },
(group_rows) => {
IBlueRow r = group_rows.ToList().OrderBy(r => r.get_datetime("expiration")).ElementAt(0);
@@ -1,6 +1,4 @@
namespace bts.BlueOrb {
using System;
using BCG;
using bts.api;
@@ -10,7 +8,7 @@
public LiveTradeStream(string target)
: this(SecurityType.Future, target) { }
public LiveTradeStream(SecurityType sec_type, string target) {
ViewStream rs = null;
ViewStream? rs = null;
switch (sec_type) {
case SecurityType.Future:
rs = new LiveFuturesTradeStream(target);
@@ -1,11 +1,11 @@
namespace bts.BlueOrb {
using BCG;
using Spark.Core.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BCG;
[DataStreamUserRespresentation("ReplayFutureLiveBBOStream")]
public class ReplayFutureLiveBBOStream : ViewStream, BCG.Utilities.General.IWorker{
@@ -14,13 +14,13 @@
public DateTime last_firetime_clock = DateTime.MinValue;
}
private class RowsWithPointer {
public List<IBlueRow> rows;
public List<IBlueRow>? rows;
public int pointer;
}
private readonly ViewStreamDatabase _vsd;
private readonly ContractUtils.FutureContinousContract _fcc;
readonly ViewStreamDatabase? _vsd;
readonly ContractUtils.FutureContinousContract? _fcc;
private readonly LastFireTime _last_fire_time = new LastFireTime();
private RowsWithPointer _rows = new RowsWithPointer();
@@ -62,20 +62,22 @@
}
protected override void myOnFirstSubscriber() {
var file_path = Path.Combine(SQLiteHelper.location, $"mbp1_{_fcc.symbol}_small.csv".ToLower());
Log.notnull(_fcc);
var file_path = Path.Combine(SQLiteHelper.location, $"mbp1_{_fcc.Symbol}_small.csv".ToLower());
var rows = BCG.CSVReaderStream.LoadFile(file_path);
_rows.rows = new(rows.Count);
_rows.rows.AddRange(rows.OfType<IBlueRow>().OrderBy(r => r.get<string>("ts_event")));
_rows.pointer = 0;
_vsd.addWorker(this);
ExceptionAssert.NotNull(_vsd).addWorker(this);
}
protected override void myOnLastSubscriber() {
_vsd.removeWorker(this);
ExceptionAssert.NotNull(_vsd).removeWorker(this);
}
public void doWork() {
IBlueRow cand_row = _rows.rows[_rows.pointer];
var rows = ExceptionAssert.NotNull(_rows.rows);
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;
@@ -1,11 +1,11 @@
namespace bts.BlueOrb {
using BCG;
using Spark.Core.Diagnostics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BCG;
[DataStreamUserRespresentation("ReplayFutureLiveTradeStream")]
public class ReplayFutureLiveTradeStream : ViewStream, BCG.Utilities.General.IWorker {
@@ -14,15 +14,15 @@
public DateTime last_firetime_clock = DateTime.MinValue;
}
private class RowsWithPointer {
public List<IBlueRow> rows;
public List<IBlueRow>? rows;
public int pointer;
}
private readonly ViewStreamDatabase _vsd;
private readonly ContractUtils.FutureContinousContract _fcc;
readonly ViewStreamDatabase? _vsd;
readonly ContractUtils.FutureContinousContract? _fcc;
private readonly LastFireTime _last_fire_time = new LastFireTime();
private RowsWithPointer _rows = new RowsWithPointer();
readonly RowsWithPointer _rows = new();
public ReplayFutureLiveTradeStream(string continous_contract) {
Func<string> iso_8601_now = () => {
@@ -61,21 +61,24 @@
}
protected override void myOnFirstSubscriber() {
var file_path = Path.Combine(SQLiteHelper.location, $"trades_{_fcc.symbol}.csv");
Log.notnull(_vsd);
Log.notnull(_fcc);
var file_path = Path.Combine(SQLiteHelper.location, $"trades_{_fcc.Symbol}.csv");
var csv_rd = new CSVReaderStream(file_path, false);
var rows = BCG.CSVReaderStream.LoadFile(file_path);
_rows.rows = new(rows.Count);
_rows.rows.AddRange(rows.OfType<IBlueRow>().OrderBy(r => r.get<string>("ts_event")));
_rows.pointer = 0;
_vsd.addWorker(this);
ExceptionAssert.NotNull(_vsd).addWorker(this);
}
protected override void myOnLastSubscriber() {
_vsd.removeWorker(this);
ExceptionAssert.NotNull(_vsd).removeWorker(this);
}
public void doWork() {
IBlueRow cand_row = _rows.rows[_rows.pointer];
var rows = ExceptionAssert.NotNull(_rows.rows);
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;
@@ -8,7 +8,7 @@ namespace bts {
using System.Text.Json.Nodes;
[DataStreamUserRespresentation("benzingaNews")]
public class BenzingaNewsStream : ViewStream {
private IBlueTableSchema _schema = null;
IBlueTableSchema? _schema;
private int _id = 0;
@@ -63,14 +63,14 @@ namespace bts {
}
foreach (JsonNode jnode in json_objs) {
if (jnode is JsonObject json_object) {
string symbol = jnode["symbol"] == null ? String.Empty : jnode["symbol"].ToString();
string exchange = jnode["exchange"] == null ? String.Empty : jnode["exchange"].ToString();
string symbol = jnode["symbol"]?.ToString() ?? string.Empty;
string exchange = jnode["exchange"]?.ToString() ?? string.Empty;
MutableBlueRow nr = new MutableBlueRow(_schema, r);
nr.setValue("id", _id++);
nr.setValue("doc_id_internal", $"{r["doc_id"]}_{jnode["symbol"]}");
nr.setValue("doc_id_internal", $"{r["doc_id"]}_{symbol}");
nr.setValue("symbol", symbol);
nr.setValue("exchange", exchange);
nr.setValue("is_primary_exchange", Boolean.Parse(jnode["primary"].ToString()));
nr.setValue("is_primary_exchange", jnode["primary"]?.GetValue<bool>() ?? false);
expanded_rows.Add(nr);
}
}
@@ -84,4 +84,4 @@ namespace bts {
mySetRealSource(output_stream);
}
}
}
}
@@ -15,8 +15,8 @@ namespace bts {
this(new BenzingaNewsStream(connection_string, db_name, collection_name, poll_period, ttl)) {
}
public IBlueRowCollection evaluate(IDictionary<int, List<IBlueRow>> grouped_rows) {
BlueTable rv = null;
public IBlueRowCollection? evaluate(IDictionary<int, List<IBlueRow>> grouped_rows) {
BlueTable? rv = null;
foreach (var kv in grouped_rows) {
var symbol_rows = kv.Value;
IBlueRow state_row = BlueDataUtility.find_max(symbol_rows, "created_at");
@@ -30,4 +30,4 @@ namespace bts {
return new string[] { "symbol" };
}
}
}
}
@@ -14,7 +14,7 @@
public class SpatialArbStatsStream : ViewStream{
private ViewStream _spatial_pairs_stream;
private ViewStreamDatabase _vsd;
private ViewStream _tot_str = null;
ViewStream? _tot_str = null;
private HashSet<string> _key_map = new HashSet<string>();
private ViewStream _bbo_stream;
private readonly TimeSpan _window_sz, _sampling_period_sz;
@@ -1,30 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
using MathNet.Numerics.LinearRegression;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
using MathNet.Numerics.LinearAlgebra;
using Amazon.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
// stats calculator
using System;
using System.Collections.Generic;
using System.Linq;
using MathNet.Numerics.Statistics;
using Spark.Core.Diagnostics;
/// <summary>
/// Provides evaluation metrics to assess the quality of a synthetic spread for mean-reversion trading.
@@ -35,13 +13,13 @@ public static class SpreadPerformanceEvaluator
public static class SpreadStatistics {
public class SpreadStatsResult {
public Dictionary<string, double> bid_zscore_distribution { get; set; }
public Dictionary<string, double> ask_zscore_distribution { get; set; }
public Dictionary<string, double> mid_zscore_distribution { get; set; }
public Dictionary<string, double>? bid_zscore_distribution { get; set; }
public Dictionary<string, double>? ask_zscore_distribution { get; set; }
public Dictionary<string, double>? mid_zscore_distribution { get; set; }
public DescriptiveStatistics bid_stats { get; set; }
public DescriptiveStatistics ask_stats { get; set; }
public DescriptiveStatistics mid_stats { get; set; }
public DescriptiveStatistics? bid_stats { get; set; }
public DescriptiveStatistics? ask_stats { get; set; }
public DescriptiveStatistics? mid_stats { get; set; }
}
private static readonly string[] _zscore_labels = new[]
@@ -105,9 +83,10 @@ public static class SpreadPerformanceEvaluator
}
public static double score_spread(SpreadStatsResult result) {
var ask_bins = result.ask_zscore_distribution;
var bid_bins = result.bid_zscore_distribution;
var mid_bins = result.mid_zscore_distribution;
var ask_bins = ExceptionAssert.NotNull(result.ask_zscore_distribution);
var bid_bins = ExceptionAssert.NotNull(result.bid_zscore_distribution);
var mid_bins = ExceptionAssert.NotNull(result.mid_zscore_distribution);
var mid_stats = ExceptionAssert.NotNull(result.mid_stats);
double buy_opportunity = ask_bins["Z < -2σ"] + ask_bins["-2σ ≤ Z < -1σ"];
double sell_opportunity = bid_bins["Z ≥ 2σ"] + bid_bins["1σ ≤ Z < 2σ"];
@@ -117,7 +96,7 @@ public static class SpreadPerformanceEvaluator
double above_mean = mid_bins["Z ≥ 2σ"] + mid_bins["1σ ≤ Z < 2σ"] + mid_bins["0σ ≤ Z < 1σ"];
double symmetry_score = 1.0 - Math.Abs(below_mean - above_mean) / (below_mean + above_mean + 1e-6);
double amplitude_score = result.mid_stats.StandardDeviation;
double amplitude_score = mid_stats.StandardDeviation;
double skew_penalty = 1.0 / (1.0 + Math.Abs(result.mid_stats.Skewness));
double kurtosis_bonus = Math.Min(result.mid_stats.Kurtosis, 6.0) / 6.0;
@@ -1,7 +1,10 @@
namespace bts.BlueOrb {
using BCG;
using Bts.DataStreamCore;
using Spark.Api.MarketData;
using Spark.Core.Diagnostics;
using System.Diagnostics;
@@ -9,11 +12,13 @@ namespace bts.BlueOrb {
// IMarketDataClient. Until then, hide it from DSQA.
[DataStreamUserRespresentation(false)]
public class SpreadPerformanceStream : ViewStream {
ViewStream _spread_price_stream = null;
ViewStream? _spread_price_stream;
private readonly IBlueTableSchema _schema;
private readonly int _window_secs;
private readonly double _buy_threshold, _sell_threshold, _flat_threshold;
private ViewStream _bbo_stream;
IDisposable? subscription;
public SpreadPerformanceStream(
string s1,
string s2,
@@ -84,11 +89,13 @@ namespace bts.BlueOrb {
}
protected override void myOnFirstSubscriber() {
_spread_price_stream.onChange += _handle_spread_prices;
ExceptionAssert.IsNull(subscription);
subscription = ExceptionAssert.NotNull(_spread_price_stream).Subscribe(_handle_spread_prices);
}
protected override void myOnLastSubscriber() {
_spread_price_stream.onChange -= _handle_spread_prices;
subscription?.Dispose();
subscription = null;
}
private void _handle_spread_prices(object dp_obj) {
@@ -2,6 +2,7 @@
using BCG;
using Spark.Api.MarketData;
using Spark.Core.Diagnostics;
using System;
using System.Collections.Generic;
@@ -100,36 +101,40 @@
var result = SpreadPerformanceEvaluator.SpreadStatistics.analyze_spread_quotes(spread_prices);
(uint n_buy_signals, double cumm_buy_price, uint n_sell_signals, double cumm_sell_price) =
SpreadPerformanceEvaluator.EvaluateExcursionCount(spread_prices.Select(t => Tuple.Create(t.Item2, t.Item3, t.Item4, t.Item5)).ToList(), 2.0);
var bidStats = ExceptionAssert.NotNull(result.bid_stats);
var askStats = ExceptionAssert.NotNull(result.ask_stats);
var bidZscoreDist = ExceptionAssert.NotNull(result.bid_zscore_distribution);
var askZscoreDist = ExceptionAssert.NotNull(result.ask_zscore_distribution);
IBlueRow nr = new BlueRow(_schema,
0,
_spread,
$"n_ticks: {spread_prices.Count} t0: {t0.ToLongTimeString()} -> t1: {t1.ToLongTimeString()} ({tot_secs}) secs",
result.bid_stats.Mean,
result.ask_stats.Mean,
result.bid_stats.StandardDeviation,
result.ask_stats.StandardDeviation,
result.bid_stats.Skewness,
result.ask_stats.Skewness,
result.bid_stats.Kurtosis,
result.ask_stats.Kurtosis,
result.bid_stats.Maximum,
result.ask_stats.Maximum,
result.bid_stats.Minimum,
result.ask_stats.Minimum,
bidStats.Mean,
askStats.Mean,
bidStats.StandardDeviation,
askStats.StandardDeviation,
bidStats.Skewness,
askStats.Skewness,
bidStats.Kurtosis,
askStats.Kurtosis,
bidStats.Maximum,
askStats.Maximum,
bidStats.Minimum,
askStats.Minimum,
// bid distribution
result.bid_zscore_distribution["Z < -2σ"],
result.bid_zscore_distribution["-2σ ≤ Z < -1σ"],
result.bid_zscore_distribution["-1σ ≤ Z < 0σ"],
result.bid_zscore_distribution["0σ ≤ Z < 1σ"],
result.bid_zscore_distribution["1σ ≤ Z < 2σ"],
result.bid_zscore_distribution["Z ≥ 2σ"],
bidZscoreDist["Z < -2σ"],
bidZscoreDist["-2σ ≤ Z < -1σ"],
bidZscoreDist["-1σ ≤ Z < 0σ"],
bidZscoreDist["0σ ≤ Z < 1σ"],
bidZscoreDist["1σ ≤ Z < 2σ"],
bidZscoreDist["Z ≥ 2σ"],
// ask distributions
result.ask_zscore_distribution["Z < -2σ"],
result.ask_zscore_distribution["-2σ ≤ Z < -1σ"],
result.ask_zscore_distribution["-1σ ≤ Z < 0σ"],
result.ask_zscore_distribution["0σ ≤ Z < 1σ"],
result.ask_zscore_distribution["1σ ≤ Z < 2σ"],
result.ask_zscore_distribution["Z ≥ 2σ"],
askZscoreDist["Z < -2σ"],
askZscoreDist["-2σ ≤ Z < -1σ"],
askZscoreDist["-1σ ≤ Z < 0σ"],
askZscoreDist["0σ ≤ Z < 1σ"],
askZscoreDist["1σ ≤ Z < 2σ"],
askZscoreDist["Z ≥ 2σ"],
n_buy_signals,
cumm_buy_price,
n_sell_signals,
@@ -1,15 +1,15 @@
namespace bts.BlueOrb {
using BCG;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
[DataStreamUserRespresentation("Events")]
public class EventsStream : ViewStream {
public EventsStream(string event_type) : this(ViewStreamDatabase.instance, event_type) { }
public EventsStream(ViewStreamDatabase vsd, string event_type) {
string path = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "C:\\BlueOrb_Data\\":Path.Combine(Environment.GetEnvironmentVariable("HOME") , "BlueOrb_Data");
public EventsStream(string event_type) {
string path = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "C:\\BlueOrb_Data\\"
: Path.Combine(Environment.GetEnvironmentVariable("HOME") ?? string.Empty , "BlueOrb_Data");
string query = "Data Source="+ Path.Combine(path,"stream_data.db")+";Version=3; select * from events";
bts.Log.Gen.info($"EventsStream path: {path}, query: {query}");
ViewStream rs =
@@ -24,9 +24,9 @@ namespace bts.BlueOrb{
mySetRealSource(new NonIncGroupByStream(rs, this));
}
public IBlueRowCollection evaluate(IDictionary<int, List<IBlueRow>> grouped_rows) {
public IBlueRowCollection? evaluate(IDictionary<int, List<IBlueRow>> grouped_rows) {
Func<string, bool> is_future = (c) => ContractUtils.get_category(c) == ContractUtils.ContractCategory.FutureString;
BlueTable rv = null;
BlueTable? rv = null;
Func<List<IBlueRow>, IBlueRow> reduce = (rows) => {
var future_rows = rows.Where(r => is_future(r.get<string>("contract")));
IBlueRow rv = future_rows.ElementAt(0);
@@ -41,7 +41,7 @@ namespace bts.BlueOrb{
if (rows == null || rows.Count == 0)
continue;
IBlueRow rr = reduce(rows);
rv = rv ?? new BlueTable(rr.schema);
rv ??= new BlueTable(rr.schema);
rv.addRow(rr);
}
return rv;
@@ -23,8 +23,7 @@ namespace bts.BlueOrb {
private readonly TimeSpan _poll_period = TimeSpan.FromMilliseconds(500);
private DateTime _last_poll_time = DateTime.MinValue;
readonly IWorkScheduler workScheduler;
private int _id = 0;
IReadOnlyDictionary<uint, SecurityImmutable> _cached_state = null;
IReadOnlyDictionary<uint, SecurityImmutable>? _cached_state;
IMarketDataClient _md_client;
IDisposable? subscription;
private bool _dirty = false;
@@ -87,7 +86,7 @@ namespace bts.BlueOrb {
bts.api.SecurityType sec_type = sec.security_type();
object exp = DBNull.Value;
if (sec_type == bts.api.SecurityType.Future || sec_type == bts.api.SecurityType.Option)
exp = sec.security_expiration();
exp = sec.security_expiration() ?? throw new InvalidOperationException($"Security has invalid expiration (id={skey})");
object strike = DBNull.Value;
if (sec_type == bts.api.SecurityType.Option)
strike = sec.strike();
@@ -97,7 +96,7 @@ namespace bts.BlueOrb {
IBlueRow r = new BlueRow(_instrument_schema, id, skey, sec.security_desc(), sec.security_type().ToString(), sec.display_exchange().ToString(), sec.Symbol, sec.Currency, sec.ContractSpec.CashPerPoint, exp, strike, cp);
new_state.addRow(r);
}
DataPacket dp = null;
DataPacket? dp;
if (myLastValue == null) {
dp = new DataPacket(new_state, new_state, new BlueTable(_instrument_schema));
} else {
@@ -167,10 +167,10 @@ namespace bts.BlueOrb {
return String.Empty;
}
private Source _sourse = Source.SQL; // get from config
readonly string _location = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? "C:\\BlueOrb_Data\\"
: Path.Combine(Environment.GetEnvironmentVariable("HOME") ?? string.Empty, "BlueOrb_Data");
// private Source _sourse = Source.SQL; // get from config
// readonly string _location = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
// ? "C:\\BlueOrb_Data\\"
// : Path.Combine(Environment.GetEnvironmentVariable("HOME") ?? string.Empty, "BlueOrb_Data");
private readonly string _db_name = "stream_data.db";
// the symbol is used ot retreive the correct table, the data flows as-is from the table
// with some name / type changes
@@ -20,11 +20,9 @@ namespace BCG {
private readonly TimeSpan _poll_period = TimeSpan.FromMilliseconds(500);
private DateTime _last_poll_time = DateTime.MinValue;
private ViewStreamDatabase _vsd;
private int _id = 0;
IReadOnlyDictionary<SecurityKey, PriceStats> _cached_state = null;
IReadOnlyDictionary<SecurityKey, PriceStats>? _cached_state = null;
IMarketDataClient _md_client;
private bool _dirty = false;
private IDisposable _sub = null;
private readonly IBlueTableSchema _pstats_scheam = BlueDataUtility.form_schema("bbo",
Tuple.Create("id", TypeCode.Int32),
Tuple.Create("sec_key", TypeCode.UInt32),
@@ -48,7 +46,7 @@ namespace BCG {
}
private void _log_updates(TableUpdate<PriceStats, uint> update) {
int i = 0;
// int i = 0;
// foreach (BookTuple bt in update.added) {
// bts.Log.Gen.info($"PriceStatsStream added: idx: {i++} bid: {bt.book.bids[0].price} / {bt.book.bids[0].size} ask: {bt.book.asks[0].price} / {bt.book.asks[0].size}");
// }
@@ -68,7 +66,7 @@ namespace BCG {
protected override void myOnLastSubscriber() {
_vsd.removeWorker(this);
Disposable.dispose(ref _sub);
Disposable.Dispose(ref subscription);
}
private void _scan() {
@@ -85,7 +83,7 @@ namespace BCG {
IBlueRow r = new BlueRow(_pstats_scheam, id, skey, pstats.security.ToString(), today, pstats.open, pstats.close, pstats.settlement);
new_state.addRow(r);
}
DataPacket dp = null;
DataPacket dp;
if (myLastValue == null) {
dp = new DataPacket(new_state, new_state, new BlueTable(_pstats_scheam));
} else {
@@ -4,6 +4,8 @@ using BCG.Utilities.General;
using Bts.PubSub;
using Bts.SharedStreams.Tables;
using Spark.Core.Diagnostics;
namespace bts {
/// <summary>
/// Gets the subscription and publication state for one
@@ -46,12 +48,11 @@ namespace bts {
var updates = _sub_core.get_updates(TimeSpan.Zero);
//this is where the pubsub updates are converted to rows
if (updates.Count() > 0) {
int id = 0;
foreach (var u in updates) {
if (u.tag != _tag) {
continue;
}
var tpsi_list = TagPubSubInfo.deserialize(u.data);
var tpsi_list = TagPubSubInfo.deserialize(ExceptionAssert.NotNull(u.data));
foreach (var tsi in tpsi_list) {
_tag_map[tsi.tag] = tsi;
}
@@ -11,7 +11,7 @@ namespace bts
private class TableState
{
public ViewStream table_stream;
public IBlueTableSchema schema = null;
public IBlueTableSchema? schema = null;
public bool processed = false;
public TableState(ViewStream table_stream_)
{
@@ -100,8 +100,7 @@ namespace bts
{
Log.assert(tag_name.StartsWith("DS_"));
string table_name = tag_name.Remove(0, 3);
TableState ts = null;
if (!_table_map.TryGetValue(table_name, out ts))
if (!_table_map.TryGetValue(table_name, out var ts))
{
ts = new TableState(new TableStream(table_name, _vsd));
_table_map.Add(table_name, ts);