From 6b28fc47798a5a542262b0775471a606c00cdb1a Mon Sep 17 00:00:00 2001 From: Taha Date: Sun, 10 Aug 2025 15:13:16 -0400 Subject: [PATCH] Lot of BlueOrb stream changes --- .../DataStream/BlueOrb/CSVReaderStream.cs | 18 + .../DataStream/BlueOrb/CSVSaverStream.cs | 13 + .../DataStream/BlueOrb/GroupByStream.cs | 22 +- .../BlueOrb/Join/SimpleJoinStream.cs | 35 +- .../DataStream/BlueOrb/MultiRowOpHelper.cs | 8 + .../BlueOrb/PythonDataframeStream.cs | 3 +- .../DataStream/BlueOrb/TimeSeriesStream.cs | 22 +- .../DataStream/Misc/DSLStream.cs | 4 +- .../Primitives/Filter/TimeBasedFilter.cs | 9 +- .../Primitives/SQL/SQLite/SQLiteHelper.cs | 2 +- .../SideEffectStreams/CSVSaverStream.cs | 8 +- .../MarketData}/ContractUtils.cs | 19 +- .../Historical/HistoricalBarsStream.cs | 24 +- .../BlueOrb/MarketData/Live/LiveBBOStream.cs | 26 ++ .../MarketData/Live/LiveFuturesBBOStream.cs | 18 + .../MarketData/Live/LiveFuturesBookStream.cs | 16 + .../Live/LiveFuturesContractStream.cs | 51 +++ .../MarketData/Live/LiveFuturesTradeStream.cs | 13 + .../MarketData/Live/LiveTradeStream.cs | 25 ++ .../Live/ReplayFutureLiveBBOStream.cs | 93 +++++ .../Live/ReplayFutureLiveTradeStream.cs | 92 +++++ .../Business/MarketData/BBOStream.cs | 4 +- .../Business/MarketData/BookStream.cs | 5 +- .../MarketData/FuturesActiveContractStream.cs | 1 + .../Business/MarketData/InstrumentsStream.cs | 9 +- .../Business/MarketData/OHLCVStream.cs | 63 ++-- .../SharedStreams/NL/BlueOrbNLStream.cs | 38 ++ .../SharedStreams/NL/BlueOrbNLToDSLStream.cs | 28 ++ .../SharedStreams/NL/NLStream.cs | 64 ++-- .../SharedStreams/NL/NLToDSLStream.cs | 66 ++-- .../NL/NLToFewShotPromptStream.cs | 34 +- .../NL/NLToIndexedFewShotPromptStream.cs | 338 +++++++++--------- .../SharedStreams/NL/OpenAIPromptStream.cs | 218 ++++++----- 33 files changed, 946 insertions(+), 443 deletions(-) create mode 100644 src/DataStreamSuite/DataStream/BlueOrb/CSVReaderStream.cs create mode 100644 src/DataStreamSuite/DataStream/BlueOrb/CSVSaverStream.cs rename src/DataStreamSuite/SharedStreams/{Business => BlueOrb/MarketData}/ContractUtils.cs (92%) create mode 100644 src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveBBOStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesBBOStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesBookStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesContractStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesTradeStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveTradeStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/ReplayFutureLiveBBOStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/ReplayFutureLiveTradeStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/NL/BlueOrbNLStream.cs create mode 100644 src/DataStreamSuite/SharedStreams/NL/BlueOrbNLToDSLStream.cs diff --git a/src/DataStreamSuite/DataStream/BlueOrb/CSVReaderStream.cs b/src/DataStreamSuite/DataStream/BlueOrb/CSVReaderStream.cs new file mode 100644 index 000000000..a8ab0230b --- /dev/null +++ b/src/DataStreamSuite/DataStream/BlueOrb/CSVReaderStream.cs @@ -0,0 +1,18 @@ +namespace bts.BlueOrb { + using System; + + using BCG; + + [DataStreamUserRespresentation("CSVReaderStream")] + public class CSVReaderStream : ViewStream { + public CSVReaderStream(string file_name) + : this(file_name, false) { } + public CSVReaderStream(string file_name, bool guess_schema) { + ViewStream rs = new BCG.CSVReaderStream(file_name); + if (guess_schema) { + rs = new SchemaGuesserStream(rs); + } + mySetRealSource(rs); + } + } +} diff --git a/src/DataStreamSuite/DataStream/BlueOrb/CSVSaverStream.cs b/src/DataStreamSuite/DataStream/BlueOrb/CSVSaverStream.cs new file mode 100644 index 000000000..4f54465a5 --- /dev/null +++ b/src/DataStreamSuite/DataStream/BlueOrb/CSVSaverStream.cs @@ -0,0 +1,13 @@ +namespace bts.BlueOrb { + using BCG; + + using System; + + [DataStreamUserRespresentation("CSVSaverStream")] + public class CSVSaverStream: ViewStream { + public CSVSaverStream(ViewStream parent_str, string file_name) { + BCG.CSVSaverStream rs = new BCG.CSVSaverStream(parent_str, file_name, true, Int32.MaxValue, false); + mySetRealSource(rs); + } + } +} diff --git a/src/DataStreamSuite/DataStream/BlueOrb/GroupByStream.cs b/src/DataStreamSuite/DataStream/BlueOrb/GroupByStream.cs index d62e33c40..81916fee5 100644 --- a/src/DataStreamSuite/DataStream/BlueOrb/GroupByStream.cs +++ b/src/DataStreamSuite/DataStream/BlueOrb/GroupByStream.cs @@ -34,7 +34,8 @@ namespace bts.BlueOrb { if (out_rows != null && out_rows.Count > 0) { rv = rv ?? new BlueTable(out_rows.ElementAt(0).schema); } - rv.addRows(out_rows); + if (rv != null) + rv.addRows(out_rows); } return rv; } @@ -61,20 +62,24 @@ namespace bts.BlueOrb { Func, List> evaluate_func) : this(main_stream, new DelNonIncGroupByEvaluator(groupby_cols_func, evaluate_func)) { } - public GroupByStream(ViewStream parent_str, string groupby_col, string standard_group_by_text) - : this(parent_str, groupby_col, standard_group_by_text, String.Empty) { } + public GroupByStream(ViewStream parent_str, string groupby_cols, string standard_group_by_text) + : this(parent_str, groupby_cols, standard_group_by_text, String.Empty) { } // this is the main constructor that does everything - public GroupByStream(ViewStream parent_str, string groupby_col, string standard_group_by_ops, string optional_sort_col) { + public GroupByStream(ViewStream parent_str, string groupby_cols, string standard_group_by_ops, string optional_sort_col) { MultiRowOpHelper std_group_by = MultiRowOpHelper.parse_ops(standard_group_by_ops); Func groupby_cols_func = () => { - return String.IsNullOrEmpty(groupby_col) ? null : new string[] { groupby_col }; + if (String.IsNullOrEmpty(groupby_cols)) + return null; + return groupby_cols.Split(',').Select(x => x.Trim()).ToArray(); }; Func, List> evaluate_func = (group_rows) => { if (!String.IsNullOrEmpty(optional_sort_col)) group_rows.Sort((r1, r2) => BlueDataUtility.compare_rows(r2, r1, optional_sort_col)); // this si where the group by aggregation happens IBlueRow rv = MultiRowOpHelper.group_by_compute(group_rows, std_group_by); + if (rv == null) + return new List(); return new IBlueRow[] { rv }.ToList(); }; ViewStream rs = new GroupByStream(parent_str, groupby_cols_func, evaluate_func); @@ -105,6 +110,9 @@ namespace bts.BlueOrb { /// reducing _timer.Restart(); IBlueRowCollection total_state = _groupby_func.evaluate(grouped_rows); + if (total_state == null) + // mayeb returna n empty table ? + return; _timer.Stop(); var applyElapsedMs = _timer.ElapsedMilliseconds; _n_total_fires++; @@ -113,9 +121,7 @@ namespace bts.BlueOrb { Log.DataFlow.info( $"Time to evaluate {grouped_rows.Count} groups {_timer.ElapsedMilliseconds}ms, ratio {_n_expensive_fires}/{_n_total_fires}"); } - // TODO, - if (total_state != null) - myFireEvent(new DataPacket(total_state, total_state, myLastValue == null ? new BlueTable(total_state.schema) : (myLastValue as DataPacket).newRows)); + myFireEvent(new DataPacket(total_state, total_state, myLastValue == null ? new BlueTable(total_state.schema) : (myLastValue as DataPacket).newRows)); } } } diff --git a/src/DataStreamSuite/DataStream/BlueOrb/Join/SimpleJoinStream.cs b/src/DataStreamSuite/DataStream/BlueOrb/Join/SimpleJoinStream.cs index 42286727d..14ae2444a 100644 --- a/src/DataStreamSuite/DataStream/BlueOrb/Join/SimpleJoinStream.cs +++ b/src/DataStreamSuite/DataStream/BlueOrb/Join/SimpleJoinStream.cs @@ -20,9 +20,9 @@ private IBlueTableSchema _schema; private int[] _join_cols; private IDictionary> _hash_row_map = new Dictionary>(); - + public JoinBookkeepingData(ViewStream vs, List join_cols, bool is_left, BlueRowHasher row_hasher) { - _join_col_names = join_cols.Where (c => !String.IsNullOrEmpty(c)).ToList (); + _join_col_names = join_cols.Where(c => !String.IsNullOrEmpty(c)).ToList(); _is_left = is_left; _hasher = row_hasher; } @@ -31,23 +31,23 @@ public IDictionary> rows => _hash_row_map; - public List get_matching_rows (int hash) { + public List get_matching_rows(int hash) { List rv = null; _hash_row_map.TryGetValue(hash, out rv); return rv; } private RowHash _get_hash(IBlueRow r) { - if (_join_cols == null || _join_cols.Length == 0) { + if (_join_cols == null || _join_cols.Length == 0) { return 0; } return _hasher.get_hash(r, _join_cols); } public void update_data(DataPacket dp) { - if (!ready) { + if (!ready) { _schema = dp.newRows.schema; - _join_cols = _join_col_names.Count == 0 ? new int[] { }: _join_col_names.Select(n => dp.schema[n].colNo).ToArray(); + _join_cols = _join_col_names.Count == 0 ? new int[] { } : _join_col_names.Select(n => dp.schema[n].colNo).ToArray(); } _hash_row_map.Clear(); foreach (IBlueRow r in dp.newRows) { @@ -82,7 +82,7 @@ _rs = rs; List lj_col_list = ljc.Split(',').Where(x => !String.IsNullOrEmpty(x)).ToList(); List rj_col_list = rjc.Split(',').Where(x => !String.IsNullOrEmpty(x)).ToList(); - Log.assert(lj_col_list.Count == rj_col_list.Count); + Log.assert(lj_col_list.Count == rj_col_list.Count); int n_cols = lj_col_list.Count; BlueRowHasher hasher = new BlueRowHasher(n_cols); _ldata = new JoinBookkeepingData(ls, lj_col_list, true, hasher); @@ -101,7 +101,7 @@ } private void _rs_onchange(object dp_obj) { - DataPacket dp = dp_obj as DataPacket ; + DataPacket dp = dp_obj as DataPacket; _rdata.update_data(dp); _form_and_fire(); } @@ -128,11 +128,11 @@ } private void _form_and_fire() { - if (!_ldata.ready||!_rdata.ready) + if (!_ldata.ready || !_rdata.ready) return; _build_schema(); List res_rows = new List(); - + Action copy_row = (rval, r, is_left) => { int offset = 1; JoinBookkeepingData sdata = _ldata; @@ -148,7 +148,7 @@ } }; Func build_row_array = (id, l_row) => { - object[] rv = new object[_schema.columnNames.Length]; + object[] rv = new object[_schema.columnNames.Length]; for (int i = 0; i < _schema.columnNames.Length; i++) { rv[i] = DBNull.Value; } @@ -162,7 +162,7 @@ List l_rows = kv.Value; List r_rows = _rdata.get_matching_rows(hash); - foreach (IBlueRow lr in l_rows) { + foreach (IBlueRow lr in l_rows) { if (r_rows != null) { foreach (IBlueRow r in r_rows) { object[] rowvals = build_row_array(res_rows.Count, lr); @@ -182,6 +182,15 @@ var dp = BlueDataUtility.build_dp(rv, myLastValue as DataPacket); myFireEvent(dp); } - } + + [DataStreamUserRespresentation("FullJoinStream")] + public class FullJoinStream : ViewStream { + public FullJoinStream(ViewStream l_str, string ljcs, ViewStream r_str, string rjcs) { + ViewStream js = new SimpleJoinStream(l_str, ljcs, r_str, rjcs); + ViewStream rs = new bts.BlueOrb.FilterStream(js, r => !DBNull.Value.Equals(r["right_id"])); + mySetRealSource(rs); + } + } + } diff --git a/src/DataStreamSuite/DataStream/BlueOrb/MultiRowOpHelper.cs b/src/DataStreamSuite/DataStream/BlueOrb/MultiRowOpHelper.cs index a4b03389e..2b0b70d16 100644 --- a/src/DataStreamSuite/DataStream/BlueOrb/MultiRowOpHelper.cs +++ b/src/DataStreamSuite/DataStream/BlueOrb/MultiRowOpHelper.cs @@ -150,6 +150,14 @@ namespace bts.BlueOrb { return col_vals.Last(); case MultiRowOp.StdDev: return MathNet.Numerics.Statistics.Statistics.StandardDeviation(col_vals); + case MultiRowOp.EdgeDiff: + return col_vals.First() - col_vals.Last(); + case MultiRowOp.EdgeDiffPercentage: { + double first = col_vals.First(); + double last = col_vals.Last(); + return ((first - last) / last) * 100.0; + return col_vals.First() - col_vals.Last(); + } default: // TODO Log.assert(false); diff --git a/src/DataStreamSuite/DataStream/BlueOrb/PythonDataframeStream.cs b/src/DataStreamSuite/DataStream/BlueOrb/PythonDataframeStream.cs index a8f9625ca..02714aeaf 100644 --- a/src/DataStreamSuite/DataStream/BlueOrb/PythonDataframeStream.cs +++ b/src/DataStreamSuite/DataStream/BlueOrb/PythonDataframeStream.cs @@ -37,7 +37,8 @@ // now this function should read _out_csv_filename into a dp // and fire it _compute_and_write(); - ViewStream rs = new SchemaGuesserStream(new CSVReaderStream(_out_csv_filename)); + //ViewStream rs = new SchemaGuesserStream(new CSVReaderStream(_out_csv_filename)); + ViewStream rs = new CSVReaderStream(_out_csv_filename); IBlueRowCollection nrows = null; rs.onChange += (dp_obj) => { nrows = (dp_obj as DataPacket).newRows; diff --git a/src/DataStreamSuite/DataStream/BlueOrb/TimeSeriesStream.cs b/src/DataStreamSuite/DataStream/BlueOrb/TimeSeriesStream.cs index 3e308c76e..557da7ea7 100644 --- a/src/DataStreamSuite/DataStream/BlueOrb/TimeSeriesStream.cs +++ b/src/DataStreamSuite/DataStream/BlueOrb/TimeSeriesStream.cs @@ -1,18 +1,25 @@ using System; +using System.Data.Entity.Core.Mapping; using BCG; namespace bts.BlueOrb { // Keeps adding changing rows to the stream, hence preserving the history // and creating a time series, for example this can be used to make bbo updates - // into a time series of prices/qty + // into a time series of prices/qty + [DataStreamUserRespresentation("TimeSeriesStream")] public class TimeSeriesStream : ViewStream { - private BlueTable _table; + private CircularBufferTable _table; private ViewStream _stream; private int _id = 0; + private int _size = 0; - public TimeSeriesStream(ViewStream stream) { + public TimeSeriesStream(ViewStream stream) + : this(stream, Int32.MaxValue) { } + + public TimeSeriesStream(ViewStream stream, int size) { _stream = stream; + _size = size; } protected override void myOnFirstSubscriber() { @@ -29,17 +36,16 @@ namespace bts.BlueOrb { if (_table == null) { IBlueTableSchema schema = new BlueTableSchema(dp.newRows.schema.columnInfo, dp.newRows.schema.tableName); schema = schema.add_columns(Tuple.Create(typeof(DateTime), "timestamp")); - _table = new BlueTable(schema); + _table = new CircularBufferTable(schema, _size); } - BlueTable added_rows = new BlueTable(_table.schema); foreach (IBlueRow r in dp.addedRows) { MutableBlueRow ar = new MutableBlueRow(_table.schema, r); ar.setValue("timestamp", now); ar.setValue("id", _id++); - added_rows.addRow(ar); + _table.add_row(ar); } - _table.addRows(added_rows); - myFireEvent(new DataPacket(_table, added_rows, new BlueTable(_table.schema))); + var dp_out = BlueDataUtility.build_dp(_table, myLastValue as DataPacket); + myFireEvent(dp_out); } } diff --git a/src/DataStreamSuite/DataStream/Misc/DSLStream.cs b/src/DataStreamSuite/DataStream/Misc/DSLStream.cs index c652e15e8..ca043adc5 100644 --- a/src/DataStreamSuite/DataStream/Misc/DSLStream.cs +++ b/src/DataStreamSuite/DataStream/Misc/DSLStream.cs @@ -1,4 +1,4 @@ -namespace bts.SilverPine { +namespace bts.BlueOrb { using System; using BCG; using System.Collections.Generic; @@ -29,4 +29,4 @@ namespace bts.SilverPine { } } } -} \ No newline at end of file +} diff --git a/src/DataStreamSuite/DataStream/Primitives/Filter/TimeBasedFilter.cs b/src/DataStreamSuite/DataStream/Primitives/Filter/TimeBasedFilter.cs index 02fc44fc9..d4f5e205a 100644 --- a/src/DataStreamSuite/DataStream/Primitives/Filter/TimeBasedFilter.cs +++ b/src/DataStreamSuite/DataStream/Primitives/Filter/TimeBasedFilter.cs @@ -71,11 +71,10 @@ namespace BCG { #region IStreamFilter public bool filter(IBlueRow row) { - DateTime now = DateTime.Now; - - DateTime row_time = row.get_datetime(_time_col, DateTime.Now); - if (now > row_time) { - TimeSpan span = now - row_time; + DateTime now_utc = DateTime.UtcNow; + DateTime row_time_utc = row.get_datetime(_time_col, DateTime.Now).ToUniversalTime(); + if (now_utc > row_time_utc) { + TimeSpan span = now_utc - row_time_utc; if (span >= _ttl) { return (false); } diff --git a/src/DataStreamSuite/DataStream/Primitives/SQL/SQLite/SQLiteHelper.cs b/src/DataStreamSuite/DataStream/Primitives/SQL/SQLite/SQLiteHelper.cs index c52240096..b9610e3fc 100644 --- a/src/DataStreamSuite/DataStream/Primitives/SQL/SQLite/SQLiteHelper.cs +++ b/src/DataStreamSuite/DataStream/Primitives/SQL/SQLite/SQLiteHelper.cs @@ -15,7 +15,7 @@ using System.Data.SQLite; namespace bts.BlueOrb{ public static class SQLiteHelper { - public static string location = "C:\\Users\\m_tah\\development\\data\\"; + public static string location = "C:\\BlueOrb_Data\\"; public static string db_name = "stream_data.db"; public static DataTable execute_select_query(string connection_string, string query) { diff --git a/src/DataStreamSuite/DataStream/Primitives/SideEffectStreams/CSVSaverStream.cs b/src/DataStreamSuite/DataStream/Primitives/SideEffectStreams/CSVSaverStream.cs index 41eb76390..12324e741 100644 --- a/src/DataStreamSuite/DataStream/Primitives/SideEffectStreams/CSVSaverStream.cs +++ b/src/DataStreamSuite/DataStream/Primitives/SideEffectStreams/CSVSaverStream.cs @@ -112,10 +112,10 @@ namespace BCG { } protected override void myOnFirstSubscriber() { - _stopwatch.Start(); - DataFrame df = DataFrame.LoadCsv(_file_address); - _stopwatch.Stop(); - bts.Log.Gen.info($"CSVReaderStream.myOnFirstSubscriber stream csv load col_count: {df.Columns.Count} rows, time: {_stopwatch.ElapsedMilliseconds} msecs"); + //_stopwatch.Start(); + //DataFrame df = DataFrame.LoadCsv(_file_address); + //_stopwatch.Stop(); + //bts.Log.Gen.info($"CSVReaderStream.myOnFirstSubscriber stream csv load col_count: {df.Columns.Count} rows, time: {_stopwatch.ElapsedMilliseconds} msecs"); _stopwatch.Start(); IBlueRowCollection rows = BlueDataUtility.createRowsFromCSVFileWithoutTypes(_file_address); _stopwatch.Stop(); diff --git a/src/DataStreamSuite/SharedStreams/Business/ContractUtils.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/ContractUtils.cs similarity index 92% rename from src/DataStreamSuite/SharedStreams/Business/ContractUtils.cs rename to src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/ContractUtils.cs index 8a60b1c9b..cdb35395f 100644 --- a/src/DataStreamSuite/SharedStreams/Business/ContractUtils.cs +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/ContractUtils.cs @@ -1,6 +1,7 @@ using bts.SilverPine; namespace bts.BlueOrb { + using bts; //using bts.api; //using bts.spark; @@ -16,10 +17,10 @@ namespace bts.BlueOrb { public string contract_text; } public class FutureSpreadContract { - public List> legs; + public List> legs; 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; @@ -58,6 +59,10 @@ namespace bts.BlueOrb { continous_constract = new FutureContinousContract() { symbol = txt }; } public bool is_continous_contract => continous_constract != null; + public bool is_wildcard_contract => wildcard_contract != null; + public bool is_future_tradable_contract => future_tradable_contract != null; + public bool is_spread_tradable_contract => spread_tradable_contract != null; + public string symbol() { if (wildcard_contract != null) return wildcard_contract.symbol; @@ -69,7 +74,7 @@ namespace bts.BlueOrb { return spread_tradable_contract.symbol; } Log.assert(false); - return String.Empty; + return string.Empty; } public string contract_text { get { @@ -84,7 +89,7 @@ namespace bts.BlueOrb { #region Parsing public static FutureWildcardContract parse_wildcard_contract(string contract_txt, Exchange exchange = Exchange.CME) { if (contract_txt.EndsWith("*")) { - contract_txt = contract_txt.Replace("*", String.Empty); + contract_txt = contract_txt.Replace("*", string.Empty); return new FutureWildcardContract() { symbol = contract_txt, exchange = exchange @@ -94,7 +99,7 @@ namespace bts.BlueOrb { } 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))) + if (!contract_txt.All(c => char.IsLetterOrDigit(c))) return null; if (contract_txt.Length < 4) { return null; @@ -206,7 +211,7 @@ namespace bts.BlueOrb { } // tehre are some non calendar spreads we cant parse //Log.assert(false); - return ContractUtils.ContractType.FutureSpread; + return ContractType.FutureSpread; } public static ContractCategory get_category(string symbol) { @@ -215,7 +220,7 @@ namespace bts.BlueOrb { } public static Tuple get_symbol_category(string symbol) { - ContractUtils.FutureTradableContract fc = parse_future_contract(symbol); + FutureTradableContract fc = parse_future_contract(symbol); if (fc != null) { return Tuple.Create(ContractCategory.FutureString, fc.symbol); } diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Historical/HistoricalBarsStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Historical/HistoricalBarsStream.cs index e56f6a7fe..db434cd7c 100644 --- a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Historical/HistoricalBarsStream.cs +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Historical/HistoricalBarsStream.cs @@ -2,9 +2,6 @@ namespace bts.BlueOrb { using bts.SilverPine; using BCG; - using System.Runtime.CompilerServices; - - using ZstdSharp.Unsafe; public class DateTimeRange { public readonly DateTime range_beg; @@ -149,21 +146,22 @@ namespace bts.BlueOrb { [DataStreamUserRespresentation("FutureHistoricalBarsStream")] public class FutureHistoricalBarsStream : ViewStream { - public FutureHistoricalBarsStream(string fut_contract, string range_beg, string range_end) { - DateTime dt_range_beg = DateTime.Parse(range_beg); - DateTime dt_range_end = DateTime.Parse(range_end); - TimeSpan diff = dt_range_end - dt_range_beg; - BarSize bar_size = diff < TimeSpan.FromDays(1.0) ? BarSize.ONE_MIN : BarSize.ONE_DAY; - ViewStream rs = new FutureHistoricalBarsStream(fut_contract, bar_size.ToString(), dt_range_beg, dt_range_end); - mySetRealSource(rs); - } + //public FutureHistoricalBarsStream(string fut_contract, string range_beg, string range_end) { + // DateTime dt_range_beg = DateTime.Parse(range_beg).ToUniversalTime(); + // DateTime dt_range_end = DateTime.Parse(range_end).ToUniversalTime(); + // TimeSpan diff = dt_range_end - dt_range_beg; + // BarSize bar_size = diff < TimeSpan.FromDays(1.0) ? BarSize.ONE_MIN : BarSize.ONE_DAY; + // ViewStream rs = new FutureHistoricalBarsStream(fut_contract, bar_size.ToString(), dt_range_beg, dt_range_end); + // mySetRealSource(rs); + //} public FutureHistoricalBarsStream(string fut_contract, string bar_size) : this(fut_contract, bar_size, DateTime.MinValue, DateTime.MaxValue) { } public FutureHistoricalBarsStream(string fut_contract, string bar_size, string dt_range_beg, string dt_range_end) - : this(fut_contract, bar_size, DateTime.Parse(dt_range_beg), - DateTime.Parse(dt_range_end)) { } + : this(fut_contract, bar_size, + DateTime.Parse(dt_range_beg).ToUniversalTime(), + DateTime.Parse(dt_range_end).ToUniversalTime()) { } public FutureHistoricalBarsStream(string fut_contract, string bar_size, DateTime dt_range_beg, DateTime dt_range_end) diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveBBOStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveBBOStream.cs new file mode 100644 index 000000000..7fe3f7adf --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveBBOStream.cs @@ -0,0 +1,26 @@ +namespace bts.BlueOrb + { + using System; + + using BCG; + + using bts.api; + + [DataStreamUserRespresentation("LiveBBOStream")] + public class LiveBBOStream : ViewStream { + public LiveBBOStream(string target) + : this(SecurityType.Future, target) { } + public LiveBBOStream(SecurityType sec_type, string target) { + ViewStream rs = null; + switch (sec_type) { + case SecurityType.Future: + rs = new LiveFuturesBBOStream(target); + break; + default: + Log.assert(false); + break; + } + mySetRealSource(rs); + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesBBOStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesBBOStream.cs new file mode 100644 index 000000000..f3a0340cd --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesBBOStream.cs @@ -0,0 +1,18 @@ +namespace bts.BlueOrb { + using BCG; + + using System; + + [DataStreamUserRespresentation("LiveFuturesBBOStream")] + public class LiveFuturesBBOStream : ViewStream { + public LiveFuturesBBOStream (string future_target) { + var rs = new ReplayFutureLiveBBOStream (future_target); + mySetRealSource(rs); + //ViewStream contract_str = new LiveFuturesContractStream (future_target); + //ViewStream bbo_str = new BBOStream(); + //ViewStream rs = new SimpleJoinStream(contract_str, "sec_key", bbo_str, "sec_key"); + //rs = new ProjectStream(rs, "left_sec:sec, left_sec_key:sec_key, bid_price, bid_sz:bid_size, ask_price, ask_sz:ask_size"); + //mySetRealSource(rs); + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesBookStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesBookStream.cs new file mode 100644 index 000000000..470e67c23 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesBookStream.cs @@ -0,0 +1,16 @@ +namespace bts.BlueOrb { + using BCG; + + using System; + + [DataStreamUserRespresentation("LiveFuturesBooktream")] + public class LiveFuturesBooktream : ViewStream { + public LiveFuturesBooktream(string future_target) { + ViewStream contract_str = new LiveFuturesContractStream(future_target); + ViewStream bbo_str = new BookStream(); + ViewStream rs = new SimpleJoinStream(contract_str, "sec_key", bbo_str, "sec_key"); + rs = new ProjectStream(rs, "left_sec:sec, left_sec_key:sec_key, bid_price, bid_sz:bid_size, ask_price, ask_sz:ask_size"); + mySetRealSource(rs); + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesContractStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesContractStream.cs new file mode 100644 index 000000000..74b780cca --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesContractStream.cs @@ -0,0 +1,51 @@ +namespace bts.BlueOrb { + using System; + + using BCG; + + using bts.api; + + [DataStreamUserRespresentation("LiveFuturesContractStream")] + public class LiveFuturesContractStream : ViewStream { + public LiveFuturesContractStream(string target) { + var fc = new ContractUtils.FutureContract(target); + // temporary + ViewStream ins_str = new InstrumentsStream(); + //new bts.BlueOrb.CSVReaderStream(@"C:\Temp\instruments.csv"); + var rs = new LiveFuturesContractStream(ins_str, fc); + mySetRealSource(rs); + } + public LiveFuturesContractStream(ViewStream parent_str, ContractUtils.FutureContract fc) { + // 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}'"); + 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}'"); + 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}'"); + 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}'"); + 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); + var rv = new List(); + rv.Add(r); + return rv; + }); + mySetRealSource(rs); + return; + } + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesTradeStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesTradeStream.cs new file mode 100644 index 000000000..5742c0160 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveFuturesTradeStream.cs @@ -0,0 +1,13 @@ +namespace bts.BlueOrb { + using BCG; + + using System; + + [DataStreamUserRespresentation("LiveFuturesTradeStream")] + public class LiveFuturesTradeStream : ViewStream { + public LiveFuturesTradeStream(string future_target) { + var rs = new ReplayFutureLiveTradeStream(future_target); + mySetRealSource(rs); + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveTradeStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveTradeStream.cs new file mode 100644 index 000000000..a38e5cce1 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/LiveTradeStream.cs @@ -0,0 +1,25 @@ +namespace bts.BlueOrb { + using System; + + using BCG; + + using bts.api; + + [DataStreamUserRespresentation("LiveTradeStream")] + public class LiveTradeStream : ViewStream { + public LiveTradeStream(string target) + : this(SecurityType.Future, target) { } + public LiveTradeStream(SecurityType sec_type, string target) { + ViewStream rs = null; + switch (sec_type) { + case SecurityType.Future: + rs = new LiveFuturesTradeStream(target); + break; + default: + Log.assert(false); + break; + } + mySetRealSource(rs); + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/ReplayFutureLiveBBOStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/ReplayFutureLiveBBOStream.cs new file mode 100644 index 000000000..7adf95c9c --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/ReplayFutureLiveBBOStream.cs @@ -0,0 +1,93 @@ +namespace bts.BlueOrb { + 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{ + private class LastFireTime { + public DateTime last_fireitme_file = DateTime.MinValue; + public DateTime last_firetime_clock = DateTime.MinValue; + } + private class RowsWithPointer { + public List rows; + public int pointer; + } + + + private readonly ViewStreamDatabase _vsd; + private readonly ContractUtils.FutureContinousContract _fcc; + private readonly LastFireTime _last_fire_time = new LastFireTime(); + private RowsWithPointer _rows = new RowsWithPointer(); + + public ReplayFutureLiveBBOStream(string continous_contract) { + Func iso_8601_now = () => { + DateTime utc_now = DateTime.UtcNow; + long ticks = utc_now.Ticks; // 1 tick = 100 ns + long nanoseconds = ticks % TimeSpan.TicksPerSecond * 100; + string formatted = utc_now.ToString("yyyy-MM-ddTHH:mm:ss"); + formatted += $".{nanoseconds:D9}Z"; + return formatted; + }; + ViewStream rs = new ReplayFutureLiveBBOStream(continous_contract, 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("bid_price", TypeCode.Double), + Tuple.Create("bid_size", TypeCode.Int32), + Tuple.Create("ask_price", TypeCode.Double), + Tuple.Create("ask_size", TypeCode.Int32)); + rs = new MapStream(rs, s => schema_out, + r => + new BlueRow(schema_out, r["id"], /*r.get("ts_event")*/iso_8601_now(), r.get("symbol"), + r.get("bid_px_00"), r.get("bid_sz_00"), + r.get("ask_px_00"), r.get("ask_sz_00"))); + mySetRealSource(rs); + } + + private ReplayFutureLiveBBOStream(string continous_contract, bool noop) + : this(ViewStreamDatabase.instance, new ContractUtils.FutureContract(continous_contract)) + {} + + public ReplayFutureLiveBBOStream(ViewStreamDatabase vsd, ContractUtils.FutureContract fc) { + var fcc = fc.continous_constract; + Log.assert(fcc != null); + _vsd = vsd; + _fcc = fcc; + } + + protected override void myOnFirstSubscriber() { + var file_path = $"{SQLiteHelper.location}\\mbp1_{_fcc.symbol}_small.csv"; + var csv_rd = new CSVReaderStream(file_path, false); + _rows.rows = csv_rd.rows.to_list().OrderBy(r => r.get("ts_event")).ToList(); + _rows.pointer = 0; + _vsd.addWorker(this); + } + + protected override void myOnLastSubscriber() { + _vsd.removeWorker(this); + } + + public void doWork() { + IBlueRow cand_row = _rows.rows[_rows.pointer]; + string cand_ts_event = cand_row.get("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(cand_row); + var dp_out = BlueDataUtility.build_dp(bt_out, myLastValue as DataPacket); + myFireEvent(dp_out); + } + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/ReplayFutureLiveTradeStream.cs b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/ReplayFutureLiveTradeStream.cs new file mode 100644 index 000000000..d40755b42 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/BlueOrb/MarketData/Live/ReplayFutureLiveTradeStream.cs @@ -0,0 +1,92 @@ +namespace bts.BlueOrb { + 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 { + private class LastFireTime { + public DateTime last_fireitme_file = DateTime.MinValue; + public DateTime last_firetime_clock = DateTime.MinValue; + } + private class RowsWithPointer { + public List rows; + public int pointer; + } + + + private readonly ViewStreamDatabase _vsd; + private readonly ContractUtils.FutureContinousContract _fcc; + private readonly LastFireTime _last_fire_time = new LastFireTime(); + private RowsWithPointer _rows = new RowsWithPointer(); + + public ReplayFutureLiveTradeStream(string continous_contract) { + Func iso_8601_now = () => { + DateTime utc_now = DateTime.UtcNow; + long ticks = utc_now.Ticks; // 1 tick = 100 ns + long nanoseconds = ticks % TimeSpan.TicksPerSecond * 100; + string formatted = utc_now.ToString("yyyy-MM-ddTHH:mm:ss"); + formatted += $".{nanoseconds:D9}Z"; + return formatted; + }; + ViewStream rs = new ReplayFutureLiveTradeStream(continous_contract, 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.Int32), + Tuple.Create("aggressor_side", TypeCode.String)); + rs = new MapStream(rs, s => schema_out, + r => + new BlueRow(schema_out, r["id"], /*r.get("ts_event")*/iso_8601_now(), r.get("symbol"), + r.get("size"), r.get("price"), + r.get("side").StartsWith("B") ? "BUY" : (r.get("side").StartsWith("A") ? "SELL" : "NONE"))); + rs = new TimeSeriesStream(rs); + mySetRealSource(rs); + } + + private ReplayFutureLiveTradeStream(string continous_contract, bool noop) + : this(ViewStreamDatabase.instance, new ContractUtils.FutureContract(continous_contract)) { } + + public ReplayFutureLiveTradeStream(ViewStreamDatabase vsd, ContractUtils.FutureContract fc) { + var fcc = fc.continous_constract; + Log.assert(fcc != null); + _vsd = vsd; + _fcc = fcc; + } + + protected override void myOnFirstSubscriber() { + var file_path = $"{SQLiteHelper.location}\\trades_{_fcc.symbol}.csv"; + var csv_rd = new CSVReaderStream(file_path, false); + _rows.rows = csv_rd.rows.to_list().OrderBy(r => r.get("ts_event")).ToList(); + _rows.pointer = 0; + _vsd.addWorker(this); + } + + protected override void myOnLastSubscriber() { + _vsd.removeWorker(this); + } + + public void doWork() { + IBlueRow cand_row = _rows.rows[_rows.pointer]; + string cand_ts_event = cand_row.get("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(cand_row); + var dp_out = BlueDataUtility.build_dp(bt_out, myLastValue as DataPacket); + myFireEvent(dp_out); + } + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/Business/MarketData/BBOStream.cs b/src/DataStreamSuite/SharedStreams/Business/MarketData/BBOStream.cs index 4bf57787e..31df64695 100644 --- a/src/DataStreamSuite/SharedStreams/Business/MarketData/BBOStream.cs +++ b/src/DataStreamSuite/SharedStreams/Business/MarketData/BBOStream.cs @@ -149,7 +149,7 @@ namespace bts.BlueOrb { } private void _on_books(TableUpdate update) { - _log_updates(update); + //_log_updates(update); // just cacching in here, will populate the rows in _poll_scan and fire the datapacket //bts.Log.Gen.info($"BBOStream._on_books state: {update.state.Count()} changes: {update.changes.Count()} added: {update.added.Count()}"); _cached_state = update.state; @@ -166,6 +166,8 @@ namespace bts.BlueOrb { return; BlueTable new_state = new BlueTable(_bbo_schema); foreach (var kv in _cached_state) { + if (!kv.Value.security.HasFuture) + continue; SecurityKey skey = kv.Key; var sec = kv.Value.security; int id = Convert.ToInt32(skey); diff --git a/src/DataStreamSuite/SharedStreams/Business/MarketData/BookStream.cs b/src/DataStreamSuite/SharedStreams/Business/MarketData/BookStream.cs index 1556bde33..03ce1f0c6 100644 --- a/src/DataStreamSuite/SharedStreams/Business/MarketData/BookStream.cs +++ b/src/DataStreamSuite/SharedStreams/Business/MarketData/BookStream.cs @@ -26,8 +26,9 @@ namespace bts.BlueOrb{ MarketDataClient _md_client; readonly Stopwatch _timer = new(); private readonly IBlueTableSchema _bbo_schema = BlueDataUtility.form_schema("books", - Tuple.Create("id", TypeCode.Int32), + Tuple.Create("id", TypeCode.Int32), Tuple.Create("sec_key", TypeCode.UInt32), + Tuple.Create("sec", TypeCode.String), Tuple.Create("level", TypeCode.UInt32), Tuple.Create("bid_price", TypeCode.Double), Tuple.Create("bid_sz", TypeCode.Single), @@ -94,7 +95,7 @@ namespace bts.BlueOrb{ BookTuple bt = kv.Value; for (int level = 0; level < bt.book.bids.Count; level++) { int id = _get_id(skey, level); - IBlueRow r = new BlueRow(_bbo_schema, id, skey, Convert.ToUInt32(level), bt.book.bids[level].price, bt.book.bids[0].size, + IBlueRow r = new BlueRow(_bbo_schema, id, skey, bt.security.ToString(), Convert.ToUInt32(level), bt.book.bids[level].price, bt.book.bids[0].size, bt.book.asks[level].price, bt.book.asks[level].size); new_state.addRow(r); } diff --git a/src/DataStreamSuite/SharedStreams/Business/MarketData/FuturesActiveContractStream.cs b/src/DataStreamSuite/SharedStreams/Business/MarketData/FuturesActiveContractStream.cs index 834344e5f..9d23bbfb6 100644 --- a/src/DataStreamSuite/SharedStreams/Business/MarketData/FuturesActiveContractStream.cs +++ b/src/DataStreamSuite/SharedStreams/Business/MarketData/FuturesActiveContractStream.cs @@ -2,6 +2,7 @@ namespace bts.BlueOrb{ using BCG; using bts; + // Given volume data per date for all futures (all exps + spreads) it selects the // the future with the highest volume [DataStreamUserRespresentation("FuturesActiveContract")] diff --git a/src/DataStreamSuite/SharedStreams/Business/MarketData/InstrumentsStream.cs b/src/DataStreamSuite/SharedStreams/Business/MarketData/InstrumentsStream.cs index 0005e9814..3845eb2e9 100644 --- a/src/DataStreamSuite/SharedStreams/Business/MarketData/InstrumentsStream.cs +++ b/src/DataStreamSuite/SharedStreams/Business/MarketData/InstrumentsStream.cs @@ -16,7 +16,7 @@ namespace bts.BlueOrb { using SecurityKey = System.UInt32; - [DataStreamUserRespresentation("instruments")] + [DataStreamUserRespresentation("InstrumentsStream")] public class InstrumentsStream : ViewStream, IWorker { private readonly TimeSpan _poll_period = TimeSpan.FromMilliseconds(500); private DateTime _last_poll_time = DateTime.MinValue; @@ -33,6 +33,7 @@ namespace bts.BlueOrb { Tuple.Create("venue", TypeCode.String), Tuple.Create("symbol", TypeCode.String), Tuple.Create("currency", TypeCode.String), + Tuple.Create("cpp", TypeCode.Double), Tuple.Create("expiration", TypeCode.DateTime), Tuple.Create("strike", TypeCode.Double), Tuple.Create("callput", TypeCode.String) @@ -63,7 +64,7 @@ namespace bts.BlueOrb { private void _on_instruments(IReadOnlyDictionary state) { _dirty = true; - _log_updates(state); + //_log_updates(state); // just cacching in here, will populate the rows in _poll_scan and fire the datapacket bts.Log.Gen.info($"InstrumentsStream._on_instruments state: {state.Count()}"); _cached_state = state; @@ -83,7 +84,7 @@ namespace bts.BlueOrb { foreach (var kv in _cached_state) { SecurityKey skey = kv.Key; int id = Convert.ToInt32(skey); - SecurityImmutable sec = kv.Value; + SecurityImmutable sec = kv.Value; 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) @@ -94,7 +95,7 @@ namespace bts.BlueOrb { object cp = DBNull.Value; if (sec_type == bts.api.SecurityType.Option) cp = sec.Option.CallPut.ToString(); - IBlueRow r = new BlueRow(_instrument_schema, id, skey, sec.security_desc(), sec.security_type().ToString(), sec.display_exchange().ToString(), sec.Symbol, sec.Currency, exp, strike, cp); + 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; diff --git a/src/DataStreamSuite/SharedStreams/Business/MarketData/OHLCVStream.cs b/src/DataStreamSuite/SharedStreams/Business/MarketData/OHLCVStream.cs index 192885118..26069e458 100644 --- a/src/DataStreamSuite/SharedStreams/Business/MarketData/OHLCVStream.cs +++ b/src/DataStreamSuite/SharedStreams/Business/MarketData/OHLCVStream.cs @@ -1,7 +1,6 @@ namespace bts.BlueOrb { using bts; using BCG; - using MongoDB.Driver; // OHLCV request breakdown // symbol_or_contract (if symbol, get continous, otherwise get raw and filter it) @@ -10,7 +9,7 @@ namespace bts.BlueOrb { // time range // internal code oranization only - public class OHLCV_1min_stream : ViewStream { + internal class OHLCV_1min_stream : ViewStream { public OHLCV_1min_stream(string symbol_or_contract, string range_beg, string range_end) : this(symbol_or_contract, DateTime.Parse(range_beg), DateTime.Parse(range_end)) { } @@ -56,37 +55,37 @@ namespace bts.BlueOrb { // this is to make bigger bars form smaller bars. Right now the assumption it only works // with symbols vs contracts, and the 1min <= aggregation_period < 1day - [DataStreamUserRespresentation("OHLCVAggregated")] - public class OHLCVAggregatedStream : ViewStream { - public OHLCVAggregatedStream(string symbol, string agregation_period, string range_beg, string range_end) : - this(symbol, TimeBasedFilter.parse_duration(agregation_period), DateTime.Parse(range_beg), DateTime.Parse(range_end)) { - } + //[DataStreamUserRespresentation("OHLCVAggregated")] + //public class OHLCVAggregatedStream : ViewStream { + // public OHLCVAggregatedStream(string symbol, string agregation_period, string range_beg, string range_end) : + // this(symbol, TimeBasedFilter.parse_duration(agregation_period), DateTime.Parse(range_beg), DateTime.Parse(range_end)) { + // } - public OHLCVAggregatedStream(string symbol, TimeSpan aggregation_period, DateTime range_beg, DateTime range_end) { - Tuple tup = ContractUtils.get_symbol_category(symbol); - Log.assert(tup.Item1 == ContractUtils.ContractCategory.Symbol); - if (aggregation_period < TimeSpan.FromDays(1.0) && - aggregation_period > TimeSpan.FromMinutes(1.0)) { - ViewStream r = new OHLCV_1min_stream(symbol, range_beg, range_end); - r = new DateTimeExpanstionStream(r, - "ts_event"); - double tot_secs = aggregation_period.TotalSeconds; - r = new MathStream(r, - $"bucket = Floor(ts_event_seconds_of_day / {tot_secs})"); - r = new NonIncGroupByStream(r, - "bucket", - // column:operation - "open:first, high:max, low:min, close:last, volume:sum", - "ts_event"); - r = new SortStream(r, - "-ts_event"); - mySetRealSource(r); - } else { - // fix it later - Log.assert(false); - } - } - } + // public OHLCVAggregatedStream(string symbol, TimeSpan aggregation_period, DateTime range_beg, DateTime range_end) { + // Tuple tup = ContractUtils.get_symbol_category(symbol); + // Log.assert(tup.Item1 == ContractUtils.ContractCategory.Symbol); + // if (aggregation_period < TimeSpan.FromDays(1.0) && + // aggregation_period > TimeSpan.FromMinutes(1.0)) { + // ViewStream r = new OHLCV_1min_stream(symbol, range_beg, range_end); + // r = new DateTimeExpanstionStream(r, + // "ts_event"); + // double tot_secs = aggregation_period.TotalSeconds; + // r = new MathStream(r, + // $"bucket = Floor(ts_event_seconds_of_day / {tot_secs})"); + // r = new NonIncGroupByStream(r, + // "bucket", + // // column:operation + // "open:first, high:max, low:min, close:last, volume:sum", + // "ts_event"); + // r = new SortStream(r, + // "-ts_event"); + // mySetRealSource(r); + // } else { + // // fix it later + // Log.assert(false); + // } + // } + //} [DataStreamUserRespresentation("OHLCV")] diff --git a/src/DataStreamSuite/SharedStreams/NL/BlueOrbNLStream.cs b/src/DataStreamSuite/SharedStreams/NL/BlueOrbNLStream.cs new file mode 100644 index 000000000..dfc593b54 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/NL/BlueOrbNLStream.cs @@ -0,0 +1,38 @@ +namespace bts.BlueOrb { + using BCG; + + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + [DataStreamUserRespresentation("nl")] + public class BlueOrbNLStream : ViewStream { + private readonly string _nl_prompt; + private ViewStream _nl_to_dsl_stream, _dsl_stream; + public BlueOrbNLStream(string nl_prompt) { + _nl_prompt = nl_prompt; + } + + protected override void myOnFirstSubscriber() { + _nl_to_dsl_stream = new BlueOrbNLToDSLStream(_nl_prompt); + _nl_to_dsl_stream.onChange += _handle_dsl_callback; + } + + private void _handle_dsl_callback(object dp_obj) { + DataPacket dp = dp_obj as DataPacket; + var r = dp.newRows.to_list().ElementAt(0); + string dsl = r.get("response"); + Log.Gen.info($"NLStream._handle_dsl_callback dsl: {dsl}"); + _dsl_stream = new DSLStream(dsl); + _dsl_stream.onChange += _handle_data_cb; + } + + private void _handle_data_cb(object dp_obj) { + var dp = dp_obj as DataPacket; + DataPacket dp_out = BlueDataUtility.build_dp_inc(dp.newRows, myLastValue as DataPacket); + myFireEvent(dp_out); + } + } +} diff --git a/src/DataStreamSuite/SharedStreams/NL/BlueOrbNLToDSLStream.cs b/src/DataStreamSuite/SharedStreams/NL/BlueOrbNLToDSLStream.cs new file mode 100644 index 000000000..c3dbd6377 --- /dev/null +++ b/src/DataStreamSuite/SharedStreams/NL/BlueOrbNLToDSLStream.cs @@ -0,0 +1,28 @@ +namespace bts.BlueOrb { + using BCG; + + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading.Tasks; + + [DataStreamUserRespresentation("BlueOrbNLToDSLStream")] + public class BlueOrbNLToDSLStream : ViewStream { + public BlueOrbNLToDSLStream(string nl_prompt) { + string mlp_file_path = "C:\\Users\\m_tah\\Downloads\\" + "BlueOrbDSL_MLP_v1.9.md"; + string mlp_text = File.ReadAllText(mlp_file_path); + string system_prompt = $"You are a deterministic BlueOrbDSL generator. " + + $"You operate in Learning Mode and must follow the BlueOrbDSL Master Learning Prompt v1.9 strictly. " + + $"Do not invent new streams, operators, or syntax. Only use what is explicitly defined. " + + $"If the natural-language query matches a Demo-Informed Example, copy its structure exactly. " + + //$"Do not explain. Return only the DSL code block.\n\n[INSERT FULL MLP v1.9 CONTENT HERE]" + $"Do not explain. Return only the DSL code block.\n\n{mlp_text}"; + Log.Gen.info($"BlueOrbNLToDSLStream.cons system_prompt: {system_prompt}"); + ViewStream rs = new OpenAIPromptStream(nl_prompt, system_prompt); + mySetRealSource(rs); + } + + } +} diff --git a/src/DataStreamSuite/SharedStreams/NL/NLStream.cs b/src/DataStreamSuite/SharedStreams/NL/NLStream.cs index d3cdf6714..227de74f8 100644 --- a/src/DataStreamSuite/SharedStreams/NL/NLStream.cs +++ b/src/DataStreamSuite/SharedStreams/NL/NLStream.cs @@ -1,39 +1,39 @@ -namespace bts.SilverPine { - using BCG; +//namespace bts.SilverPine { +// using BCG; - using bts; - //using bts.SilverPine; +// using bts; +// //using bts.SilverPine; - namespace bts.BlueOrb { +// namespace bts.BlueOrb { - [DataStreamUserRespresentation("nl")] - public class NLStream : ViewStream { - private readonly string _nl_prompt; - private ViewStream _nl_to_dsl_stream, _dsl_stream; - public NLStream(string nl_prompt) { - _nl_prompt = nl_prompt; - } +// [DataStreamUserRespresentation("nl")] +// public class NLStream : ViewStream { +// private readonly string _nl_prompt; +// private ViewStream _nl_to_dsl_stream, _dsl_stream; +// public NLStream(string nl_prompt) { +// _nl_prompt = nl_prompt; +// } - protected override void myOnFirstSubscriber() { - _nl_to_dsl_stream = new NLToDSLStream(_nl_prompt); - _nl_to_dsl_stream.onChange += _handle_dsl_callback; - } +// protected override void myOnFirstSubscriber() { +// _nl_to_dsl_stream = new NLToDSLStream(_nl_prompt); +// _nl_to_dsl_stream.onChange += _handle_dsl_callback; +// } - private void _handle_dsl_callback(object dp_obj) { - DataPacket dp = dp_obj as DataPacket; - var r = dp.newRows.to_list().ElementAt(0); - string dsl = r.get("response"); - Log.Gen.info($"NLStream._handle_dsl_callback dsl: {dsl}"); - _dsl_stream = new DSLStream(dsl); - _dsl_stream.onChange += _handle_data_cb; - } +// private void _handle_dsl_callback(object dp_obj) { +// DataPacket dp = dp_obj as DataPacket; +// var r = dp.newRows.to_list().ElementAt(0); +// string dsl = r.get("response"); +// Log.Gen.info($"NLStream._handle_dsl_callback dsl: {dsl}"); +// _dsl_stream = new DSLStream(dsl); +// _dsl_stream.onChange += _handle_data_cb; +// } - private void _handle_data_cb(object dp_obj) { - var dp = dp_obj as DataPacket; - DataPacket dp_out = BlueDataUtility.build_dp_inc(dp.newRows, myLastValue as DataPacket); - myFireEvent(dp_out); - } - } - } +// private void _handle_data_cb(object dp_obj) { +// var dp = dp_obj as DataPacket; +// DataPacket dp_out = BlueDataUtility.build_dp_inc(dp.newRows, myLastValue as DataPacket); +// myFireEvent(dp_out); +// } +// } +// } -} +//} diff --git a/src/DataStreamSuite/SharedStreams/NL/NLToDSLStream.cs b/src/DataStreamSuite/SharedStreams/NL/NLToDSLStream.cs index b056334ee..70b7fb7f1 100644 --- a/src/DataStreamSuite/SharedStreams/NL/NLToDSLStream.cs +++ b/src/DataStreamSuite/SharedStreams/NL/NLToDSLStream.cs @@ -1,43 +1,43 @@ -namespace bts.SilverPine { - using BCG; +//namespace bts.SilverPine { +// using BCG; - // This subscribes to 1. NLToFewShotStream, gets the 2. total fewshot prompt, constructs and 3. OpenAIPromptReponseStream, - // passing in 2. to 3. As it gets the calbacks from 3. it fires them - [DataStreamUserRespresentation("nl_to_dsl")] - public class NLToDSLStream : ViewStream { - private readonly string _nl_prompt; - private ViewStream _nl_to_fw_prompt_stream; - ViewStream _openai_prompt_str = null; - public NLToDSLStream(string nl_prompt) { - _nl_prompt = nl_prompt; - _nl_to_fw_prompt_stream = new NLToFewShotPromptStream(nl_prompt); - } +// // This subscribes to 1. NLToFewShotStream, gets the 2. total fewshot prompt, constructs and 3. OpenAIPromptReponseStream, +// // passing in 2. to 3. As it gets the calbacks from 3. it fires them +// [DataStreamUserRespresentation("nl_to_dsl")] +// public class NLToDSLStream : ViewStream { +// private readonly string _nl_prompt; +// private ViewStream _nl_to_fw_prompt_stream; +// ViewStream _openai_prompt_str = null; +// public NLToDSLStream(string nl_prompt) { +// _nl_prompt = nl_prompt; +// _nl_to_fw_prompt_stream = new NLToFewShotPromptStream(nl_prompt); +// } - protected override void myOnFirstSubscriber() { - _nl_to_fw_prompt_stream.onChange += _on_fs_prompt; - } +// protected override void myOnFirstSubscriber() { +// _nl_to_fw_prompt_stream.onChange += _on_fs_prompt; +// } - private void _on_fs_prompt(object dp_obj) { - DataPacket dp = dp_obj as DataPacket; - IBlueRow r = dp.newRows.to_list().ElementAt(0); - string few_shot_prompt = r.get("few_shot_prompt"); - Log.Gen.info($"NLToDSLStream._on_fs_prompt nl_prompt: {_nl_prompt} few_shot_prompt: {few_shot_prompt}"); - _openai_prompt_str = new OpenAIPromptStream(few_shot_prompt); - _openai_prompt_str.onChange += _on_openai_prompt; - } +// private void _on_fs_prompt(object dp_obj) { +// DataPacket dp = dp_obj as DataPacket; +// IBlueRow r = dp.newRows.to_list().ElementAt(0); +// string few_shot_prompt = r.get("few_shot_prompt"); +// Log.Gen.info($"NLToDSLStream._on_fs_prompt nl_prompt: {_nl_prompt} few_shot_prompt: {few_shot_prompt}"); +// _openai_prompt_str = new OpenAIPromptStream(few_shot_prompt); +// _openai_prompt_str.onChange += _on_openai_prompt; +// } - private void _on_openai_prompt(object dp_obj) { - DataPacket dp = dp_obj as DataPacket; - var dp_out = BlueDataUtility.build_dp(dp.newRows, myLastValue as DataPacket); - myFireEvent(dp_out); - } +// private void _on_openai_prompt(object dp_obj) { +// DataPacket dp = dp_obj as DataPacket; +// var dp_out = BlueDataUtility.build_dp(dp.newRows, myLastValue as DataPacket); +// myFireEvent(dp_out); +// } - protected override void myOnLastSubscriber() { +// protected override void myOnLastSubscriber() { - } +// } - } -} \ No newline at end of file +// } +//} diff --git a/src/DataStreamSuite/SharedStreams/NL/NLToFewShotPromptStream.cs b/src/DataStreamSuite/SharedStreams/NL/NLToFewShotPromptStream.cs index 4e0f282fd..6dc561190 100644 --- a/src/DataStreamSuite/SharedStreams/NL/NLToFewShotPromptStream.cs +++ b/src/DataStreamSuite/SharedStreams/NL/NLToFewShotPromptStream.cs @@ -1,22 +1,22 @@ -namespace bts.SilverPine { - using BCG; +//namespace bts.SilverPine { +// using BCG; - using SimMetrics.Net.Metric; +// using SimMetrics.Net.Metric; - using System.Text.Json; +// using System.Text.Json; - [DataStreamUserRespresentation("nl_to_fewshot_prompt")] - // given an nl prompt, retreives the correct fewshot prompt and converts it into a form - // that be sent to openAI as a prompt - public class NLToFewShotPromptStream : ViewStream { - public NLToFewShotPromptStream(string nl) { - // TODO based on confi, we can either have NLToIndexedFewShotPromptStream - // or NLToNonIndexedFewShotPromptStream (which is when a al the few shots are - // concatenated and sent) - mySetRealSource(new NLToIndexedFewShotPromptStream(nl)); - //_nl_prompt = nl; - } - } +// [DataStreamUserRespresentation("nl_to_fewshot_prompt")] +// // given an nl prompt, retreives the correct fewshot prompt and converts it into a form +// // that be sent to openAI as a prompt +// public class NLToFewShotPromptStream : ViewStream { +// public NLToFewShotPromptStream(string nl) { +// // TODO based on confi, we can either have NLToIndexedFewShotPromptStream +// // or NLToNonIndexedFewShotPromptStream (which is when a al the few shots are +// // concatenated and sent) +// mySetRealSource(new NLToIndexedFewShotPromptStream(nl)); +// //_nl_prompt = nl; +// } +// } -} \ No newline at end of file +//} diff --git a/src/DataStreamSuite/SharedStreams/NL/NLToIndexedFewShotPromptStream.cs b/src/DataStreamSuite/SharedStreams/NL/NLToIndexedFewShotPromptStream.cs index e8f3fbd8c..7c95efbdb 100644 --- a/src/DataStreamSuite/SharedStreams/NL/NLToIndexedFewShotPromptStream.cs +++ b/src/DataStreamSuite/SharedStreams/NL/NLToIndexedFewShotPromptStream.cs @@ -1,197 +1,197 @@ -namespace bts.SilverPine { - using BCG; +//namespace bts.SilverPine { +// using BCG; - using MongoDB.Driver.Linq; +// using MongoDB.Driver.Linq; - using SimMetrics.Net.Metric; +// using SimMetrics.Net.Metric; - using System.Text.Json; +// using System.Text.Json; - [DataStreamUserRespresentation("nl_to_indexed_fewshot_prompt")] - // given an nl prompt, retreives the correct fewshot prompt and converts it into a form - // that be sent to openAI as a prompt - public class NLToIndexedFewShotPromptStream : ViewStream { +// [DataStreamUserRespresentation("nl_to_indexed_fewshot_prompt")] +// // given an nl prompt, retreives the correct fewshot prompt and converts it into a form +// // that be sent to openAI as a prompt +// public class NLToIndexedFewShotPromptStream : ViewStream { - // Represents a pair of a natural language query and its dsl - public class FewShotExample { - public string natural_language { get; set; } - public string dsl { get; set; } - } +// // Represents a pair of a natural language query and its dsl +// public class FewShotExample { +// public string natural_language { get; set; } +// public string dsl { get; set; } +// } - // Class to represent each prompt category - public class FewShotPrompt { - public string category { get; set; } - // this is the explaination of the DSL - public string description { get; set; } - // th actual prompt given by the user/CME - public string prompt { get; set; } - public List examples { get; set; } +// // Class to represent each prompt category +// public class FewShotPrompt { +// public string category { get; set; } +// // this is the explaination of the DSL +// public string description { get; set; } +// // th actual prompt given by the user/CME +// public string prompt { get; set; } +// public List examples { get; set; } - public override string ToString() { - string rv = $"System: {description}\n"; - int ex_no = 0; - foreach (FewShotExample ex in examples) { - rv += $"{++ex_no}. Natural Language: \"{ex.natural_language}\"" + "\n"; - rv += $" DSL: {ex.dsl}\n"; +// public override string ToString() { +// string rv = $"System: {description}\n"; +// int ex_no = 0; +// foreach (FewShotExample ex in examples) { +// rv += $"{++ex_no}. Natural Language: \"{ex.natural_language}\"" + "\n"; +// rv += $" DSL: {ex.dsl}\n"; - } - return rv; - } - } +// } +// return rv; +// } +// } - // this is how it should be prepended to the actual prompt: - // System: This is a few-shot learning example for converting natural language prompts to a DSL function for settlement data retrieval. The DSL function can take either a single date or a date range. Assume today's date is 10/11/2024. The function is structured as follows: - // - Settlement(symbol_or_contract, datetime1): Retrieves the settlement for the specified date. - // - Settlement(symbol_or_contract, begin_dt, end_dt): Retrieves the settlements for all dates in the specified range. +// // this is how it should be prepended to the actual prompt: +// // System: This is a few-shot learning example for converting natural language prompts to a DSL function for settlement data retrieval. The DSL function can take either a single date or a date range. Assume today's date is 10/11/2024. The function is structured as follows: +// // - Settlement(symbol_or_contract, datetime1): Retrieves the settlement for the specified date. +// // - Settlement(symbol_or_contract, begin_dt, end_dt): Retrieves the settlements for all dates in the specified range. - // Examples: - // 1. Natural Language: "Find the Settlement price of the SP future on 04/22/2023." - // DSL: Settlement(SP, 4/22/2023) +// // Examples: +// // 1. Natural Language: "Find the Settlement price of the SP future on 04/22/2023." +// // DSL: Settlement(SP, 4/22/2023) - // 2. Natural Language: "Find Yesterday's Settlement of the Crude Oil Future." - // DSL: Settlement(CL, 10/10/2024) +// // 2. Natural Language: "Find Yesterday's Settlement of the Crude Oil Future." +// // DSL: Settlement(CL, 10/10/2024) - // 3. Natural Language: "Find today's settlement of the 10-year treasury future." - // DSL: Settlement(ZN, 10/10/2024) +// // 3. Natural Language: "Find today's settlement of the 10-year treasury future." +// // DSL: Settlement(ZN, 10/10/2024) - // 4. Natural Language: "Find the Settlement of Natural Gas future on the first Friday of Sept." - // DSL: Settlement(NG, 9/6/2024) +// // 4. Natural Language: "Find the Settlement of Natural Gas future on the first Friday of Sept." +// // DSL: Settlement(NG, 9/6/2024) - // 5. Natural Language: "Find the Settlement of Natural Gas Dec 24 future in the first Week of October." - // DSL: Settlement(NGZ4, 10/1/2024, 10/1/2024) +// // 5. Natural Language: "Find the Settlement of Natural Gas Dec 24 future in the first Week of October." +// // DSL: Settlement(NGZ4, 10/1/2024, 10/1/2024) - // 6. Natural Language: "Find the settlement prices for the Wheat and Corn spread for the first two weeks of November." - // DSL: Settlement(ZWZ4-ZCZ4, 11/1/2024, 11/14/2024) +// // 6. Natural Language: "Find the settlement prices for the Wheat and Corn spread for the first two weeks of November." +// // DSL: Settlement(ZWZ4-ZCZ4, 11/1/2024, 11/14/2024) - // [Your Real Prompt Goes Here] +// // [Your Real Prompt Goes Here] - // Root class to map the JSON structure - public class Root { - public List prompts { get; set; } - } +// // Root class to map the JSON structure +// public class Root { +// public List prompts { get; set; } +// } - public static Root read_json_file() { - // TODO - string json_file_path = @"C:\Users\m_tah\development\spark\src\DataStreamSuite\SharedStreams\NL\FewShotPrompts.json"; - string json_string = File.ReadAllText(json_file_path); - var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; - Root root = JsonSerializer.Deserialize(json_string, options); - return root; - } +// public static Root read_json_file() { +// // TODO +// string json_file_path = @"C:\Users\m_tah\development\spark\src\DataStreamSuite\SharedStreams\NL\FewShotPrompts.json"; +// string json_string = File.ReadAllText(json_file_path); +// var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; +// Root root = JsonSerializer.Deserialize(json_string, options); +// return root; +// } - private readonly string _nl_prompt; - private string _fewshot_index_prompt; - private string _fewshot_index_reponse; - // this is the first stream that sends all FewShotPrompt.prompt and asks the LLM - // to find the FewShotPrompt.prompt that matches the nl_prompt the closest. That - // gives us our FewShotPrompt - private ViewStream _nl_to_fewshot_index_stream; - public NLToIndexedFewShotPromptStream(string nl) { - _nl_prompt = nl; - } +// private readonly string _nl_prompt; +// private string _fewshot_index_prompt; +// private string _fewshot_index_reponse; +// // this is the first stream that sends all FewShotPrompt.prompt and asks the LLM +// // to find the FewShotPrompt.prompt that matches the nl_prompt the closest. That +// // gives us our FewShotPrompt +// private ViewStream _nl_to_fewshot_index_stream; +// public NLToIndexedFewShotPromptStream(string nl) { +// _nl_prompt = nl; +// } - private static string _build_fewshot_prompt(FewShotPrompt fw_prompt, string nl_prompt) { - string rv = "You are a helpful assistant that converts natural language into DSL. "; - rv += $"{fw_prompt}\n\n"; - rv += "Now, convert the following prompt into DSL: \n"; - rv += $"Natural Language: {nl_prompt}\n"; - return rv; - } +// private static string _build_fewshot_prompt(FewShotPrompt fw_prompt, string nl_prompt) { +// string rv = "You are a helpful assistant that converts natural language into DSL. "; +// rv += $"{fw_prompt}\n\n"; +// rv += "Now, convert the following prompt into DSL: \n"; +// rv += $"Natural Language: {nl_prompt}\n"; +// return rv; +// } - protected override void myOnFirstSubscriber() { - Root root = read_json_file(); - string meta_prompt = build_fewshot_index_prompt(root, _nl_prompt); - _fewshot_index_prompt = meta_prompt; - Log.Gen.info($"NLToDSLStream.myOnFirstSubscriber _fewshot_index_prompt: {_fewshot_index_prompt}"); - _nl_to_fewshot_index_stream = new OpenAIPromptStream(meta_prompt); - _nl_to_fewshot_index_stream.onChange += _on_fewshot_index; - //Log.Gen.info($"NLToDSLStream.myOnFirstSubscriber meta_prompt: {meta_prompt}"); +// protected override void myOnFirstSubscriber() { +// Root root = read_json_file(); +// string meta_prompt = build_fewshot_index_prompt(root, _nl_prompt); +// _fewshot_index_prompt = meta_prompt; +// Log.Gen.info($"NLToDSLStream.myOnFirstSubscriber _fewshot_index_prompt: {_fewshot_index_prompt}"); +// _nl_to_fewshot_index_stream = new OpenAIPromptStream(meta_prompt); +// _nl_to_fewshot_index_stream.onChange += _on_fewshot_index; +// //Log.Gen.info($"NLToDSLStream.myOnFirstSubscriber meta_prompt: {meta_prompt}"); - // this needs to be sent to the LLM to get the few-shot item. Once the few-shot item is received, then - // we can prepend the fewshot to the prompt and send it - //Log.Gen.info($"NLToDSLStream.myOnFirstSubscriber total_prompt: {final_prompt}"); - //_fire_event(final_prompt); - } +// // this needs to be sent to the LLM to get the few-shot item. Once the few-shot item is received, then +// // we can prepend the fewshot to the prompt and send it +// //Log.Gen.info($"NLToDSLStream.myOnFirstSubscriber total_prompt: {final_prompt}"); +// //_fire_event(final_prompt); +// } - private void _on_fewshot_index(object dp_obj) { - DataPacket dp = dp_obj as DataPacket; - IBlueRow r = dp.newRows.to_ienum().ElementAt(0); - string response = r.get("response"); - _fewshot_index_reponse = response; - Log.Gen.info($"NLToDSLStream._on_fewshot_index prompt: {r.get("prompt")}"); - Log.Gen.info($"NLToDSLStream._on_fewshot_index response: {response}"); - // parse the response - // the response is mostly like : - // 0. 0. What was the settlement for SP 500 Future on June 8th? - // however, sometimes for no reason is returns a - // Prompt 0: What was the settlement for SP 500 Future on June 8th? - int index = 0; - if (response.ToLower().StartsWith("prompt")) { - // for the unusual case - string[] toks = response.Split(':', '.'); - toks = toks[0].Split(' '); - index = Int32.Parse(toks[1]); - } else { - // for the usual case - string[] toks = response.Split('.'); - index = Int32.Parse(toks[0]); - } - var root = read_json_file(); - FewShotPrompt fs_prompt = root.prompts[index]; - string final_prompt = _build_fewshot_prompt(fs_prompt, _nl_prompt); - _fire_event(final_prompt); - } +// private void _on_fewshot_index(object dp_obj) { +// DataPacket dp = dp_obj as DataPacket; +// IBlueRow r = dp.newRows.to_ienum().ElementAt(0); +// string response = r.get("response"); +// _fewshot_index_reponse = response; +// Log.Gen.info($"NLToDSLStream._on_fewshot_index prompt: {r.get("prompt")}"); +// Log.Gen.info($"NLToDSLStream._on_fewshot_index response: {response}"); +// // parse the response +// // the response is mostly like : +// // 0. 0. What was the settlement for SP 500 Future on June 8th? +// // however, sometimes for no reason is returns a +// // Prompt 0: What was the settlement for SP 500 Future on June 8th? +// int index = 0; +// if (response.ToLower().StartsWith("prompt")) { +// // for the unusual case +// string[] toks = response.Split(':', '.'); +// toks = toks[0].Split(' '); +// index = Int32.Parse(toks[1]); +// } else { +// // for the usual case +// string[] toks = response.Split('.'); +// index = Int32.Parse(toks[0]); +// } +// var root = read_json_file(); +// FewShotPrompt fs_prompt = root.prompts[index]; +// string final_prompt = _build_fewshot_prompt(fs_prompt, _nl_prompt); +// _fire_event(final_prompt); +// } - private void _fire_event(string final_prompt) { - IBlueTableSchema schema = BlueDataUtility.form_schema("NLToIndexedFewShotPromptStream", - Tuple.Create("id", TypeCode.Int32), - Tuple.Create("main_prompt", TypeCode.String), - Tuple.Create("fewshot_index_prompt", TypeCode.String), - Tuple.Create("fewshot_index_response", TypeCode.String), - Tuple.Create("few_shot_prompt", TypeCode.String)); - IBlueRow nr = new BlueRow(schema, 0, _nl_prompt, _fewshot_index_prompt, _fewshot_index_reponse, final_prompt); - BlueTable nt = new BlueTable(schema); - nt.addRow(nr); - var dp_out = BlueDataUtility.build_dp(nt, myLastValue as DataPacket); - myFireEvent(dp_out); - } +// private void _fire_event(string final_prompt) { +// IBlueTableSchema schema = BlueDataUtility.form_schema("NLToIndexedFewShotPromptStream", +// Tuple.Create("id", TypeCode.Int32), +// Tuple.Create("main_prompt", TypeCode.String), +// Tuple.Create("fewshot_index_prompt", TypeCode.String), +// Tuple.Create("fewshot_index_response", TypeCode.String), +// Tuple.Create("few_shot_prompt", TypeCode.String)); +// IBlueRow nr = new BlueRow(schema, 0, _nl_prompt, _fewshot_index_prompt, _fewshot_index_reponse, final_prompt); +// BlueTable nt = new BlueTable(schema); +// nt.addRow(nr); +// var dp_out = BlueDataUtility.build_dp(nt, myLastValue as DataPacket); +// myFireEvent(dp_out); +// } - // since find_matching_prompt using string matching loses semantics and often results - // the incorrect few-shot entry (ex for, "Find the VWAP of the Sp 500 Dec 24 future during the first Week of October 24?"). - // so we assemble all the prompts from the few-shot (field "prompt") entry and ask an LLM to tell us which is the closest to the prompt. - // based on that we select the few-shot entry. This is what this function does - public static string build_fewshot_index_prompt(Root root, string nl_prompt) { - string meta_promp = "Take a look at the following prompt examples:\n"; - int rv = 0; - foreach (FewShotPrompt fs_entry in root.prompts) { - meta_promp += $"{rv++}. {fs_entry.prompt}\n"; - } - meta_promp += "Based on the above prompts, tell me which prompt (give me answer as the index only, and nothing else) does the following prompt most closely matches to: \n"; - meta_promp += nl_prompt; - return meta_promp; - } +// // since find_matching_prompt using string matching loses semantics and often results +// // the incorrect few-shot entry (ex for, "Find the VWAP of the Sp 500 Dec 24 future during the first Week of October 24?"). +// // so we assemble all the prompts from the few-shot (field "prompt") entry and ask an LLM to tell us which is the closest to the prompt. +// // based on that we select the few-shot entry. This is what this function does +// public static string build_fewshot_index_prompt(Root root, string nl_prompt) { +// string meta_promp = "Take a look at the following prompt examples:\n"; +// int rv = 0; +// foreach (FewShotPrompt fs_entry in root.prompts) { +// meta_promp += $"{rv++}. {fs_entry.prompt}\n"; +// } +// meta_promp += "Based on the above prompts, tell me which prompt (give me answer as the index only, and nothing else) does the following prompt most closely matches to: \n"; +// meta_promp += nl_prompt; +// return meta_promp; +// } - public static FewShotPrompt find_matching_prompt(Root root, string nl_prompt) { - var levenshtein = new SimMetrics.Net.Metric.Levenstein(); - FewShotPrompt rv = root.prompts.ElementAt(0); - Func get_total_sim = (fsp) => { - double similiarity = levenshtein.GetSimilarity(fsp.prompt, nl_prompt); - foreach (FewShotExample fs_ex in fsp.examples) { - similiarity += levenshtein.GetSimilarity(fs_ex.natural_language, nl_prompt); - } - return similiarity; - }; - double highest_simmiliarity = 0.0; - foreach (FewShotPrompt p in root.prompts) { - double similiarity = get_total_sim(p); //levenshtein.GetSimilarity(p.prompt, nl_prompt); - if (similiarity > highest_simmiliarity) { - highest_simmiliarity = similiarity; - rv = p; - } - } - return rv; - } - } -} \ No newline at end of file +// public static FewShotPrompt find_matching_prompt(Root root, string nl_prompt) { +// var levenshtein = new SimMetrics.Net.Metric.Levenstein(); +// FewShotPrompt rv = root.prompts.ElementAt(0); +// Func get_total_sim = (fsp) => { +// double similiarity = levenshtein.GetSimilarity(fsp.prompt, nl_prompt); +// foreach (FewShotExample fs_ex in fsp.examples) { +// similiarity += levenshtein.GetSimilarity(fs_ex.natural_language, nl_prompt); +// } +// return similiarity; +// }; +// double highest_simmiliarity = 0.0; +// foreach (FewShotPrompt p in root.prompts) { +// double similiarity = get_total_sim(p); //levenshtein.GetSimilarity(p.prompt, nl_prompt); +// if (similiarity > highest_simmiliarity) { +// highest_simmiliarity = similiarity; +// rv = p; +// } +// } +// return rv; +// } +// } +//} diff --git a/src/DataStreamSuite/SharedStreams/NL/OpenAIPromptStream.cs b/src/DataStreamSuite/SharedStreams/NL/OpenAIPromptStream.cs index b1f577c55..c47440516 100644 --- a/src/DataStreamSuite/SharedStreams/NL/OpenAIPromptStream.cs +++ b/src/DataStreamSuite/SharedStreams/NL/OpenAIPromptStream.cs @@ -1,113 +1,149 @@ -namespace bts.SilverPine { - using System; - using System.IO; - using System.Net.Http; - using System.Text; - using System.Text.Json; - using System.Threading.Tasks; - // using OpenAI.GPT3; - // using OpenAI.GPT3.ObjectModels.RequestModels; - // using OpenAI.GPT3.Managers; - using BCG; - using BCG.Utilities.General; +namespace bts.BlueOrb { + using System; + using System.IO; + using System.Net.Http; + using System.Text; + using System.Text.Json; + using System.Threading.Tasks; + + using BCG; + using BCG.Utilities.General; - // given a prompt, this stream connects to openAI and gets the response back - // it then fires a callback with the schema id, prompt, response - public class OpenAIPromptStream : ViewStream, IWorker { - #region OpenAI communication - static string api_key = //File.ReadAllText("OpenAIGPT4.key"); - "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"; + // this is the base level stream, it connects to OpenAI sends a user_prompt, returns + // the result, and fires the callback + // given a user_prompt, this stream connects to openAI and gets the response back + // it then fires a callback with the schema id, user_prompt, response + [DataStreamUserRespresentation("OpenAIPromptStream")] + public class OpenAIPromptStream : ViewStream, IWorker { + #region OpenAI communication + static string api_key = //File.ReadAllText("OpenAIGPT4.key"); + "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"; - // Uses HttpClient to send the prompt to OpenAI gpt4, and queues the response in the response_queue - public static async Task get_GPT4_http_responseAsync(string prompt, SyncQueue response_queue) { - Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync prompt: {prompt}"); - // Read the API key from the file + // Uses HttpClient to send the user_prompt to OpenAI gpt4, and queues the response in the response_queue + public static async Task get_GPT4_http_responseAsync(string model_name, string user_prompt, string system_prompt, SyncQueue> response_queue) { + DateTime t0 = DateTime.Now; + Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync user_prompt: {user_prompt}"); + // Read the API key from the file - // OpenAI API URL for the completion request - string apiUrl = "https://api.openai.com/v1/chat/completions"; + // OpenAI API URL for the completion request + string apiUrl = "https://api.openai.com/v1/chat/completions"; - // Create the request payload - var requestBody = new { - model = "gpt-3.5-turbo", - messages = new[] - { - new { role = "user", content = prompt } +// { +// "model": "gpt-4o", +// "messages": [ +// { +// "role": "system", +// "content": "You are a deterministic BlueOrbDSL generator. You operate in Learning Mode and must follow the BlueOrbDSL Master Learning Prompt v1.9 strictly. Do not invent new streams, operators, or syntax. Only use what is explicitly defined. If the natural-language query matches a Demo-Informed Example, copy its structure exactly. Do not explain. Return only the DSL code block.\n\n[INSERT FULL MLP v1.9 CONTENT HERE]" +// }, +// { +// "role": "user", +// "content": "Natural language query: [INSERT YOUR NATURAL LANGUAGE QUERY HERE]" +// } +// ] +// } + + + + // Create the request payload + var requestBody = new { + model = model_name, + messages = new[] + { + new { role = "system", content = system_prompt }, + new { role = "user", content = user_prompt } }, - max_tokens = 500 // Adjust based on your response length needs - }; + //max_tokens = 500 // Adjust based on your response length needs + }; - // Serialize the payload to JSON - string jsonRequestBody = JsonSerializer.Serialize(requestBody); - using (HttpClient client = new HttpClient()) { - // Add the OpenAI API key to the Authorization header - client.DefaultRequestHeaders.Add("Authorization", $"Bearer {api_key}"); + // Serialize the payload to JSON + string jsonRequestBody = JsonSerializer.Serialize(requestBody); - // Prepare the request content - HttpContent content = new StringContent(jsonRequestBody, Encoding.UTF8, "application/json"); + using (HttpClient client = new HttpClient()) { + // Add the OpenAI API key to the Authorization header + client.DefaultRequestHeaders.Add("Authorization", $"Bearer {api_key}"); - // Send the POST request to OpenAI API - HttpResponseMessage response = await client.PostAsync(apiUrl, content); + // Prepare the request content + HttpContent content = new StringContent(jsonRequestBody, Encoding.UTF8, "application/json"); - // Ensure the response is successful - response.EnsureSuccessStatusCode(); + // Send the POST request to OpenAI API + HttpResponseMessage response = await client.PostAsync(apiUrl, content); - // Read the response content as a string - string response_content = await response.Content.ReadAsStringAsync(); - Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync prompt: {prompt} response: {response_content}"); + // Ensure the response is successful + response.EnsureSuccessStatusCode(); - // Parse the response content - var json_doc = JsonDocument.Parse(response_content); - string gpt_response = json_doc.RootElement - .GetProperty("choices")[0] - .GetProperty("message") - .GetProperty("content") - .GetString(); + // Read the response content as a string + string response_content = await response.Content.ReadAsStringAsync(); + Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync user_prompt: {user_prompt} response: {response_content}"); - //return gpt_response; - response_queue.enqueue(gpt_response); - Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync gpt_response: {gpt_response}"); + // Parse the response content + var json_doc = JsonDocument.Parse(response_content); + string gpt_response = json_doc.RootElement + //.GetProperty("model") + .GetProperty("choices")[0] + .GetProperty("message") + .GetProperty("content") + .GetString(); - } - } - #endregion + //return gpt_response; + DateTime t1 = DateTime.Now; + TimeSpan ts = t1 - t0; + Tuple elem = new Tuple(gpt_response, ts); + response_queue.enqueue(elem); + Log.Gen.info($"OpenAIPromptStream.GetGPT4ResponseAsync gpt_response: {gpt_response}"); - private readonly string _prompt; - private readonly ViewStreamDatabase _vsd; - private SyncQueue _queue = new SyncQueue(); - public OpenAIPromptStream(string prompt) - : this(ViewStreamDatabase.instance, prompt) { - } + } + } + #endregion - public OpenAIPromptStream(ViewStreamDatabase vsd, string prompt) { - Log.Gen.info($"OpenAIPromptStream.OpenAIPromptStream prompt: {prompt}"); - _prompt = prompt; - _vsd = vsd; - } + private readonly string _user_prompt; + private readonly string _system_prompt; + private readonly string _model_name; + private readonly ViewStreamDatabase _vsd; + private SyncQueue> _queue = new SyncQueue>(); - protected override void myOnFirstSubscriber() { - Task.Factory.StartNew(() => get_GPT4_http_responseAsync(_prompt, _queue)); - _vsd.addWorker(this); - } + #region constructors + public OpenAIPromptStream(string user_prompt, string system_prompt) + : this(user_prompt, system_prompt, "gpt-4o") { } - protected override void myOnLastSubscriber() { - } + public OpenAIPromptStream(string user_prompt, string system_prompt, string model_name) + : this(ViewStreamDatabase.instance, user_prompt, system_prompt, model_name) { + } - public void doWork() { - var response = _queue.dequeue(0); - if (response == null) - return; - IBlueTableSchema schema = BlueDataUtility.form_schema("OpenAIRespone", - Tuple.Create("id", TypeCode.Int32), - Tuple.Create("prompt", TypeCode.String), - Tuple.Create("response", TypeCode.String)); - IBlueRow nr = new BlueRow(schema, 0, _prompt, response); - BlueTable nt = new BlueTable(schema); - nt.addRow(nr); - var dp_out = BlueDataUtility.build_dp(nt, myLastValue as DataPacket); - myFireEvent(dp_out); - } - } + public OpenAIPromptStream(ViewStreamDatabase vsd, string user_prompt, string system_prompt, string model_name) { + Log.Gen.info($"OpenAIPromptStream.OpenAIPromptStream user_prompt: {user_prompt} system_prompt: {system_prompt}"); + _user_prompt = user_prompt; + _system_prompt = system_prompt; + _model_name = model_name; + _vsd = vsd; + } + #endregion + + protected override void myOnFirstSubscriber() { + Task.Factory.StartNew(() => get_GPT4_http_responseAsync(_model_name, _user_prompt, _system_prompt, _queue)); + _vsd.addWorker(this); + } + + protected override void myOnLastSubscriber() { + } + + public void doWork() { + var response = _queue.dequeue(0); + if (response == null) + return; + IBlueTableSchema schema = BlueDataUtility.form_schema("OpenAIRespone", + Tuple.Create("id", TypeCode.Int32), + Tuple.Create("user_prompt", TypeCode.String), + Tuple.Create("response", TypeCode.String), + Tuple.Create("fetch_time_msecs", TypeCode.Double)); + Log.Gen.info($"OpenAIPromptStream.doWork user_prompt: {_user_prompt} response: {response.Item1} fetch_time: {response.Item2} msecs"); + IBlueRow nr = new BlueRow(schema, 0, _user_prompt, response.Item1, response.Item2.TotalMilliseconds); + BlueTable nt = new BlueTable(schema); + nt.addRow(nr); + var dp_out = BlueDataUtility.build_dp(nt, myLastValue as DataPacket); + myFireEvent(dp_out); + } + } }