Merge branch 'vwap' of bitbucket.org:bluetradesys/spark into vwap

This commit is contained in:
Kevin Darby committed 2019-11-26 21:31:42 -05:00
commit 3280376df3
16 files changed
+260 -70

No files matched your search

+1 -1
View File
@@ -34,7 +34,7 @@
<PackageReference Include="Google.Protobuf" Version="3.6.1" />
<PackageReference Include="IronPython" Version="2.7.7" />
<PackageReference Include="NAudio" Version="1.8.4" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.0.0" />
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="NUnit3TestAdapter" Version="3.8.0" />
+1 -1
View File
@@ -25,7 +25,7 @@
<PackageReference Include="System.Reactive" Version="3.1.1" />
<PackageReference Include="System.Reactive.PlatformServices" Version="3.1.1" />
<PackageReference Include="NUnit" Version="3.10.1" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="System.Linq.Dynamic" Version="1.0.7" />
<PackageReference Include="ExcelDna.AddIn" Version="0.34.6" />
@@ -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<string, co2.BookMessage> _books =
private readonly Dictionary<string, co2.BookMessage> _books =
new Dictionary<string, co2.BookMessage>();
readonly string _path;
private readonly string _book_path;
IDictionary<string, SecData> _book_stream_map =
new Dictionary<string, SecData>();
public BookAnalyzer(string symbol,
HistoricalDataOptions options) {
_path = String.Format(@"{0}{1}/{2}/{3}/",
Configuration.get<bts.config.System>().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<bts.config.System>().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<bts.config.System>().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);
@@ -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)
{
@@ -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<IAnalyzer> anal = new List<IAnalyzer>();
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<Entry> arb = new List<Entry>();
int count = 0;
var comparer = Comparer<MarketDataIncrementalRefresh>.Create((x, y)
=> x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime()));
@@ -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,
@@ -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<string, co2.BookMessage> _books = new Dictionary<string, co2.BookMessage>();
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<MarketDataIncrementalRefresh>.Create((x, y)
=> x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime()));
await _stream.process_md_stream<MarketDataIncrementalRefresh>(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();
}
}
}
@@ -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;
@@ -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<ProcessedBook> _pbooks = new List<ProcessedBook>();
class BookState{
private List<BookEntry> _books = new List<BookEntry>();
public void add(IEnumerable<ProcessedBook> pbooks){
@@ -0,0 +1,29 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace bts.history{
class MarketQueries{
static IEnumerable<BookEntry> 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<Tuple<string,double,double,bool>> legs = new List<Tuple<string,double,double,bool>>();
int n_legs = (toks.Length-2)/4;
for (int l=0;l<n_legs;l++){
string contract = toks[i++];
double leg_qty = Double.Parse(toks[i++]);
double price_mult = Double.Parse(toks[i++]);
bool is_quoting = toks[i++].ToLower().StartsWith("q");
}
return null;
}
}
}
@@ -10,16 +10,32 @@ using Google.Protobuf.WellKnownTypes;
namespace bts.history{
class SpreaderTickSniperAnalyzer{
// product, date, result file, spreaders
public SpreaderTickSniperAnalyzer(HistoricalDataOptions hd_options){
string algo_params = hd_options.algo_params;
string[] args = algo_params.Split(';');
DateTime date = DateTime.Parse(args[0]);
string spread_file = args[1];
Console.WriteLine("SpreaderTickSniperAnalyzer date={0} file={1}",
date.ToShortDateString(), spread_file);
string input_file_name = hd_options.algo_params;
string path = String.Format(@"{0}/{1}",BookAnalyzer.get_algo_input_path("sniper"));
input_file_name = String.Format(@"{0}/{1}",path, input_file_name);
FileStream fs = new FileStream (input_file_name, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string product = sr.ReadLine();
DateTime day = DateTime.Parse (sr.ReadLine());
string output_file = sr.ReadLine ();
string spread;
while (fs.Position < fs.Length){
// read spreads
spread = sr.ReadLine();
}
_temp_test();
}
// given a spread and date, return all possible book values
// for that spread
private static IEnumerable<ProcessedBook> _get_spread_prices (string spread,
DateTime day){
return null;
}
public void _temp_test()
{
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
@@ -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;
}
+4 -1
View File
@@ -31,9 +31,12 @@
<ItemGroup>
<PackageReference Include="CommandLineParser" Version="2.6.0" />
<PackageReference Include="Microsoft.CSharp" Version="4.5.0" />
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<!-- <PackageReference Include="AWSSDK.Core" Version="3.3.103.31" /> -->
<!-- For historical analysis, to be moved out -->
<PackageReference Include="Npgsql" Version="4.1.2" />
<PackageReference Include="Npgsql.Json.NET" Version="4.1.2" />
<PackageReference Include="AWSSDK.S3" Version="3.3.104.17" />
<PackageReference Include="QuickFix.Net.NETCore" Version="1.8.1" />
<PackageReference Include="QuickFix.Net.NETCore.FIX50SP2" Version="1.8.1" />
+1 -1
View File
@@ -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"
+3
View File
@@ -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'