fixed spreads / outright arbitration
This commit is contained in:
1 parent
a251a8f411
commit
6638e4c765
7 files changed
+113
-85
No files matched your search
Vendored
+7
-8
@@ -105,15 +105,14 @@
|
||||
"program": "${workspaceRoot}/build/Debug/bin/net471/sparkcmd.exe",
|
||||
"args": [
|
||||
"historical",
|
||||
"--lskip", "18000000",
|
||||
"--rskip", "10/21/2019 02:40:00 PM",
|
||||
"--rstart", "10/21/2019",
|
||||
"--rend", "10/21/2019",
|
||||
"--rsymbol", "CL",
|
||||
"--rsecuritytype", "Spread",
|
||||
"--algo_security", "CLX9-CLZ9;CLZ9-CLF0;CLX9-CLF0",
|
||||
"--rskip", "08/28/2019",
|
||||
"--rstart", "08/28/2019",
|
||||
"--rend", "08/28/2019",
|
||||
"--rsymbol", "ZN",
|
||||
"--rsecuritytype", "Synthetic",
|
||||
"--algo_security", "ZNU9;ZNU9-ZNZ9;ZNZ9",
|
||||
"--algo_type", "RoundTrip",
|
||||
"--algo_params", "size=1;profit_ticks=1;tick_size=1,1,1;;hedge_factors=1,1,1"
|
||||
"--algo_params", "size=1;profit_ticks=1;tick_size=0.015625,0.0078125,0.015625;hedge_factors=1,-1,-1"
|
||||
],
|
||||
"cwd": "${workspaceRoot}",
|
||||
"stopAtEntry": false,
|
||||
|
||||
@@ -37,7 +37,7 @@ namespace bts.history
|
||||
if(mde.MdEntryType == MDEntryType.Trade)
|
||||
{
|
||||
//opposite the aggressor
|
||||
api.Side side = (mde.AggressorSide == 0 ? api.Side.Undefined : (mde.AggressorSide == 1 ? api.Side.Sell : api.Side.Buy));
|
||||
api.Side side = (mde.AggressorSide == 0 ? api.Side.Undefined : (mde.AggressorSide == 1 ? api.Side.Buy : api.Side.Sell));
|
||||
//convert to a fill entry to write
|
||||
var ord = new OrderEntry(mde.Symbol, "Market");
|
||||
FillEntry ent = new FillEntry(md.timestamp(), ord, side, mde.MdEntryPx, mde.LastQty, -1, -1);
|
||||
@@ -50,9 +50,10 @@ namespace bts.history
|
||||
_symbol = options.replaysymbol;
|
||||
_securitytype = (SecurityType)Enum.Parse(typeof(SecurityType), options.replaysecuritytype);
|
||||
_tradedate = DateTime.Parse(options.replaystart);
|
||||
var path = HistoricalDataDownloader.data_path(_tradedate.Date, _symbol, _securitytype);
|
||||
var path = HistoricalDataDownloader.data_path(_tradedate.Date);
|
||||
new FileInfo(path).Directory.Create();
|
||||
_fs = new StreamWriter(
|
||||
File.Open(path + $"/{algo.GetType().Name}_{algo.bucket.LowerBound.ToString("0") }_trades.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite) );
|
||||
File.Open(path + $"/{_symbol}_{_securitytype}_{algo.GetType().Name}_{algo.bucket.LowerBound.ToString("0") }_trades.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite) );
|
||||
}
|
||||
|
||||
~AlgoWrapper()
|
||||
@@ -120,6 +121,7 @@ namespace bts.history
|
||||
var t = _market_tradelog.Dequeue();
|
||||
fills.Add(t);
|
||||
}
|
||||
fills.Sort( Comparer<FillEntry>.Create( (x, y) => x.timestamp.compare(y.timestamp) ) );
|
||||
foreach(var t in fills)
|
||||
_fs.WriteLine(t.ToString());
|
||||
_fs.Flush();
|
||||
|
||||
@@ -34,13 +34,13 @@ namespace bts.history
|
||||
//algo parameters
|
||||
public double lean_factor { get; set; } = 1.0;
|
||||
public int profit_ticks { get; set; } = 1;
|
||||
public int[] tick_size { get; set; }
|
||||
public double[] tick_size { get; set; }
|
||||
public bool[] should_quote { get; set; }
|
||||
public double[] hedge_factors { get; set; }
|
||||
|
||||
SortedList<string, double> _tick_size = new SortedList<string, double>();
|
||||
SortedList<string, double> _hedge_factors = new SortedList<string, double>();
|
||||
|
||||
string _quote_leg;
|
||||
|
||||
protected override void on_activate(string[] security_list, api.Side side, double price, uint size, Timestamp asof)
|
||||
{
|
||||
@@ -51,6 +51,7 @@ namespace bts.history
|
||||
_working_book[_security_list[i]] = null;
|
||||
_tick_size[_security_list[i]] = tick_size[i];
|
||||
_hedge_factors[_security_list[i]] = hedge_factors[i];
|
||||
_quote_leg = _security_list[i]; //last
|
||||
}
|
||||
_state = AlgoState.Begin;
|
||||
_mysize = size;
|
||||
@@ -67,7 +68,7 @@ namespace bts.history
|
||||
{
|
||||
var b = base.report();
|
||||
string qtleg = _security_list.Last();
|
||||
return $"{b} Quoting(bsz,bpx,bpiq ssz,spx,spiq) = ( {_buystatus.size},{_buystatus.price},{_buypiq} at {_sellstatus.size},{_sellstatus.price},{_sellpiq} )";
|
||||
return $"{b} Quoting {_quote_leg} (bsz,bpx,bpiq ssz,spx,spiq) = ( {_buystatus.size},{_buystatus.price},{_buypiq} at {_sellstatus.size},{_sellstatus.price},{_sellpiq} )";
|
||||
}
|
||||
|
||||
protected override void on_child_status(Handle child, OrderStatus stat)
|
||||
@@ -91,18 +92,34 @@ namespace bts.history
|
||||
|
||||
protected override void on_child_fill(Handle child, FillEntry fill)
|
||||
{
|
||||
var ff = factor_side(this._hedge_factors[_quote_leg]);
|
||||
bool invert = ff != fill.order.side;
|
||||
|
||||
foreach(var sec in _security_list)
|
||||
{
|
||||
if(sec == _security_list.Last())
|
||||
if(sec == _quote_leg)
|
||||
continue;
|
||||
|
||||
var side = OrderBook.opposite_side(fill.order.side);
|
||||
uint size = (uint)(fill.size * this._hedge_factors[sec]);
|
||||
double price = (side == api.Side.Buy) ? _current_book[sec].ask_at(0) : _current_book[sec].bid_at(0);
|
||||
|
||||
var hedgeside = factor_side(this._hedge_factors[sec], invert);
|
||||
|
||||
uint size = (uint)(fill.size * Math.Abs(this._hedge_factors[sec]));
|
||||
double price = (hedgeside == api.Side.Buy) ? _current_book[sec].ask_at(0) : _current_book[sec].bid_at(0);
|
||||
queue_hedge(_packet, sec,
|
||||
(new[] { sec }, side, price, size));
|
||||
(new[] { sec }, hedgeside, price, size));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
api.Side factor_side(double mult, bool invert = false)
|
||||
{
|
||||
api.Side sd = api.Side.Undefined;
|
||||
if(mult >= 0.0)
|
||||
sd = api.Side.Buy;
|
||||
else
|
||||
sd = api.Side.Sell;
|
||||
if(invert)
|
||||
sd = OrderBook.opposite_side(sd);
|
||||
return sd;
|
||||
}
|
||||
|
||||
protected override void on_md(string security_desc, co2.BookMessage current_book, co2.BookMessage working_book,
|
||||
MarketDataIncrementalRefresh pre_packet)
|
||||
@@ -121,30 +138,42 @@ namespace bts.history
|
||||
case AlgoState.Quoting:
|
||||
{
|
||||
uint sz = 0;
|
||||
string qtleg = _security_list.Last();
|
||||
foreach(var side in new[] { api.Side.Buy, api.Side.Sell })
|
||||
foreach(var invert in new[] { false, true})
|
||||
{
|
||||
double qt = 0.0;
|
||||
var opp = OrderBook.opposite_side(side);
|
||||
double qt = 0.0;
|
||||
api.Side quoteside = factor_side(this._hedge_factors[_quote_leg], invert);
|
||||
foreach(var sec in _security_list)
|
||||
{
|
||||
var book = _current_book[sec];
|
||||
if (sec != qtleg)
|
||||
{
|
||||
qt += book.side_at(opp, 0);
|
||||
sz = Math.Min(_mysize, (uint) (book.sidesize_at(opp, 0) / this._hedge_factors[sec]) );
|
||||
if (sec != _quote_leg)
|
||||
{
|
||||
var hedge_side = factor_side(this._hedge_factors[sec], invert);
|
||||
var cross_side = OrderBook.opposite_side(hedge_side);
|
||||
qt += book.side_at(cross_side, 0);
|
||||
sz = Math.Min(_mysize, (uint) (book.sidesize_at(cross_side, 0) / Math.Abs(this._hedge_factors[sec])) );
|
||||
}
|
||||
else
|
||||
{
|
||||
if(opp == api.Side.Sell)
|
||||
if(quoteside == api.Side.Sell)
|
||||
{
|
||||
qt += profit_ticks*_tick_size[sec];
|
||||
qt = Math.Max(qt, current_book.ask_at(0));
|
||||
}
|
||||
else
|
||||
{
|
||||
qt -= profit_ticks*_tick_size[sec];
|
||||
qt = Math.Min(qt, current_book.bid_at(0));
|
||||
}
|
||||
}
|
||||
}
|
||||
var param = (opp, qt, sz);
|
||||
if (!double.IsNaN(qt) && sz > 0 && security_desc == qtleg)
|
||||
queue_reaction(quote_function, pre_packet, qtleg, param);
|
||||
var param = (quoteside, qt, sz);
|
||||
if (!double.IsNaN(qt) && sz > 0 && security_desc == _quote_leg)
|
||||
{
|
||||
if(quoteside == api.Side.Buy && (_buystatus.price != qt || _buystatus.size != sz) && !_buystatus.is_terminal())
|
||||
queue_reaction(quote_function, pre_packet, _quote_leg, param);
|
||||
else if(quoteside == api.Side.Sell && (_sellstatus.price != qt || _sellstatus.size != sz) && !_sellstatus.is_terminal())
|
||||
queue_reaction(quote_function, pre_packet, _quote_leg, param);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -157,20 +186,20 @@ namespace bts.history
|
||||
}
|
||||
void quote_function(MarketDataIncrementalRefresh packet, string qtleg, object param, Timestamp asof)
|
||||
{
|
||||
(api.Side side, double qt, uint sz) tup = (ValueTuple<api.Side, double, uint>) param;
|
||||
if (!double.IsNaN(tup.qt) && tup.sz > 0 && tup.side == api.Side.Buy)
|
||||
(api.Side quoteside, double qt, uint sz) tup = (ValueTuple<api.Side, double, uint>) param;
|
||||
if (tup.quoteside == api.Side.Buy)
|
||||
{
|
||||
if (_buychild == null)
|
||||
_buychild = this.activate<Child>(new[] { qtleg }, tup.side, tup.qt, tup.sz, asof);
|
||||
else if (_buystatus.price != tup.qt && !_buystatus.is_terminal())
|
||||
_buychild = this.activate<Child>(new[] { qtleg }, tup.quoteside, tup.qt, tup.sz, asof);
|
||||
else
|
||||
_buychild.update(asof, tup.qt, tup.sz);
|
||||
_buypiq = _order_book[qtleg].get_my_piq(_buychild?.order_id ?? 0);
|
||||
}
|
||||
else if(!double.IsNaN(tup.qt) && tup.sz > 0 && tup.side == api.Side.Sell)
|
||||
else
|
||||
{
|
||||
if (_sellchild == null)
|
||||
_sellchild = this.activate<Child>(new[] { qtleg }, tup.side, tup.qt, tup.sz, asof);
|
||||
else if (_sellstatus.price != tup.qt && !_sellstatus.is_terminal())
|
||||
_sellchild = this.activate<Child>(new[] { qtleg }, tup.quoteside, tup.qt, tup.sz, asof);
|
||||
else
|
||||
_sellchild.update(asof, tup.qt, tup.sz);
|
||||
_sellpiq = _order_book[qtleg].get_my_piq(_sellchild?.order_id ?? 0);
|
||||
}
|
||||
|
||||
@@ -637,12 +637,14 @@ namespace bts.history
|
||||
bool desc = true;
|
||||
for (int i = 0; i < book.Bids.Count - 1; i++)
|
||||
{
|
||||
double curr = NativePriceHelpers.to_double(book.Bids[i].Mantissa, (sbyte)book.Bids[i].Exponent);
|
||||
double next = NativePriceHelpers.to_double(book.Bids[i + 1].Mantissa, (sbyte)book.Bids[i + 1].Exponent);
|
||||
if (curr == 0.0)
|
||||
double curr = book.bid_at(i);
|
||||
double next = book.bid_at(i+1);
|
||||
if(book.bidsize_at(i) == 0 || book.bidsize_at(i+1) == 0)
|
||||
continue;
|
||||
desc = desc && curr > next;
|
||||
}
|
||||
if(book.asksize_at(0) == 0 && book.asksize_at(1) > 0)
|
||||
Log.assert(true);
|
||||
if (!desc)
|
||||
{
|
||||
bts.Log.Testing.info("bad bid book " + debug_fix ?? "");
|
||||
|
||||
@@ -114,7 +114,7 @@ namespace bts.history
|
||||
string prefix = $"mbo/mbo/{date}/";
|
||||
return prefix + key;
|
||||
}
|
||||
public static string data_path(DateTime dt, string symbol, api.SecurityType st)
|
||||
public static string data_path(DateTime dt)
|
||||
{
|
||||
string date = dt.ToString("yyyyMMdd");
|
||||
string prefix = $"mbo/mbo/{date}/";
|
||||
|
||||
@@ -6,12 +6,14 @@ using bts.api;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using MathNet.Numerics.Statistics;
|
||||
|
||||
using Entry = System.Tuple<bts.api.SecurityType, bts.history.MarketDataIncrementalRefresh, string>;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
class HistoricalDataReplayer
|
||||
{
|
||||
readonly HistoricalDataStreamer _stream;
|
||||
Timestamp _last = new Timestamp();
|
||||
MarketDataIncrementalRefresh _last = new MarketDataIncrementalRefresh() { SendingTime = new Timestamp() } ;
|
||||
public HistoricalDataReplayer()
|
||||
{
|
||||
_stream = new HistoricalDataStreamer();
|
||||
@@ -49,48 +51,24 @@ namespace bts.history
|
||||
anal.Add(new QueueAnalyzer(algo_security));
|
||||
}
|
||||
api.Product prod = new Product() { Exchange = query.Exchange, Type = query.SecurityType, Symbol = query.Symbol };
|
||||
SortedList<decimal, Tuple<SecurityType, history.MarketDataIncrementalRefresh, string>> arb =
|
||||
new SortedList<decimal, Tuple<SecurityType, MarketDataIncrementalRefresh, string>>();
|
||||
List<Entry> arb = new List<Entry>();
|
||||
int count = 0;
|
||||
await _stream.process_md_stream<history.MarketDataIncrementalRefresh>(query, (sectype, md, line) =>
|
||||
var comparer = Comparer<MarketDataIncrementalRefresh>.Create((x, y)
|
||||
=> x.timestamp().ToDateTime().CompareTo(y.timestamp().ToDateTime()));
|
||||
await _stream.process_md_stream<MarketDataIncrementalRefresh>(query, (sectype, md, line) =>
|
||||
{
|
||||
if (md.timestamp().ToDateTime() < end)
|
||||
{
|
||||
bool preanal = (md.timestamp().ToDateTime() < start);
|
||||
if(preanal && count++ % 50000 == 1)
|
||||
Console.WriteLine("Pre analysis " + md.timestamp().ToDateTime());
|
||||
if (query.SecurityType == SecurityType.Synthetic)
|
||||
{
|
||||
decimal ts = (decimal)(md.timestamp().Seconds * 1e9) + md.timestamp().Nanos;
|
||||
if(arb.ContainsKey(ts))
|
||||
flush();
|
||||
arb.Add(ts, Tuple.Create(sectype, md, line));
|
||||
if (arb.Any(x => x.Value.Item1 == SecurityType.Future) &&
|
||||
arb.Any(x => x.Value.Item1 == SecurityType.Spread) &&
|
||||
arb.Last().Key != ts)
|
||||
{
|
||||
flush();
|
||||
}
|
||||
void flush()
|
||||
{
|
||||
foreach (var aa in arb)
|
||||
{
|
||||
do_anal(aa.Value.Item2, anal, preanal, aa.Value.Item3);
|
||||
Log.assert(aa.Value.Item2.timestamp().greater_or_equal(_last));
|
||||
_last = md.timestamp();
|
||||
}
|
||||
arb.Clear();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
do_anal(md, anal, preanal, line);
|
||||
Log.assert(md.timestamp().greater_or_equal( _last ));
|
||||
_last = md.timestamp();
|
||||
}
|
||||
do_anal(md, anal, preanal, line);
|
||||
Log.assert(md.timestamp().greater_or_equal( _last.timestamp() ));
|
||||
_last = md;
|
||||
}
|
||||
});
|
||||
}, comparer);
|
||||
}
|
||||
|
||||
|
||||
void do_anal(MarketDataIncrementalRefresh md, IEnumerable<IAnalyzer> anal, bool is_before_analysis_time, string debug_fix = null)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using bts.api;
|
||||
|
||||
@@ -13,7 +14,8 @@ namespace bts.history
|
||||
|
||||
|
||||
#pragma warning disable CS0183
|
||||
async public Task process_md_stream<T>(MDQuery request, Action<SecurityType, T, string> action) where T : Google.Protobuf.IMessage, new()
|
||||
async public Task process_md_stream<T>(MDQuery request, Action<SecurityType, T, string> action, IComparer<T> comp = null)
|
||||
where T : Google.Protobuf.IMessage, new()
|
||||
{
|
||||
DateTime d = request.Begin.ToDateTime();
|
||||
while (d <= request.End.ToDateTime())
|
||||
@@ -30,15 +32,31 @@ namespace bts.history
|
||||
{
|
||||
var fut = fparser.next<T>(null, null, request.Skip, request.LineSkip).GetEnumerator();
|
||||
var spr = sparser.next<T>(null, null, request.Skip, request.LineSkip).GetEnumerator();
|
||||
bool futgo , sprgo;
|
||||
while( (futgo = fut.MoveNext()) is bool &&
|
||||
(sprgo = spr.MoveNext()) is bool )
|
||||
bool futgo = fut.MoveNext(), sprgo = spr.MoveNext();
|
||||
while(futgo || sprgo)
|
||||
{
|
||||
if(futgo)
|
||||
if(comp.Compare(fut.Current.Item1, spr.Current.Item1) < 0)
|
||||
{
|
||||
action(SecurityType.Future, fut.Current.Item1, fut.Current.Item2.Replace('\u0001', '|'));
|
||||
if(sprgo)
|
||||
if(futgo)
|
||||
futgo = fut.MoveNext();
|
||||
}
|
||||
else if(comp.Compare(fut.Current.Item1, spr.Current.Item1) > 0)
|
||||
{
|
||||
action(SecurityType.Spread, spr.Current.Item1, spr.Current.Item2.Replace('\u0001', '|'));
|
||||
}
|
||||
if (sprgo)
|
||||
sprgo = spr.MoveNext();
|
||||
}
|
||||
else
|
||||
{
|
||||
action(SecurityType.Future, fut.Current.Item1, fut.Current.Item2.Replace('\u0001', '|'));
|
||||
if (futgo)
|
||||
futgo = fut.MoveNext();
|
||||
action(SecurityType.Spread, spr.Current.Item1, spr.Current.Item2.Replace('\u0001', '|'));
|
||||
if (sprgo)
|
||||
sprgo = spr.MoveNext();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user