diff --git a/docker/linux b/docker/linux
index 68f43cef8..9d93e9352 160000
--- a/docker/linux
+++ b/docker/linux
@@ -1 +1 @@
-Subproject commit 68f43cef8d3edbda05a9517421092ada3c392aff
+Subproject commit 9d93e93525869620b0e051bf7c0021f667d2fc45
diff --git a/src/client/spark/Spark.csproj b/src/client/spark/Spark.csproj
index 5ea7c812f..bf89df6ea 100644
--- a/src/client/spark/Spark.csproj
+++ b/src/client/spark/Spark.csproj
@@ -34,7 +34,7 @@
-
+
diff --git a/src/client/spark_excel/spark_excel.csproj b/src/client/spark_excel/spark_excel.csproj
index 13e6e8828..e44d3dd43 100644
--- a/src/client/spark_excel/spark_excel.csproj
+++ b/src/client/spark_excel/spark_excel.csproj
@@ -25,7 +25,7 @@
-
+
diff --git a/src/client/sparkcmd/Cmd/Historical/Analyzers/BookAnalyzer.cs b/src/client/sparkcmd/Cmd/Historical/Analyzers/BookAnalyzer.cs
index 6832cae92..a453f0e57 100644
--- a/src/client/sparkcmd/Cmd/Historical/Analyzers/BookAnalyzer.cs
+++ b/src/client/sparkcmd/Cmd/Historical/Analyzers/BookAnalyzer.cs
@@ -8,7 +8,7 @@ using mbts.config;
using bts.config;
namespace bts.history
-{
+{
class BookAnalyzer : IAnalyzer
{
class SecData{
@@ -21,20 +21,16 @@ namespace bts.history
n_updates++;
}
}
- readonly Dictionary _books =
+ private readonly Dictionary _books =
new Dictionary();
- readonly string _path;
+ private readonly string _book_path;
IDictionary _book_stream_map =
new Dictionary();
public BookAnalyzer(string symbol,
HistoricalDataOptions options) {
- _path = String.Format(@"{0}{1}/{2}/{3}/",
- Configuration.get().data_path,
- "preprocessed_md",
- symbol,
- options.replaystart.Replace("/","_"));
- System.IO.Directory.CreateDirectory(_path);
+ _book_path = get_book_path(symbol, DateTime.Parse(options.replaystart));
+ System.IO.Directory.CreateDirectory(_book_path);
}
public void pre_analyze(MarketDataIncrementalRefresh md,
@@ -62,10 +58,29 @@ namespace bts.history
// handle trades here
}
}
+
+ public static string get_book_path (string symbol,
+ DateTime date){
+ return String.Format(@"{0}{1}/{2}/{3}/{4}/{5}/",
+ Configuration.get().data_path,
+ "trade_analysis",
+ "market_data",
+ date.ToShortDateString().Replace("/","_"),
+ "books",
+ symbol);
+ }
- void on_new_book(co2.BookMessage book,
- MDEntry entry,
- MarketDataIncrementalRefresh md_inc){
+ public static string get_algo_input_path (string algo_name){
+ return String.Format(@"{0}{1}/{2}/{3}/",
+ Configuration.get().data_path,
+ "trade_analysis",
+ "algos",
+ "algo_name");
+ }
+
+ private void on_new_book(co2.BookMessage book,
+ MDEntry entry,
+ MarketDataIncrementalRefresh md_inc){
ProcessedBook pb = new ProcessedBook();
pb.MsgSeqNum = md_inc.MsgSeqNum;
pb.SendingTime = md_inc.SendingTime;
@@ -76,7 +91,7 @@ namespace bts.history
if(!_book_stream_map.TryGetValue(pb.Security, out s)){
string file_name = pb.Security;
file_name = file_name.Replace(":",".");
- file_name = String.Format ("{0}{1}",_path,file_name);
+ file_name = String.Format ("{0}{1}",_book_path,file_name);
var str = new FileStream(file_name, FileMode.OpenOrCreate);
s = new SecData (str);
_book_stream_map.Add(pb.Security,s);
diff --git a/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs b/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs
index 8701f6345..10fb9b63f 100644
--- a/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs
+++ b/src/client/sparkcmd/Cmd/Historical/Analyzers/OrderBook.cs
@@ -394,14 +394,7 @@ namespace bts.history
this.last_trade_size = entry.MdEntrySize;
this.last_trade_price = entry.MdEntryPx;
- var tm = new TradeMessage();
- tm.Key = entry.SecurityId;
- tm.Time = md.timestamp().Seconds;
- var ip = IntPrice.from_double(entry.MdEntryPx);
- tm.Mantissa = ip.mantissa;
- tm.Exponent = ip.exponent;
- tm.Size = entry.MdEntrySize;
- tm.AggressorSide = (AggressorSide)entry.AggressorSide;
+ var tm = create_trade(md, entry);
list.Add(tm);
}
has_trade |= trade;
@@ -410,6 +403,20 @@ namespace bts.history
this.on_market_trade(md);
return list;
}
+
+ static public TradeMessage create_trade(MarketDataIncrementalRefresh md, MDEntry entry)
+ {
+ Log.assert(entry.MdEntryType == MDEntryType.Trade);
+ var tm = new TradeMessage();
+ tm.Key = entry.SecurityId;
+ tm.Time = md.timestamp().Seconds;
+ var ip = IntPrice.from_double(entry.MdEntryPx);
+ tm.Mantissa = ip.mantissa;
+ tm.Exponent = ip.exponent;
+ tm.Size = entry.MdEntrySize;
+ tm.AggressorSide = (AggressorSide)entry.AggressorSide;
+ return tm;
+ }
public void match_our_trades(MarketDataIncrementalRefresh md)
{
diff --git a/src/client/sparkcmd/Cmd/Historical/HistoricalDataReplayer.cs b/src/client/sparkcmd/Cmd/Historical/HistoricalDataReplayer.cs
index c718cb2f0..ef5952bed 100644
--- a/src/client/sparkcmd/Cmd/Historical/HistoricalDataReplayer.cs
+++ b/src/client/sparkcmd/Cmd/Historical/HistoricalDataReplayer.cs
@@ -13,7 +13,7 @@ namespace bts.history
class HistoricalDataReplayer
{
readonly HistoricalDataStreamer _stream;
- MarketDataIncrementalRefresh _last = new MarketDataIncrementalRefresh() { SendingTime = new Timestamp() } ;
+ MarketDataIncrementalRefresh _last = new MarketDataIncrementalRefresh() { SendingTime = new Timestamp(), TransactTime = new Timestamp() } ;
public HistoricalDataReplayer()
{
_stream = new HistoricalDataStreamer();
@@ -35,8 +35,6 @@ namespace bts.history
};
if(DateTime.TryParse(o.replayskip, out DateTime skip) && skip != DateTime.MinValue)
query.Skip = Timestamp.FromDateTime(skip.ToUniversalTime());
- else
- query.Skip = null;
List anal = new List();
string algo_security = o.algo_security ?? string.Empty;
@@ -53,8 +51,6 @@ namespace bts.history
else
anal.Add(new BookAnalyzer(algo_security, o));
- api.Product prod = new Product() { Exchange = query.Exchange, Type = query.SecurityType, Symbol = query.Symbol };
- List arb = new List();
int count = 0;
var comparer = Comparer.Create((x, y)
=> x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime()));
diff --git a/src/client/sparkcmd/Cmd/Historical/HistoricalDataSender.cs b/src/client/sparkcmd/Cmd/Historical/HistoricalDataSender.cs
index 1b526a15f..c591aa8d7 100644
--- a/src/client/sparkcmd/Cmd/Historical/HistoricalDataSender.cs
+++ b/src/client/sparkcmd/Cmd/Historical/HistoricalDataSender.cs
@@ -121,7 +121,7 @@ namespace bts.history
async public Task replay(DateTime start, DateTime end, string symbol, SecurityType st,
HistoricalDataOptions o)
{
- int us = o.dt_us;
+ int us = 20;//o.dt_us;
var query = new MDQuery
{
Exchange = Venue.Glbx,
diff --git a/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs b/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs
new file mode 100644
index 000000000..5e80f0af4
--- /dev/null
+++ b/src/client/sparkcmd/Cmd/Historical/HistoricalDatabaseGenerator.cs
@@ -0,0 +1,125 @@
+using System;
+using System.Collections.Generic;
+using System.Threading.Tasks;
+using bts.api;
+using bts.co2;
+using Google.Protobuf.WellKnownTypes;
+
+namespace bts.history
+{
+ class HistoricalDatabaseGenerator : IDisposable
+ {
+ readonly HistoricalDataStreamer _stream;
+ MarketDataIncrementalRefresh _last = new MarketDataIncrementalRefresh() { SendingTime = new Timestamp(), TransactTime = new Timestamp() };
+ readonly string _post_process_db;
+ readonly string _post_process_db_ip;
+ Npgsql.NpgsqlConnection _sql;
+
+ public HistoricalDatabaseGenerator(string post_process_db, string post_process_db_ip)
+ {
+ _post_process_db = post_process_db;
+ _post_process_db_ip = post_process_db_ip;
+ _stream = new HistoricalDataStreamer();
+ 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}
+ with owner = postgres
+ encoding = 'UTF8'
+ connection limit = -1;
+ ", _sql);
+ _sql.Open();
+ create.ExecuteNonQuery();
+ _sql.Close(); //TODO google says I have to do this
+ _sql = null;
+ }
+
+ readonly Dictionary _books = new Dictionary();
+
+ async public Task generate(DateTime start, DateTime end, string symbol, SecurityType st,
+ HistoricalDataOptions o)
+ {
+ var tname = maybe_create_table(start, end, symbol, st, o);
+ start = start.ToUniversalTime();
+ end = end.ToUniversalTime();
+ var query = new MDQuery
+ {
+ Exchange = Venue.Glbx,
+ Symbol = symbol,
+ SecurityType = st,
+ Begin = Timestamp.FromDateTime(start),
+ End = Timestamp.FromDateTime(end),
+ LineSkip = o.lineskip,
+ };
+ if (DateTime.TryParse(o.replayskip, out DateTime skip) && skip != DateTime.MinValue)
+ query.Skip = Timestamp.FromDateTime(skip.ToUniversalTime());
+
+ var comparer = Comparer.Create((x, y)
+ => x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime()));
+ await _stream.process_md_stream(query, (sectype, md, line) =>
+ {
+ foreach (var entry in md.MdEntries)
+ {
+ if (entry.MdEntryType == MDEntryType.Bid || entry.MdEntryType == MDEntryType.Offer)
+ {
+ if (!_books.TryGetValue(entry.Symbol, out co2.BookMessage book))
+ {
+ book = new co2.BookMessage();
+ OrderBook.init_book(book);
+ _books[entry.security_desc()] = book;
+ }
+ OrderBook.keep_book(book, entry);
+ write_book(tname, book, entry, md);
+ }
+ else if (entry.MdEntryType == MDEntryType.Trade)
+ {
+ var tm = OrderBook.create_trade(md, entry);
+ write_trade(tname, tm, entry, md);
+ }
+ }
+ }, comparer);
+ }
+
+ 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}";
+ _sql = new Npgsql.NpgsqlConnection(conn);
+ var name = $"{symbol}_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,
+ security_desc TEXT NOT NULL, data_type TEXT NOT NULL, data jsonb NOT NULL)",
+ _sql);
+ _sql.Open();
+ cmd.ExecuteNonQuery();
+ return name;
+ }
+
+ 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();
+ }
+
+ private void write_book(string tname, BookMessage book, MDEntry entry, MarketDataIncrementalRefresh md)
+ {
+ 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);
+ }
+
+ public void Dispose()
+ {
+ if(_sql != null)
+ _sql.Close();
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/client/sparkcmd/Cmd/Historical/HistoricalExtensions.cs b/src/client/sparkcmd/Cmd/Historical/HistoricalExtensions.cs
index 91be12059..c5a8fa5b2 100644
--- a/src/client/sparkcmd/Cmd/Historical/HistoricalExtensions.cs
+++ b/src/client/sparkcmd/Cmd/Historical/HistoricalExtensions.cs
@@ -8,12 +8,14 @@ namespace bts.history
{
return md.SendingTime;
}
-
+ public static string security_desc(this MDEntry md)
+ {
+ return md.Symbol;
+ }
public static bool less(this Timestamp lhs, Timestamp rhs)
{
return lhs.Seconds * 1e9 + lhs.Nanos < rhs.Seconds * 1e9 + rhs.Nanos;
}
-
public static bool less_or_equal(this Timestamp lhs, Timestamp rhs)
{
return lhs.Seconds * 1e9 + lhs.Nanos <= rhs.Seconds * 1e9 + rhs.Nanos;
diff --git a/src/client/sparkcmd/Cmd/Historical/StaticAnalysis/DayBookState.cs b/src/client/sparkcmd/Cmd/Historical/StaticAnalysis/DayBookState.cs
index d31d169f5..e64fd5ad6 100644
--- a/src/client/sparkcmd/Cmd/Historical/StaticAnalysis/DayBookState.cs
+++ b/src/client/sparkcmd/Cmd/Historical/StaticAnalysis/DayBookState.cs
@@ -5,8 +5,7 @@ using Google.Protobuf.WellKnownTypes;
namespace bts.history{
// all book updates for a security, for the duration of a day
- class BookState{
- //private List _pbooks = new List();
+ class BookState{
private List _books = new List();
public void add(IEnumerable pbooks){
diff --git a/src/client/sparkcmd/Cmd/Historical/StaticAnalysis/MarketQueries.cs b/src/client/sparkcmd/Cmd/Historical/StaticAnalysis/MarketQueries.cs
new file mode 100644
index 000000000..80a973770
--- /dev/null
+++ b/src/client/sparkcmd/Cmd/Historical/StaticAnalysis/MarketQueries.cs
@@ -0,0 +1,29 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace bts.history{
+ class MarketQueries{
+ static IEnumerable get_synthetic_prices(string synthetic_text,
+ DateTime date){
+ return null;
+ }
+ // name, tick_size, (leg, qty, price_mult, q/h)*
+ static bts.api.Security parse_synthetic (string synthetic_text){
+ uint i=0;
+ string[] toks = synthetic_text.Split(',');
+ string name = toks[i++];
+ double tick_size = Double.Parse(toks[i++]);
+ List> legs = new List>();
+ int n_legs = (toks.Length-2)/4;
+ for (int l=0;l _get_spread_prices (string spread,
+ DateTime day){
+ return null;
+ }
+
public void _temp_test()
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
diff --git a/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs b/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs
index 97f6a1a0c..88775b908 100644
--- a/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs
+++ b/src/client/sparkcmd/Cmd/HistoricalDataCommand.cs
@@ -77,16 +77,8 @@ namespace bts.history
[Option('t', "rsecuritytype", Required = false, HelpText = "SecurityType for replay backtesting")]
public string replaysecuritytype{ get; set; }
-
- [Option('>', "should_send", Required = false, Default = false, HelpText = "Should send books through BTS's push_md service")]
- public bool should_send { get; set; }
-
- [Option('m', "micros", Required = false, HelpText = "A quantum of time, in microseconds to send data to BTS through push_md")]
- public int dt_us{ get; set; }
- [Option('p', "post_process", Required = false, Default = "Book", HelpText = "Book|Trade|Order")]
- public string post_process { get; set; }
-
+
[Option('1', "algo_security", Required = false, HelpText = "Security Desc i.e. ZCZ9 on which to run stat analysis")]
public string algo_security { get; set; }
@@ -96,9 +88,17 @@ namespace bts.history
[Option('3', "algo_params", Required = false, Default = "size=1;", HelpText = "semicolon dellimited list of key=value pairs to parameterize algo")]
public string algo_params { get; set; }
- [Option('i', "skip_preanalysis", Required = false, Default = false, HelpText = "don't send data before midnight on rstart to pre-analysis")]
+ [Option('4', "skip_preanalysis", Required = false, Default = false, HelpText = "don't send data before midnight on rstart to pre-analysis")]
public bool skip_preanalysis { get; set; }
+
+ [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")]
+ public string post_process_db_ip { get; set; }
+
+
public override string ToString()
{
return Stringizer.to_string(this);
@@ -111,27 +111,14 @@ namespace bts.history
public static int Run(HistoricalDataOptions o)
{
Console.WriteLine(o.ToString());
- if ("sniper".Equals (o.algo_type)){
+ if ("sniper".Equals (o.algo_type))
+ {
Console.WriteLine("Analyzing sniper");
SpreaderTickSniperAnalyzer sa = new SpreaderTickSniperAnalyzer(o);
sa.analyze();
return 0;
}
- if(o.should_send)
- {
- var start = DateTime.Parse(o.replaystart);
- var end = DateTime.Parse(o.replayend).AddDays(1.0); //incl
- SecurityType st = SecurityType.Future;
- if (!string.IsNullOrEmpty(o.replaysecuritytype))
- st = (SecurityType)Enum.Parse(typeof(SecurityType), o.replaysecuritytype, true);
- using (var ctx = new ServiceContext())
- {
- var rep = new HistoricalDataSender(ctx);
- rep.replay(start, end, o.replaysymbol.ToUpper(), st, o).GetAwaiter().GetResult();
- }
- return 0;
- }
-
+
if (!string.IsNullOrEmpty(o.replayend) && !string.IsNullOrEmpty(o.replaystart) &&
!string.IsNullOrEmpty(o.replaysymbol) )
{
@@ -140,8 +127,16 @@ namespace bts.history
SecurityType st = SecurityType.Future;
if(!string.IsNullOrEmpty(o.replaysecuritytype))
st = (SecurityType)Enum.Parse(typeof(SecurityType), o.replaysecuritytype, true);
- var rep = new HistoricalDataReplayer();
- rep.replay(start, end, o.replaysymbol.ToUpper(), st, o).GetAwaiter().GetResult();
+ if(!string.IsNullOrEmpty(o.post_process_db))
+ {
+ var rep = new HistoricalDatabaseGenerator(o.post_process_db, o.post_process_db_ip);
+ rep.generate(start, end, o.replaysymbol.ToUpper(), st, o).GetAwaiter().GetResult();
+ }
+ else
+ {
+ var rep = new HistoricalDataReplayer();
+ rep.replay(start, end, o.replaysymbol.ToUpper(), st, o).GetAwaiter().GetResult();
+ }
Console.ReadKey();
return 0;
}
diff --git a/src/client/sparkcmd/sparkcmd.csproj b/src/client/sparkcmd/sparkcmd.csproj
index 861a9c543..6d4763492 100644
--- a/src/client/sparkcmd/sparkcmd.csproj
+++ b/src/client/sparkcmd/sparkcmd.csproj
@@ -31,9 +31,12 @@
-
+
+
+
+
diff --git a/tools/spark_vm_shell.sh b/tools/spark_vm_shell.sh
index dbc0c8ab1..406206dc7 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 \
+ -t bluetradingsystems/linux_docker:postgres \
/bin/bash -c "(sudo /usr/sbin/sshd) & (cd ~ && $DIR/../externals/linux/bin/unison -socket 8080) & /bin/bash --login"
diff --git a/tools/start_postgres.sh b/tools/start_postgres.sh
new file mode 100644
index 000000000..0dc5ba609
--- /dev/null
+++ b/tools/start_postgres.sh
@@ -0,0 +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