From e000b1d0c06d2a130f57e60dbe93567121c76527 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Tue, 26 Nov 2019 00:07:36 -0500 Subject: [PATCH 01/10] hmm --- .vscode/launch.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index fb5ac11c7..aae19ddb9 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -105,8 +105,8 @@ "program": "${workspaceRoot}/build/Debug/bin/net471/sparkcmd.exe", "args": [ "historical", - "--rskip", "11/20/2019 10:00AM", - "--rstart", "11/20/2019 02:00PM", + "--rskip", "11/20/2019 6:00AM", + "--rstart", "11/20/2019 08:00AM", "--rend", "11/20/2019 11:00PM", "--rsymbol", "CL", "--rsecuritytype", "Spread", From 12e3e9a222f97498f78461d265f90ae6e4722d10 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 27 Nov 2019 15:08:51 -0500 Subject: [PATCH 02/10] gave up and decided to run postgres in docker on my host --- docker/linux | 2 +- tools/start_postgres.sh | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docker/linux b/docker/linux index 9d93e9352..e106e6e70 160000 --- a/docker/linux +++ b/docker/linux @@ -1 +1 @@ -Subproject commit 9d93e93525869620b0e051bf7c0021f667d2fc45 +Subproject commit e106e6e7044b147a3bc97d456a46938de8f386d7 diff --git a/tools/start_postgres.sh b/tools/start_postgres.sh index 0dc5ba609..44f56b18a 100644 --- a/tools/start_postgres.sh +++ b/tools/start_postgres.sh @@ -1,3 +1,3 @@ #!/bin/bash -su postgres -c '/usr/lib/postgresql/10/bin/pg_ctl start -D /home/bts/sparkdata/data/pgdata/ -l serverlog' \ No newline at end of file +docker run --net host -d --name pg postgres:12 \ No newline at end of file From 8b9d689a5fdbe305fa7b44c898588be47ce83b7e Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 27 Nov 2019 16:18:56 -0500 Subject: [PATCH 03/10] able to preprocess trades and books into a postgres --- .vscode/launch.json | 11 ++-- .../Cmd/Historical/Analyzers/BookAnalyzer.cs | 3 +- .../Historical/HistoricalDatabaseGenerator.cs | 56 ++++++++++++++----- .../sparkcmd/Cmd/HistoricalDataCommand.cs | 2 +- tools/simple_config.sh | 3 + 5 files changed, 53 insertions(+), 22 deletions(-) create mode 100644 tools/simple_config.sh diff --git a/.vscode/launch.json b/.vscode/launch.json index fb5ac11c7..0dac8ebdd 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -369,14 +369,11 @@ "program": "sparkcmd", "args": [ "historical", - "--rstart", "10/21/2019", - "--rend", "10/21/2019", + "--rstart", "11/20/2019", + "--rend", "11/20/2019", "--rsymbol", "CL", - "--rsecuritytype", "Future", - "--algo_security", "CLX9", - "--algo_type", "TWAP", - "--algo_params", "size=100;profit_ticks=1;tick_size=1,1,1;hedge_factors=1,1,-1", - "--skip_preanalysis", "true", + "--rsecuritytype", "Spread", + "--post_process_db", "cl_history", ], "env": {"LD_LIBRARY_PATH" : "."}, "stopAtEntry": false, diff --git a/src/client/sparkcmd/Cmd/Historical/Analyzers/BookAnalyzer.cs b/src/client/sparkcmd/Cmd/Historical/Analyzers/BookAnalyzer.cs index 182e22ae6..c4e8341a5 100644 --- a/src/client/sparkcmd/Cmd/Historical/Analyzers/BookAnalyzer.cs +++ b/src/client/sparkcmd/Cmd/Historical/Analyzers/BookAnalyzer.cs @@ -52,7 +52,8 @@ namespace bts.history _books[entry.Symbol] = book; } OrderBook.keep_book(book, entry); - on_new_book(book, entry, md); + if (OrderBook.quote_event_done(md)) + on_new_book(book, entry, md); } // else if (entry.MdEntryType == MDEntryType.Trade) // handle trades here diff --git a/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs b/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs index 5e80f0af4..af5952921 100644 --- a/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs +++ b/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Threading.Tasks; using bts.api; using bts.co2; @@ -23,13 +24,21 @@ namespace bts.history var conn = $@"Server={_post_process_db_ip};Port=5432; User Id=postgres;Password=enter;"; _sql = new Npgsql.NpgsqlConnection(conn); var create = new Npgsql.NpgsqlCommand( - $@"create database if not exists {_post_process_db} + $@"CREATE DATABASE {_post_process_db} with owner = postgres encoding = 'UTF8' connection limit = -1; ", _sql); _sql.Open(); - create.ExecuteNonQuery(); + try + { + create.ExecuteNonQuery(); + } + catch(Exception ex) + { + if(!ex.Message.Contains("already exists")) + throw ex; + } _sql.Close(); //TODO google says I have to do this _sql = null; } @@ -54,10 +63,15 @@ namespace bts.history if (DateTime.TryParse(o.replayskip, out DateTime skip) && skip != DateTime.MinValue) query.Skip = Timestamp.FromDateTime(skip.ToUniversalTime()); + int count = 0; var comparer = Comparer.Create((x, y) => x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime())); await _stream.process_md_stream(query, (sectype, md, line) => { + if(count++ % 50000 == 1) + Console.WriteLine($"preprocessed {count} lines"); + if(md.timestamp().ToDateTime() > end) + throw new System.IO.EndOfStreamException(); foreach (var entry in md.MdEntries) { if (entry.MdEntryType == MDEntryType.Bid || entry.MdEntryType == MDEntryType.Offer) @@ -84,7 +98,7 @@ namespace bts.history { var conn = $@"Server={_post_process_db_ip};Port=5432; User Id=postgres;Password=enter;Database={_post_process_db}"; _sql = new Npgsql.NpgsqlConnection(conn); - var name = $"{symbol}_history"; + var name = $"{symbol}_{st.ToString()}_history"; var cmd = new Npgsql.NpgsqlCommand( $@"CREATE TABLE IF NOT EXISTS {name} (id serial NOT NULL PRIMARY KEY, seqnum INTEGER NOT NULL CHECK(seqnum > 0), transact_time TIMESTAMPTZ NOT NULL, sending_time TIMESTAMPTZ NOT NULL, @@ -98,22 +112,38 @@ namespace bts.history private void write_trade(string tname, TradeMessage tm, MDEntry entry, MarketDataIncrementalRefresh md) { var json = Google.Protobuf.JsonFormatter.Default.Format(tm); - var cmd = new Npgsql.NpgsqlCommand( - $@"INSERT INTO {tname} (transact_time, sending_time, symbol, security_type, security_desc, data_type, data ) - VALUES ({md.MsgSeqNum}, {md.TransactTime.ToString()}, {md.SendingTime.ToString()}, - {entry.security_desc()}, {nameof(TradeMessage)}, { json } ) - ", _sql); - cmd.ExecuteNonQuery(); + var cmd = new Npgsql.NpgsqlCommand( + $"INSERT INTO {tname} (seqnum, transact_time, sending_time, security_desc, data_type, data ) " + + $"VALUES ({md.MsgSeqNum}, '{md.TransactTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{md.SendingTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{entry.security_desc()}', '{nameof(TradeMessage)}', '{ json }' ) ", + _sql); + try + { + cmd.ExecuteNonQuery(); + } + catch (Exception ex) + { + throw ex; + } } private void write_book(string tname, BookMessage book, MDEntry entry, MarketDataIncrementalRefresh md) { + if(!book.Bids.Any( x=>x.Size > 0) && !book.Asks.Any(x => x.Size > 0)) + return; + var json = Google.Protobuf.JsonFormatter.Default.Format(book); var cmd = new Npgsql.NpgsqlCommand( - $@"INSERT INTO {tname} (transact_time, sending_time, symbol, security_type, security_desc, data_type, data ) - VALUES ({md.MsgSeqNum}, {md.TransactTime.ToString()}, {md.SendingTime.ToString()}, - {entry.security_desc()}, {nameof(BookMessage)}, { json } ) - ", _sql); + $"INSERT INTO {tname} (seqnum, transact_time, sending_time, security_desc, data_type, data ) " + + $"VALUES ({md.MsgSeqNum}, '{md.TransactTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{md.SendingTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{entry.security_desc()}', '{nameof(BookMessage)}', '{ json }' ) ", + _sql); + try + { + cmd.ExecuteNonQuery(); + } + catch(Exception ex) + { + throw ex; + } } public void Dispose() diff --git a/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs b/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs index 88775b908..225b97df3 100644 --- a/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs +++ b/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs @@ -95,7 +95,7 @@ namespace bts.history [Option('5', "post_process_db", Required = false, Default = "", HelpText = "Name of the postgres db to generate from post processing")] public string post_process_db { get; set; } - [Option('6', "post_process_db_ip", Required = true, Default = "127.0.0.1", HelpText = "IP of the postgres db to generate from post processing")] + [Option('6', "post_process_db_ip", Required = false, Default = "127.0.0.1", HelpText = "IP of the postgres db to generate from post processing")] public string post_process_db_ip { get; set; } diff --git a/tools/simple_config.sh b/tools/simple_config.sh new file mode 100644 index 000000000..b932db5c2 --- /dev/null +++ b/tools/simple_config.sh @@ -0,0 +1,3 @@ +#!/bin/bash + +(cd /sparkdata/conf; python -m SimpleHTTPServer) \ No newline at end of file From 38b29f0afbd7963404bdf0c40c95bcea86d6ca9d Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 27 Nov 2019 17:14:29 -0500 Subject: [PATCH 04/10] more pg --- .vscode/launch.json | 12 ++-- .../Cmd/Historical/Analyzers/OrderBook.cs | 13 ++++- .../Historical/HistoricalDatabaseGenerator.cs | 55 +++++++++++++------ .../sparkcmd/Cmd/HistoricalDataCommand.cs | 6 +- 4 files changed, 56 insertions(+), 30 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 0dac8ebdd..c64ace030 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -105,14 +105,12 @@ "program": "${workspaceRoot}/build/Debug/bin/net471/sparkcmd.exe", "args": [ "historical", - "--rskip", "11/20/2019 10:00AM", - "--rstart", "11/20/2019 02:00PM", - "--rend", "11/20/2019 11:00PM", + "--rstart", "11/20/2019", + "--rend", "11/20/2019", "--rsymbol", "CL", "--rsecuritytype", "Spread", - "--algo_security", "CLZ9-CLF0;CLF0-CLG0;CLZ9-CLG0", - "--algo_type", "RoundTrip", - "--algo_params", "size=1;profit_ticks=1;tick_size=1,1,1;;hedge_factors=1,1,-1", + "--post_process_db", "mbo_history", + "--post_process_db_host", "sparkvm", ], "cwd": "${workspaceRoot}", "stopAtEntry": false, @@ -373,7 +371,7 @@ "--rend", "11/20/2019", "--rsymbol", "CL", "--rsecuritytype", "Spread", - "--post_process_db", "cl_history", + "--post_process_db", "mbo_history", ], "env": {"LD_LIBRARY_PATH" : "."}, "stopAtEntry": false, diff --git a/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs b/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs index 10fb9b63f..e772bf44f 100644 --- a/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs +++ b/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs @@ -337,13 +337,20 @@ namespace bts.history public bool cancel_my_order(ulong my_order_id) { return remove_my_order(my_order_id); - } - + } + + //https://www.cmegroup.com/confluence/display/EPICSANDBOX/MDP+3.0+-+Market+Data+Incremental+Refresh + //yes, but they make it a big-endian string public static bool quote_event_done(MarketDataIncrementalRefresh md) { return md.MatchEventIndicator[0] == '1' || md.MatchEventIndicator[5] == '1'; } - + + public static bool implied_quote_event_done(MarketDataIncrementalRefresh md) + { + return md.MatchEventIndicator[0] == '1' || md.MatchEventIndicator[3] == '1'; + } + public void process_md(MarketDataIncrementalRefresh md, Func filter, string debug_fix = null) { bool bidoffer = false, trade = false; diff --git a/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs b/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs index af5952921..9491a4850 100644 --- a/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs +++ b/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs @@ -13,15 +13,15 @@ namespace bts.history readonly HistoricalDataStreamer _stream; MarketDataIncrementalRefresh _last = new MarketDataIncrementalRefresh() { SendingTime = new Timestamp(), TransactTime = new Timestamp() }; readonly string _post_process_db; - readonly string _post_process_db_ip; + readonly string _post_process_db_host; Npgsql.NpgsqlConnection _sql; - public HistoricalDatabaseGenerator(string post_process_db, string post_process_db_ip) + public HistoricalDatabaseGenerator(string post_process_db, string post_process_db_host) { _post_process_db = post_process_db; - _post_process_db_ip = post_process_db_ip; + _post_process_db_host = post_process_db_host; _stream = new HistoricalDataStreamer(); - var conn = $@"Server={_post_process_db_ip};Port=5432; User Id=postgres;Password=enter;"; + var conn = $@"Server={_post_process_db_host};Port=5432; User Id=postgres;Password=enter;"; _sql = new Npgsql.NpgsqlConnection(conn); var create = new Npgsql.NpgsqlCommand( $@"CREATE DATABASE {_post_process_db} @@ -68,7 +68,7 @@ namespace bts.history => x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime())); await _stream.process_md_stream(query, (sectype, md, line) => { - if(count++ % 50000 == 1) + if(++count % 10000 == 1) Console.WriteLine($"preprocessed {count} lines"); if(md.timestamp().ToDateTime() > end) throw new System.IO.EndOfStreamException(); @@ -83,7 +83,8 @@ namespace bts.history _books[entry.security_desc()] = book; } OrderBook.keep_book(book, entry); - write_book(tname, book, entry, md); + if(OrderBook.quote_event_done(md)) + write_book_with_prepare(tname, book, entry, md); } else if (entry.MdEntryType == MDEntryType.Trade) { @@ -96,7 +97,7 @@ namespace bts.history private string maybe_create_table(DateTime start, DateTime end, string symbol, SecurityType st, HistoricalDataOptions o) { - var conn = $@"Server={_post_process_db_ip};Port=5432; User Id=postgres;Password=enter;Database={_post_process_db}"; + var conn = $@"Server={_post_process_db_host};Port=5432; User Id=postgres;Password=enter;Database={_post_process_db}"; _sql = new Npgsql.NpgsqlConnection(conn); var name = $"{symbol}_{st.ToString()}_history"; var cmd = new Npgsql.NpgsqlCommand( @@ -113,8 +114,10 @@ namespace bts.history { var json = Google.Protobuf.JsonFormatter.Default.Format(tm); var cmd = new Npgsql.NpgsqlCommand( - $"INSERT INTO {tname} (seqnum, transact_time, sending_time, security_desc, data_type, data ) " + - $"VALUES ({md.MsgSeqNum}, '{md.TransactTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{md.SendingTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{entry.security_desc()}', '{nameof(TradeMessage)}', '{ json }' ) ", + $@"INSERT INTO {tname} (seqnum, transact_time, sending_time, security_desc, data_type, data ) + VALUES ({md.MsgSeqNum}, '{md.TransactTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', + '{md.SendingTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{entry.security_desc()}', + '{nameof(TradeMessage)}', '{ json }' )", _sql); try { @@ -126,26 +129,44 @@ namespace bts.history } } - private void write_book(string tname, BookMessage book, MDEntry entry, MarketDataIncrementalRefresh md) + bool _book_prepared = false; + private void write_book_with_prepare(string tname, BookMessage book, MDEntry entry, MarketDataIncrementalRefresh md) { - if(!book.Bids.Any( x=>x.Size > 0) && !book.Asks.Any(x => x.Size > 0)) + if (!book.Bids.Any(x => x.Size > 0) && !book.Asks.Any(x => x.Size > 0)) return; - + + if(!_book_prepared) + { + var prep = new Npgsql.NpgsqlCommand( + $@"PREPARE bookplan (integer, timestamptz, timestamptz, text, text, jsonb) AS + INSERT INTO {tname} (seqnum, transact_time, sending_time, security_desc, data_type, data ) + VALUES($1, $2, $3, $4, $5, $6) ", _sql); + try + { + prep.ExecuteNonQuery(); + } + catch (Exception ex) + { + throw ex; + } + _book_prepared = true; + } var json = Google.Protobuf.JsonFormatter.Default.Format(book); var cmd = new Npgsql.NpgsqlCommand( - $"INSERT INTO {tname} (seqnum, transact_time, sending_time, security_desc, data_type, data ) " + - $"VALUES ({md.MsgSeqNum}, '{md.TransactTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{md.SendingTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{entry.security_desc()}', '{nameof(BookMessage)}', '{ json }' ) ", + $@"EXECUTE bookplan ({md.MsgSeqNum}, '{md.TransactTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', + '{md.SendingTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{entry.security_desc()}', + '{nameof(BookMessage)}', '{ json }' ) ", _sql); try { cmd.ExecuteNonQuery(); } - catch(Exception ex) + catch (Exception ex) { throw ex; } - } - + } + public void Dispose() { if(_sql != null) diff --git a/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs b/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs index 225b97df3..e660f6c22 100644 --- a/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs +++ b/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs @@ -95,8 +95,8 @@ namespace bts.history [Option('5', "post_process_db", Required = false, Default = "", HelpText = "Name of the postgres db to generate from post processing")] public string post_process_db { get; set; } - [Option('6', "post_process_db_ip", Required = false, Default = "127.0.0.1", HelpText = "IP of the postgres db to generate from post processing")] - public string post_process_db_ip { get; set; } + [Option('6', "post_process_db_host", Required = false, Default = "localhost", HelpText = "IP of the postgres db to generate from post processing")] + public string post_process_db_host { get; set; } public override string ToString() @@ -129,7 +129,7 @@ namespace bts.history st = (SecurityType)Enum.Parse(typeof(SecurityType), o.replaysecuritytype, true); if(!string.IsNullOrEmpty(o.post_process_db)) { - var rep = new HistoricalDatabaseGenerator(o.post_process_db, o.post_process_db_ip); + var rep = new HistoricalDatabaseGenerator(o.post_process_db, o.post_process_db_host); rep.generate(start, end, o.replaysymbol.ToUpper(), st, o).GetAwaiter().GetResult(); } else From e0112eff8971684fb6293e3c09f9b537549ecbc2 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 27 Nov 2019 17:20:55 -0500 Subject: [PATCH 05/10] stuff --- .../sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs | 2 +- src/lib/api/services/HistoricalDataService.proto | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs b/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs index 9491a4850..6393088a9 100644 --- a/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs +++ b/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs @@ -65,7 +65,7 @@ namespace bts.history int count = 0; var comparer = Comparer.Create((x, y) - => x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime())); + => x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime())); await _stream.process_md_stream(query, (sectype, md, line) => { if(++count % 10000 == 1) diff --git a/src/lib/api/services/HistoricalDataService.proto b/src/lib/api/services/HistoricalDataService.proto index d585c224e..df93fbe0a 100644 --- a/src/lib/api/services/HistoricalDataService.proto +++ b/src/lib/api/services/HistoricalDataService.proto @@ -145,7 +145,8 @@ message MDQuery int32 line_skip = 60; } -message ProcessedBook{ +message ProcessedBook +{ uint32 book_seq_num = 1; uint32 msg_seq_num = 10; google.protobuf.Timestamp sending_time = 20; From d6a533ca5ca27c39570b0c15d82eaf15f9f31a87 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 27 Nov 2019 17:21:24 -0500 Subject: [PATCH 06/10] PR feedback --- src/client/Directory.Build.targets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client/Directory.Build.targets b/src/client/Directory.Build.targets index 2aa10b04e..c52e45a1c 100644 --- a/src/client/Directory.Build.targets +++ b/src/client/Directory.Build.targets @@ -117,7 +117,7 @@ _books = new Dictionary(); async public Task generate(DateTime start, DateTime end, string symbol, SecurityType st, HistoricalDataOptions o) @@ -65,11 +70,15 @@ namespace bts.history int count = 0; var comparer = Comparer.Create((x, y) - => x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime())); + => x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime())); + + #pragma warning disable CS4014 + start_transaction_queue().ContinueWith( t => { throw t.Exception; }, TaskContinuationOptions.OnlyOnFaulted ); + await _stream.process_md_stream(query, (sectype, md, line) => { if(++count % 10000 == 1) - Console.WriteLine($"preprocessed {count} lines"); + Console.WriteLine($"preprocessed {count} lines, {_operations.Count} write queue length"); if(md.timestamp().ToDateTime() > end) throw new System.IO.EndOfStreamException(); foreach (var entry in md.MdEntries) @@ -95,22 +104,70 @@ namespace bts.history }, comparer); } - private string maybe_create_table(DateTime start, DateTime end, string symbol, SecurityType st, HistoricalDataOptions o) + string maybe_create_table(DateTime start, DateTime end, string symbol, SecurityType st, HistoricalDataOptions o) { var conn = $@"Server={_post_process_db_host};Port=5432; User Id=postgres;Password=enter;Database={_post_process_db}"; _sql = new Npgsql.NpgsqlConnection(conn); - var name = $"{symbol}_{st.ToString()}_history"; + var tname = $"{symbol}_{st.ToString()}_history"; var cmd = new Npgsql.NpgsqlCommand( - $@"CREATE TABLE IF NOT EXISTS {name} (id serial NOT NULL PRIMARY KEY, + $@"CREATE TABLE IF NOT EXISTS {tname} (id serial NOT NULL PRIMARY KEY, seqnum INTEGER NOT NULL CHECK(seqnum > 0), transact_time TIMESTAMPTZ NOT NULL, sending_time TIMESTAMPTZ NOT NULL, security_desc TEXT NOT NULL, data_type TEXT NOT NULL, data jsonb NOT NULL)", _sql); _sql.Open(); cmd.ExecuteNonQuery(); - return name; + + prepare_book_insert(tname); + return tname; } - private void write_trade(string tname, TradeMessage tm, MDEntry entry, MarketDataIncrementalRefresh md) + void prepare_book_insert(string tname) + { + var prep = new Npgsql.NpgsqlCommand( + $@"PREPARE bookplan (integer, timestamptz, timestamptz, text, text, jsonb) AS + INSERT INTO {tname} (seqnum, transact_time, sending_time, security_desc, data_type, data ) + VALUES($1, $2, $3, $4, $5, $6) ", _sql); + try + { + prep.ExecuteNonQuery(); + } + catch (Exception ex) + { + throw ex; + } + } + + async Task start_transaction_queue() + { + _qtask = Task.Run( async () => + { + while(true) + { + await Task.Delay(500); + if (_cts.IsCancellationRequested) + throw new TaskCanceledException(_qtask); + if(_operations.Count == 0) + continue; + + var trans = _sql.BeginTransaction(); + while(_operations.TryDequeue(out Npgsql.NpgsqlCommand cmd)) + { + try + { + cmd.ExecuteNonQuery(); + } + catch(Exception ex) + { + throw ex; + } + } + trans.Commit(); + } + }, _cts.Token); + await _qtask; + } + + void write_trade(string tname, TradeMessage tm, MDEntry entry, MarketDataIncrementalRefresh md) { var json = Google.Protobuf.JsonFormatter.Default.Format(tm); var cmd = new Npgsql.NpgsqlCommand( @@ -119,56 +176,28 @@ namespace bts.history '{md.SendingTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{entry.security_desc()}', '{nameof(TradeMessage)}', '{ json }' )", _sql); - try - { - cmd.ExecuteNonQuery(); - } - catch (Exception ex) - { - throw ex; - } + _operations.Enqueue(cmd); } - bool _book_prepared = false; - private void write_book_with_prepare(string tname, BookMessage book, MDEntry entry, MarketDataIncrementalRefresh md) + void write_book_with_prepare(string tname, BookMessage book, MDEntry entry, MarketDataIncrementalRefresh md) { if (!book.Bids.Any(x => x.Size > 0) && !book.Asks.Any(x => x.Size > 0)) return; - if(!_book_prepared) - { - var prep = new Npgsql.NpgsqlCommand( - $@"PREPARE bookplan (integer, timestamptz, timestamptz, text, text, jsonb) AS - INSERT INTO {tname} (seqnum, transact_time, sending_time, security_desc, data_type, data ) - VALUES($1, $2, $3, $4, $5, $6) ", _sql); - try - { - prep.ExecuteNonQuery(); - } - catch (Exception ex) - { - throw ex; - } - _book_prepared = true; - } var json = Google.Protobuf.JsonFormatter.Default.Format(book); var cmd = new Npgsql.NpgsqlCommand( $@"EXECUTE bookplan ({md.MsgSeqNum}, '{md.TransactTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{md.SendingTime.ToString().Replace('T', ' ').Replace("Z", "+00")}', '{entry.security_desc()}', '{nameof(BookMessage)}', '{ json }' ) ", _sql); - try - { - cmd.ExecuteNonQuery(); - } - catch (Exception ex) - { - throw ex; - } + _operations.Enqueue(cmd); } - public void Dispose() + public async void Dispose() { + _cts.Cancel(); + await _qtask; + if(_sql != null) _sql.Close(); } From 67c83c7d6811932c0f4e1b76bb57af8b7df25b94 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Wed, 27 Nov 2019 21:10:22 -0500 Subject: [PATCH 08/10] remove postgres tag from spark_vm_shell --- tools/spark_vm_shell.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/spark_vm_shell.sh b/tools/spark_vm_shell.sh index 406206dc7..dbc0c8ab1 100755 --- a/tools/spark_vm_shell.sh +++ b/tools/spark_vm_shell.sh @@ -22,7 +22,7 @@ docker run \ -e DISPLAY=$DISPLAY \ --name bts \ -d \ - -t bluetradingsystems/linux_docker:postgres \ + -t bluetradingsystems/linux_docker \ /bin/bash -c "(sudo /usr/sbin/sshd) & (cd ~ && $DIR/../externals/linux/bin/unison -socket 8080) & /bin/bash --login" From 5f45ddf210c118e6b80a92bdb4dfa923be9c67b7 Mon Sep 17 00:00:00 2001 From: Kevin Darby Date: Thu, 28 Nov 2019 02:46:27 +0000 Subject: [PATCH 09/10] wack vs backwack --- src/client/Directory.Build.targets | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/client/Directory.Build.targets b/src/client/Directory.Build.targets index c52e45a1c..cf31c0979 100644 --- a/src/client/Directory.Build.targets +++ b/src/client/Directory.Build.targets @@ -117,7 +117,7 @@