trying another way
This commit is contained in:
1 parent
333acf0822
commit
a3a8eb14ad
37 files changed
+428
-1651
No files matched your search
@@ -18,7 +18,6 @@ namespace bts.history
|
||||
MarketDataIncrementalRefresh packet);
|
||||
void process_trades(string security_desc, uint security_key, IEnumerable<co2.TradeMessage> trades,
|
||||
MarketDataIncrementalRefresh packet);
|
||||
IMatchingModel matching_model { get; }
|
||||
}
|
||||
|
||||
abstract public partial class AlgoBase : IAlgo
|
||||
@@ -30,16 +29,16 @@ namespace bts.history
|
||||
public Action<FillEntry> on_fill;
|
||||
public Action<OrderStatus> on_status;
|
||||
|
||||
protected IMatchingModel _matching_model;
|
||||
public IMatchingModel matching_model => _matching_model;
|
||||
protected IOrderSink _sink;
|
||||
public IOrderSink sink => _sink;
|
||||
|
||||
readonly protected SortedDictionary< string, Func<MDEntry, OrderIDEntry, bool> > _filter = new SortedDictionary<string, Func<MDEntry, OrderIDEntry, bool>>();
|
||||
|
||||
protected AlgoBase(IMatchingModel matching_model, string[] security_list)
|
||||
protected AlgoBase(IOrderSink sink, string[] security_list)
|
||||
{
|
||||
on_fill = new Action<FillEntry>(f => {});
|
||||
on_status = new Action<OrderStatus>(s => {});
|
||||
this._matching_model = matching_model;
|
||||
this._sink = sink;
|
||||
this.security_list = security_list;
|
||||
foreach (var sec in security_list)
|
||||
_filter[sec] = (MDEntry md, OrderIDEntry id) => md.Symbol == sec;
|
||||
@@ -91,7 +90,7 @@ namespace bts.history
|
||||
where C : AlgoBase
|
||||
{
|
||||
var order_key = IDGenerator.next_order_id();
|
||||
var child = AlgoBase.algo_factory(typeof(C), _matching_model, security_list);
|
||||
var child = AlgoBase.algo_factory(typeof(C), _sink, security_list);
|
||||
Handle h = hookup_child(child, security_list, side, price, size, asof, more_on_fill, more_on_status, order_key);
|
||||
return h;
|
||||
}
|
||||
|
||||
@@ -8,10 +8,10 @@ namespace bts.history
|
||||
{
|
||||
public class AlgoFactory
|
||||
{
|
||||
static public IAlgo algo_factory(System.Type t, IMatchingModel matching_model,
|
||||
static public IAlgo algo_factory(System.Type t, IOrderSink sink,
|
||||
string[] security_list, string algo_params = null)
|
||||
{
|
||||
return AlgoBase.algo_factory(t, matching_model, security_list, algo_params);
|
||||
return AlgoBase.algo_factory(t, sink, security_list, algo_params);
|
||||
}
|
||||
static public void set_algo_params(IAlgo inst, string algo_params)
|
||||
{
|
||||
@@ -24,10 +24,10 @@ namespace bts.history
|
||||
}
|
||||
abstract partial class AlgoBase
|
||||
{
|
||||
static public AlgoBase algo_factory(System.Type t, IMatchingModel matching_model,
|
||||
static public AlgoBase algo_factory(System.Type t, IOrderSink sink,
|
||||
string[] security_list, string algo_params = null)
|
||||
{
|
||||
AlgoBase inst = inst = (AlgoBase)Activator.CreateInstance(t, matching_model, security_list);
|
||||
AlgoBase inst = inst = (AlgoBase)Activator.CreateInstance(t, sink, security_list);
|
||||
|
||||
if(algo_params != null)
|
||||
set_algo_params(inst, algo_params);
|
||||
|
||||
@@ -1,170 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using bts.api;
|
||||
using MathNet.Numerics.Statistics;
|
||||
using mbts.co2;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
class AlgoStatsWrapper
|
||||
{
|
||||
readonly Queue<FillEntry> _tradelog = new Queue<FillEntry>();
|
||||
readonly Queue<FillEntry> _market_tradelog = new Queue<FillEntry>();
|
||||
DateTime _tradedate = DateTime.Now;
|
||||
readonly string _symbol;
|
||||
readonly SecurityType _securitytype;
|
||||
|
||||
readonly SortedDictionary<string, TradeStats> _stats = new SortedDictionary<string, TradeStats>();
|
||||
public IEnumerable<TradeStats> stats => _stats.Values;
|
||||
|
||||
readonly AlgoBase _algo;
|
||||
public AlgoBase algo => _algo;
|
||||
|
||||
readonly IReadOnlyDictionary<string, IOrderBook> _books;
|
||||
readonly StreamWriter _fs;
|
||||
|
||||
public AlgoStatsWrapper(AlgoBase algo, IReadOnlyDictionary<string, IOrderBook> shared_book, HistoricalDataOptions options)
|
||||
{
|
||||
_algo = algo;
|
||||
_books = shared_book;
|
||||
foreach (var sec in algo.security_list)
|
||||
{
|
||||
_stats[sec] = new TradeStats();
|
||||
shared_book[sec].on_market_trade += (md) =>
|
||||
{
|
||||
foreach(var mde in md.MdEntries)
|
||||
{
|
||||
if(mde.MdEntryType == MDEntryType.Trade)
|
||||
{
|
||||
//opposite the aggressor
|
||||
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(md.timestamp(), 0, mde.Symbol, side, mde.MdEntryPx, mde.LastQty, null, null, "Market");
|
||||
FillEntry ent = new FillEntry(md.timestamp(), ord, side, mde.MdEntryPx, mde.LastQty);
|
||||
var b = shared_book[sec];
|
||||
ent.bidsize = b.current_book.bidsize_at(0);
|
||||
ent.bid = b.current_book.bid_at(0);
|
||||
ent.ask = b.current_book.ask_at(0);
|
||||
ent.asksize = b.current_book.asksize_at(0);
|
||||
_market_tradelog.Enqueue(ent);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
algo.on_fill +=
|
||||
f => _tradelog.Enqueue(f);
|
||||
_symbol = options.replaysymbol;
|
||||
_securitytype = (SecurityType)Enum.Parse(typeof(SecurityType), options.replaysecuritytype);
|
||||
_tradedate = DateTime.Parse(options.replaystart);
|
||||
var path = DataDownloader.data_path(_tradedate.Date);
|
||||
new FileInfo(path).Directory.Create();
|
||||
_fs = new StreamWriter(
|
||||
File.Open(path + $"/{_symbol}_{_securitytype}_{algo.GetType().Name}_{algo.matching_model.latency_bucket.LowerBound.ToString("0") }_trades.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite) );
|
||||
}
|
||||
|
||||
void do_stats()
|
||||
{
|
||||
foreach (var pair in _stats)
|
||||
{
|
||||
var stats = pair.Value;
|
||||
var buys = _tradelog.Where(x => x.side == Side.Buy && x.order.security_desc == pair.Key);
|
||||
var nbuys = buys.Count();
|
||||
var buysize = buys.Sum(x => (int)x.size);
|
||||
var buyprice = buys.Sum(x => x.price);
|
||||
|
||||
var sells = _tradelog.Where(x => x.side == Side.Sell && x.order.security_desc == pair.Key);
|
||||
var nsells = sells.Count();
|
||||
var sellsize = sells.Sum(x => (int)x.size);
|
||||
var sellprice = sells.Sum(x => x.price);
|
||||
|
||||
stats.our_average_buy_piq = stats.our_average_buy_piq * stats.our_total_buys + buys.Where(x => x.piq > 0).Sum(x => (double)x.piq);
|
||||
stats.our_average_buy_q_len = stats.our_average_buy_q_len * stats.our_total_buys + buys.Where(x => x.queue_len > 0).Sum(x => (double)x.queue_len);
|
||||
stats.our_average_buy_price = stats.our_average_buy_price * stats.our_total_buys + buys.Sum(x => x.price);
|
||||
stats.our_total_buys += nbuys;
|
||||
if (stats.our_total_buys > 0)
|
||||
{
|
||||
stats.our_average_buy_piq /= stats.our_total_buys;
|
||||
stats.our_average_buy_q_len /= stats.our_total_buys;
|
||||
stats.our_average_buy_price /= stats.our_total_buys;
|
||||
}
|
||||
|
||||
stats.our_average_sell_piq = stats.our_average_sell_piq * stats.our_total_sells + sells.Where(x => x.piq > 0).Sum(x => (double)x.piq);
|
||||
stats.our_average_sell_q_len = stats.our_average_sell_q_len * stats.our_total_sells + sells.Where(x => x.queue_len > 0).Sum(x => (double)x.queue_len);
|
||||
stats.our_average_sell_price = stats.our_average_sell_price * stats.our_total_sells + sells.Sum(x => x.price);
|
||||
stats.our_total_sells += nsells;
|
||||
if (stats.our_total_sells > 0)
|
||||
{
|
||||
stats.our_average_sell_piq /= stats.our_total_sells;
|
||||
stats.our_average_sell_q_len /= stats.our_total_sells;
|
||||
stats.our_average_sell_price /= stats.our_total_sells;
|
||||
}
|
||||
|
||||
stats.our_total_volume += _tradelog.Where(x => x.order.security_desc == pair.Key).Sum(x => (int)x.size);
|
||||
|
||||
var pnl = compute_pnl();
|
||||
stats.latest_pnl = pnl;
|
||||
}
|
||||
}
|
||||
|
||||
public void reset()
|
||||
{
|
||||
do_stats();
|
||||
|
||||
List<FillEntry> fills = new List<FillEntry>();
|
||||
while(_tradelog.Count > 0)
|
||||
{
|
||||
var t = _tradelog.Dequeue();
|
||||
fills.Add(t);
|
||||
}
|
||||
while (_market_tradelog.Count > 0)
|
||||
{
|
||||
var t = _market_tradelog.Dequeue();
|
||||
fills.Add(t);
|
||||
}
|
||||
fills.Sort( Comparer<FillEntry>.Create( (x, y) => x.TransactTime.compare(y.TransactTime) ) );
|
||||
foreach(var t in fills)
|
||||
_fs.WriteLine(t.ToString());
|
||||
_fs.Flush();
|
||||
}
|
||||
|
||||
public void keep_md_stats(IOrderBook ob)
|
||||
{
|
||||
var stats = _stats[ob.security_desc];
|
||||
stats.total_exchange_volume = ob.total_exchange_volume;
|
||||
stats.total_exchange_bought = ob.total_exchange_bought;
|
||||
stats.total_exchange_sold = ob.total_exchange_sold;
|
||||
stats.last_trade_size = ob.last_trade_size;
|
||||
stats.last_trade_price = ob.last_trade_price;
|
||||
stats.security_timestamp = ob.security_timestamp;
|
||||
stats.security_desc = ob.security_desc;
|
||||
stats.best_bid = ob.current_book.bid_at(0);
|
||||
stats.best_ask = ob.current_book.ask_at(0);
|
||||
stats.best_bid_size = ob.current_book.bidsize_at(0);
|
||||
stats.best_ask_size = ob.current_book.asksize_at(0);
|
||||
}
|
||||
|
||||
public double compute_pnl()
|
||||
{
|
||||
double cost = 0.0, proceeds = 0.0;
|
||||
ulong buys = 0, sells = 0;
|
||||
foreach (var t in _tradelog)
|
||||
{
|
||||
if (t.side == Side.Buy)
|
||||
{
|
||||
cost += t.price * t.size;
|
||||
buys += t.size;
|
||||
}
|
||||
else if (t.side == Side.Sell)
|
||||
{
|
||||
proceeds += t.price * t.size;
|
||||
sells += t.size;
|
||||
}
|
||||
}
|
||||
|
||||
var pnl = proceeds - cost;
|
||||
return pnl;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ namespace bts.history
|
||||
}
|
||||
}
|
||||
}
|
||||
public CompositeBase(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list)
|
||||
public CompositeBase(IOrderSink sink, string[] security_list) : base(sink, security_list)
|
||||
{
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ namespace bts.history
|
||||
|
||||
public abstract class CompositeAlgo<Child> : CompositeBase<Child, NullAlgo>
|
||||
{
|
||||
public CompositeAlgo(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public CompositeAlgo(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
|
||||
public override bool is_completed()
|
||||
{
|
||||
@@ -131,11 +131,11 @@ namespace bts.history
|
||||
{
|
||||
protected int _payupcount;
|
||||
protected Dictionary<Handle, Hedge> _hedges = new Dictionary<Handle, Hedge>();
|
||||
public CompositeHedgeAlgo(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) {}
|
||||
public CompositeHedgeAlgo(IOrderSink sink, string[] security_list) : base(sink, security_list) {}
|
||||
|
||||
protected virtual bool are_hedges_out()
|
||||
{
|
||||
return _matching_model.operations_are_in_flight;
|
||||
return _sink.operations_are_in_flight;
|
||||
}
|
||||
|
||||
public override bool is_completed()
|
||||
|
||||
@@ -12,22 +12,16 @@ namespace bts.history
|
||||
where Child : AlgoBase
|
||||
where Hedge : AlgoBase
|
||||
{
|
||||
public CoverAlgo(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public CoverAlgo(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
|
||||
//algo state
|
||||
private MarketDataIncrementalRefresh _packet;
|
||||
string[] _security_list;
|
||||
|
||||
//algo parameters
|
||||
public uint hedge_ticks { get; set; } = 1;
|
||||
public double hedge_ticks { get; set; } = 1;
|
||||
public double hedge_factor { get; set; } = 1.0;
|
||||
|
||||
public double tick_size(string security_desc)
|
||||
{
|
||||
var b = _matching_model.tick_size(security_desc);
|
||||
return b;
|
||||
}
|
||||
|
||||
protected override void do_launch(string[] security_list, Side side, double price, uint size, Timestamp asof, ulong order_key)
|
||||
{
|
||||
_security_list = security_list;
|
||||
@@ -57,8 +51,8 @@ namespace bts.history
|
||||
var side = Utils.opposite_side(fill.order.side);
|
||||
uint size = (uint)(fill.size*this.hedge_factor);
|
||||
double price = (side == Side.Buy) ?
|
||||
fill.price - this.tick_size(fill.order.security_desc) * this.hedge_ticks :
|
||||
fill.price + this.tick_size(fill.order.security_desc) * this.hedge_ticks;
|
||||
fill.price - this.hedge_ticks :
|
||||
fill.price + this.hedge_ticks;
|
||||
|
||||
send_hedge(fill.order.security_desc, side, price, size, fill.TransactTime);
|
||||
}
|
||||
|
||||
@@ -23,9 +23,8 @@ namespace bts.history
|
||||
|
||||
co2.BookMessage _snapshot, _currentbook;
|
||||
int _turncount, _pilecount;
|
||||
(int, int) _piq;
|
||||
|
||||
public JoinAlgo(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public JoinAlgo(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
//algo parameters
|
||||
public bool initial_pile { get; set; } = false;
|
||||
public bool should_chase { get; set; } = true;
|
||||
@@ -50,7 +49,7 @@ namespace bts.history
|
||||
public override object report()
|
||||
{
|
||||
var b = base.report();
|
||||
return $"{b} Turns,Piles,Join(Size,Price,piq)={_turncount},{_pilecount},({_status?.state?.Quantity},{_status?.state?.Price},{_piq})";
|
||||
return $"{b} Turns,Piles,Join(Size,Price,piq)={_turncount},{_pilecount},({_status?.state?.Quantity},{_status?.state?.Price})";
|
||||
}
|
||||
|
||||
protected override void on_child_status(Handle child, OrderStatus stat)
|
||||
@@ -143,12 +142,10 @@ namespace bts.history
|
||||
if(_child == null)
|
||||
{
|
||||
_child = this.activate<Child>(new[]{security_desc}, _myside, joinprice, _mysize, packet.timestamp());
|
||||
_piq = _matching_model.get_my_piq(security_desc, _child.order_key);
|
||||
}
|
||||
else
|
||||
{
|
||||
_child.update(packet.timestamp(), joinprice);
|
||||
_piq = _matching_model.get_my_piq(security_desc, _child.order_key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ namespace bts.history
|
||||
co2.BookMessage _snapshot, _currentbook;
|
||||
int _payupcount;
|
||||
|
||||
public LeanAlgo(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public LeanAlgo(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
//algo parameters
|
||||
public double lean_factor { get; set; } = 3.0;
|
||||
public uint lean_quantity { get; set; } = 0;
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace bts.history
|
||||
{
|
||||
public class LimitOrder : AlgoBase
|
||||
{
|
||||
public LimitOrder(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public LimitOrder(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
|
||||
protected OrderEntry _myorder;
|
||||
OrderStatus _status;
|
||||
@@ -33,19 +33,19 @@ namespace bts.history
|
||||
};
|
||||
Log.assert(_myorder == null);
|
||||
_myorder = new OrderEntry(asof, order_key, security_desc, side, price, size, fill_action, status_action);
|
||||
_matching_model.send(_myorder);
|
||||
_sink.send(_myorder);
|
||||
}
|
||||
protected override void do_update(Timestamp asof, double price, uint size = uint.MinValue)
|
||||
{
|
||||
if(size == _mysize)
|
||||
size = uint.MinValue;
|
||||
_matching_model.update(_myorder.security_desc, asof, _myorder.order_id, price, size);
|
||||
_sink.update(_myorder.security_desc, asof, _myorder.order_id, price, size);
|
||||
}
|
||||
protected override void do_cancel(Timestamp asof)
|
||||
{
|
||||
if(_myorder == null)
|
||||
return;
|
||||
_matching_model.cancel(_myorder.security_desc, asof, _myorder.order_id);
|
||||
_sink.cancel(_myorder.security_desc, asof, _myorder.order_id);
|
||||
}
|
||||
|
||||
public override bool is_completed() => _status?.is_terminal() ?? false;
|
||||
|
||||
@@ -7,7 +7,7 @@ namespace bts.history
|
||||
{
|
||||
public class MarketOrder : LimitOrder
|
||||
{
|
||||
public MarketOrder(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public MarketOrder(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
|
||||
protected override void do_launch(string[] security_list, api.Side side, double price, uint size, Timestamp asof, ulong order_key)
|
||||
{
|
||||
|
||||
@@ -37,8 +37,8 @@ namespace bts.history
|
||||
OrderEntry _fake_order_for_status;
|
||||
|
||||
|
||||
public NativeAlgo(IMatchingModel matching_model, string[] security_list,
|
||||
api.orderman.OrderDefinition def) : base(matching_model, security_list)
|
||||
public NativeAlgo(IOrderSink sink, string[] security_list,
|
||||
api.orderman.OrderDefinition def) : base(sink, security_list)
|
||||
{
|
||||
_def = def;
|
||||
unsafe
|
||||
@@ -127,14 +127,14 @@ namespace bts.history
|
||||
{
|
||||
case api.orderman.CustomOrderDefinition.CustomOneofCase.Market:
|
||||
{
|
||||
var child = AlgoBase.algo_factory(typeof(MarketOrder), _matching_model, this.security_list);
|
||||
var child = AlgoBase.algo_factory(typeof(MarketOrder), _sink, this.security_list);
|
||||
hookup_child(child, this.security_list, def.Side, price, size, _myasof, order_key);
|
||||
}
|
||||
break;
|
||||
case api.orderman.CustomOrderDefinition.CustomOneofCase.Limit:
|
||||
case api.orderman.CustomOrderDefinition.CustomOneofCase.GlbxIceberg:
|
||||
{
|
||||
var child = AlgoBase.algo_factory(typeof(LimitOrder), _matching_model, this.security_list);
|
||||
var child = AlgoBase.algo_factory(typeof(LimitOrder), _sink, this.security_list);
|
||||
hookup_child(child, this.security_list, def.Side, price, size, _myasof, order_key);
|
||||
}
|
||||
break;
|
||||
@@ -153,7 +153,7 @@ namespace bts.history
|
||||
if(native != IntPtr.Zero)
|
||||
{
|
||||
AlgoTestNativeMethods.destroy_algo(native); //TODO, boolean
|
||||
var child = new NativeAlgo(_matching_model, this.security_list, def);
|
||||
var child = new NativeAlgo(_sink, this.security_list, def);
|
||||
hookup_child(child, this.security_list, def.Side, price, size, _myasof, order_key);
|
||||
// var handle = this.hookup_child(child, security_list, def.Side, price, size, _myasof, null, null, order_key);
|
||||
// _children.Add(handle);
|
||||
@@ -217,8 +217,9 @@ namespace bts.history
|
||||
LastMsg = curr.LastMsg,
|
||||
LastPrice = curr.LastPrice
|
||||
};
|
||||
_fake_order_for_status.last_change = curr.LastChange;
|
||||
OrderStatus agg = new OrderStatus(_fake_order_for_status, aggstate);
|
||||
agg.TransactTime = curr.LastChange;
|
||||
agg.SendingTime = curr.LastChange;
|
||||
if (this.on_status != null)
|
||||
this.on_status(agg);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ namespace bts.history
|
||||
{
|
||||
public class NullAlgo : AlgoBase
|
||||
{
|
||||
public NullAlgo(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public NullAlgo(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
public override bool is_completed() => true;
|
||||
|
||||
public override object report() { return string.Empty; }
|
||||
|
||||
+8
-7
@@ -8,7 +8,7 @@ using mbts.co2;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public class RoundTripAlgo<Child, Hedge> : CompositeHedgeAlgo<Child, Hedge>
|
||||
public class SpreaderAlgo<Child, Hedge> : CompositeHedgeAlgo<Child, Hedge>
|
||||
where Child : AlgoBase
|
||||
where Hedge : AlgoBase
|
||||
{
|
||||
@@ -33,7 +33,7 @@ namespace bts.history
|
||||
|
||||
private MarketDataIncrementalRefresh _packet;
|
||||
|
||||
public RoundTripAlgo(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public SpreaderAlgo(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
//algo parameters
|
||||
public double lean_factor { get; set; } = 1.0;
|
||||
public int profit_ticks { get; set; } = 1;
|
||||
@@ -83,9 +83,10 @@ namespace bts.history
|
||||
{
|
||||
var b = base.report();
|
||||
string qtleg = _security_list.Last();
|
||||
var buypiq = _matching_model.get_my_piq(qtleg, _buychild?.order_key ?? 0);
|
||||
var sellpiq = _matching_model.get_my_piq(qtleg, _sellchild?.order_key ?? 0);
|
||||
return $"{b} Quoting {_quote_leg} (bsz,bpx,bpiq ssz,spx,spiq) = ( {_buystatus?.state?.Quantity},{_buystatus?.state?.Price},{buypiq} at {_sellstatus?.state?.Quantity},{_sellstatus?.state?.Price},{sellpiq} )";
|
||||
// var buypiq = _sink.get_my_piq(qtleg, _buychild?.order_key ?? 0);
|
||||
// var sellpiq = _sink.get_my_piq(qtleg, _sellchild?.order_key ?? 0);
|
||||
// return $"{b} Quoting {_quote_leg} (bsz,bpx,bpiq ssz,spx,spiq) = ( {_buystatus?.state?.Quantity},{_buystatus?.state?.Price},{buypiq} at {_sellstatus?.state?.Quantity},{_sellstatus?.state?.Price},{sellpiq} )";
|
||||
return b;
|
||||
}
|
||||
|
||||
protected override void on_child_status(Handle child, OrderStatus stat)
|
||||
@@ -94,13 +95,13 @@ namespace bts.history
|
||||
{
|
||||
_buystatus = stat;
|
||||
if(stat.is_terminal())
|
||||
_sellchild?.cancel(_buystatus.timestamp);
|
||||
_sellchild?.cancel(_buystatus.SendingTime);
|
||||
}
|
||||
else
|
||||
{
|
||||
_sellstatus = stat;
|
||||
if(stat.is_terminal())
|
||||
_buychild?.cancel(_sellstatus.timestamp);
|
||||
_buychild?.cancel(_sellstatus.SendingTime);
|
||||
}
|
||||
//hedges are looked after elsewhere
|
||||
if( (_buystatus?.is_terminal() ?? true) && (_sellstatus?.is_terminal() ?? true) )
|
||||
@@ -23,7 +23,7 @@ namespace bts.history
|
||||
co2.BookMessage _currentbook;
|
||||
int _topcount;
|
||||
|
||||
public TopAlgo(IMatchingModel matching_model, string[] security_list) : base(matching_model, security_list) { }
|
||||
public TopAlgo(IOrderSink sink, string[] security_list) : base(sink, security_list) { }
|
||||
//algo parameters
|
||||
public double top_factor { get; set; } = 1.0;
|
||||
public uint top_quantity { get; set; } = 0;
|
||||
|
||||
@@ -11,32 +11,32 @@ namespace bts.history
|
||||
|
||||
public class JoinCoverLean : CoverAlgo<JoinAlgo<TopAlgo<LimitOrder>>, LeanAlgo<LimitOrder>>
|
||||
{
|
||||
public JoinCoverLean(IMatchingModel matching_model, string[] security_list)
|
||||
: base(matching_model, security_list)
|
||||
public JoinCoverLean(IOrderSink sink, string[] security_list)
|
||||
: base(sink, security_list)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class PegCoverLean : CoverAlgo<JoinAlgo<TopAlgo<LimitOrder>>, LeanAlgo<LimitOrder>>
|
||||
{
|
||||
public PegCoverLean(IMatchingModel matching_model, string[] security_list)
|
||||
: base(matching_model, security_list)
|
||||
public PegCoverLean(IOrderSink sink, string[] security_list)
|
||||
: base(sink, security_list)
|
||||
{
|
||||
this.set_param(nameof(JoinAlgo<LimitOrder>.initial_pile), true.ToString());
|
||||
}
|
||||
}
|
||||
public class RoundTrip : RoundTripAlgo<LimitOrder, LeanAlgo<LimitOrder>>
|
||||
public class Spreader : SpreaderAlgo<LimitOrder, LeanAlgo<LimitOrder>>
|
||||
{
|
||||
public RoundTrip(IMatchingModel matching_model, string[] security_list)
|
||||
: base(matching_model, security_list)
|
||||
public Spreader(IOrderSink sink, string[] security_list)
|
||||
: base(sink, security_list)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public class TWAP : NativeAlgo
|
||||
{
|
||||
public TWAP(IMatchingModel matching_model, string[] security_list)
|
||||
: base(matching_model, security_list, build_def())
|
||||
public TWAP(IOrderSink sink, string[] security_list)
|
||||
: base(sink, security_list, build_def())
|
||||
{
|
||||
}
|
||||
static api.orderman.OrderDefinition build_def()
|
||||
|
||||
@@ -1,132 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using MathNet.Numerics.Statistics;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
sealed class AlgoAnalyzer : IAnalyzer
|
||||
{
|
||||
const double _max_nanos = 500_000.0;
|
||||
readonly DistributionEstimator _dist = new DistributionEstimator();
|
||||
readonly Histogram _hist = new Histogram();
|
||||
|
||||
readonly Dictionary<Bucket, AlgoStatsWrapper> _algos = new Dictionary<Bucket, AlgoStatsWrapper>();
|
||||
readonly SortedDictionary<string, IOrderBook> _shared_order_book = new SortedDictionary<string, IOrderBook>();
|
||||
|
||||
string[] _security_list;
|
||||
public AlgoAnalyzer(HistoricalDataOptions options, System.Type algotype, string algo_params)
|
||||
{
|
||||
Log.assert(!string.IsNullOrEmpty(options.algo_security));
|
||||
_security_list = new string[] { options.algo_security };
|
||||
if (options.algo_security.Contains(';'))
|
||||
_security_list = options.algo_security.Split(';');
|
||||
|
||||
foreach(var sec in _security_list)
|
||||
{
|
||||
_shared_order_book[sec] = new OrderBook(sec);
|
||||
}
|
||||
foreach (var hist in new[] { _hist } )
|
||||
{
|
||||
hist.AddBucket(new Bucket(0, 1000.0.Decrement()));
|
||||
// hist.AddBucket(new Bucket(1000, 5000.0.Decrement()));
|
||||
// hist.AddBucket(new Bucket(5000, 10000.0.Decrement()));
|
||||
// hist.AddBucket(new Bucket(10000, 20000.0.Decrement()));
|
||||
// hist.AddBucket(new Bucket(20000, 30000.0.Decrement()));
|
||||
// hist.AddBucket(new Bucket(30000, 40000.0.Decrement()));
|
||||
// hist.AddBucket(new Bucket(40000, 50000.0.Decrement()));
|
||||
// hist.AddBucket(new Bucket(50000, 80000.0.Decrement()));
|
||||
// hist.AddBucket(new Bucket(80000, (_max_nanos/2).Decrement()));
|
||||
// hist.AddBucket(new Bucket(_max_nanos/2, _max_nanos.Decrement()));
|
||||
hist.LazySort();
|
||||
for(int i = 0; i < hist.BucketCount; i++)
|
||||
{
|
||||
var buck = hist[i];
|
||||
var matching_model = new FIFOMatchingModel(_shared_order_book, buck);
|
||||
var algo = AlgoBase.algo_factory(algotype, matching_model, _security_list, algo_params);
|
||||
_algos.Add(buck, new AlgoStatsWrapper( algo, _shared_order_book, options ) );
|
||||
activate_algo(algo);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void activate_algo(AlgoBase algo) //relies on CompositeAlgo to know I'm trying to activate my same type
|
||||
{
|
||||
api.Side side = api.Side.Undefined; double price = 0.0; uint size = 0;
|
||||
if (algo.algo_params.TryGetValue(nameof(side), out string sside))
|
||||
side = (api.Side) System.Enum.Parse(typeof(api.Side), sside, true);
|
||||
|
||||
if (algo.algo_params.TryGetValue(nameof(price), out string sprice))
|
||||
price = double.Parse(sprice);
|
||||
if (algo.algo_params.TryGetValue(nameof(size), out string ssize))
|
||||
size = uint.Parse(ssize);
|
||||
AlgoBase.activate_self(algo, side, price, size, Timestamp.FromDateTime(DateTime.UtcNow));
|
||||
}
|
||||
|
||||
public void pre_analyze(MarketDataIncrementalRefresh md, string debug_fix = null)
|
||||
{
|
||||
process_md(md, debug_fix);
|
||||
}
|
||||
|
||||
int _samples;
|
||||
MarketDataIncrementalRefresh _lastpacket = new MarketDataIncrementalRefresh();
|
||||
public void analyze(MarketDataIncrementalRefresh md, string debug_fix = null)
|
||||
{
|
||||
//get the books right
|
||||
process_md(md, debug_fix);
|
||||
|
||||
foreach(var ob in _shared_order_book)
|
||||
{
|
||||
//the last known good book from the last quote event indicator
|
||||
co2.BookMessage working_book = ob.Value.working_book;
|
||||
//the working book, with all msgs between working_book and now
|
||||
co2.BookMessage current_book = ob.Value.current_book;
|
||||
List<co2.TradeMessage> trades = ((OrderBook)ob.Value).process_market_trades(md, (mde, ore) => ob.Key == mde.Symbol);
|
||||
foreach (var algo in _algos)
|
||||
{
|
||||
//check the market data for a 'catalyst' with (potential) latency
|
||||
algo.Value.algo.process_book(ob.Key, ob.Value.security_key, current_book, working_book, md);
|
||||
algo.Value.algo.process_trades(ob.Key, ob.Value.security_key, trades, md);
|
||||
algo.Value.keep_md_stats(ob.Value);
|
||||
}
|
||||
}
|
||||
|
||||
if (_samples++ % 1000 == 0)
|
||||
{
|
||||
var dt = md.timestamp().ToDateTime();
|
||||
Console.WriteLine($"{_security_list.Aggregate( (x,y) => x + " " + y)} {_samples } Trade date {dt.ToShortDateString()} {dt.ToLongTimeString()}");
|
||||
var first = _algos.First().Value;
|
||||
var last = _algos.Last().Value;
|
||||
var lf = Environment.NewLine;
|
||||
var group = new []{"best","total","our", "security"};
|
||||
Console.WriteLine($"{first.GetType().Name} Best Stats: {_algos.First().Key.UpperBound} {first.algo.report()}{lf}{Stringizer.all_to_string(first.stats, group)} ");
|
||||
Console.WriteLine($"{last.GetType().Name} Worst Stats: {_algos.Last().Key.UpperBound} {last.algo.report()}{lf}{Stringizer.all_to_string(last.stats, group)}");
|
||||
Console.WriteLine($"{ _hist.ToString() }");
|
||||
Console.WriteLine($"-----------------------------------------------------------------------------");
|
||||
}
|
||||
foreach (var algo in _algos)
|
||||
{
|
||||
if (algo.Value.algo.is_completed())
|
||||
{
|
||||
Log.Testing.info("cleanup_function " + algo.Key.UpperBound);
|
||||
var pnl = algo.Value.compute_pnl();
|
||||
algo.Value.reset();
|
||||
algo.Key.Count += pnl;
|
||||
activate_algo(algo.Value.algo);
|
||||
}
|
||||
}
|
||||
_lastpacket = md;
|
||||
}
|
||||
void process_md(MarketDataIncrementalRefresh md, string debug_fix = null)
|
||||
{
|
||||
foreach (var ob in _shared_order_book)
|
||||
{
|
||||
OrderBook book = (OrderBook)ob.Value;
|
||||
book.process_md(md,
|
||||
(mde, ord) => mde.Symbol == ob.Key,
|
||||
debug_fix);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,218 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using bts.api;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using bts.co2;
|
||||
using mbts.co2;
|
||||
|
||||
using QueueType = System.Collections.Generic.SortedList<ulong, bts.history.OrderEntry>;
|
||||
using MathNet.Numerics.Statistics;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public delegate void OnMarketTrade(MarketDataIncrementalRefresh md);
|
||||
public interface IOrderBook
|
||||
{
|
||||
string security_desc { get; }
|
||||
uint security_key { get; }
|
||||
DateTime security_timestamp { get; }
|
||||
BookMessage working_book { get; }
|
||||
BookMessage current_book { get; }
|
||||
|
||||
event OnMarketTrade on_market_trade;
|
||||
|
||||
uint total_exchange_volume { get; }
|
||||
uint total_exchange_bought { get; }
|
||||
uint total_exchange_sold { get; }
|
||||
uint last_trade_size { get; }
|
||||
double last_trade_price { get; }
|
||||
|
||||
(int, int) get_my_piq(ulong orderid);
|
||||
OrderEntry insert_my_order(OrderEntry order);
|
||||
OrderEntry change_my_order(Timestamp asof, ulong order_id, double price, uint size = uint.MinValue);
|
||||
bool cancel_my_order(Timestamp asof, ulong my_order_id);
|
||||
void match_our_trades(MarketDataIncrementalRefresh md);
|
||||
void match_crosses(Timestamp ts);
|
||||
MBOBook mbo_book {get;}
|
||||
}
|
||||
|
||||
class OrderBook : IOrderBook
|
||||
{
|
||||
|
||||
public string security_desc { get; private set; }
|
||||
public uint security_key { get; private set; }
|
||||
|
||||
BookMessage _working_book = new BookMessage(), _current_book = new BookMessage();
|
||||
public BookMessage current_book => _current_book;
|
||||
public BookMessage working_book => _working_book;
|
||||
public event OnMarketTrade on_market_trade;
|
||||
|
||||
public uint total_exchange_volume { get; private set; }
|
||||
public uint total_exchange_bought { get; private set; }
|
||||
public uint total_exchange_sold { get; private set; }
|
||||
public uint last_trade_size { get; private set; }
|
||||
public double last_trade_price { get; private set; }
|
||||
public DateTime security_timestamp { get; private set; }
|
||||
|
||||
readonly MBOBook _mbo;
|
||||
public MBOBook mbo_book => _mbo;
|
||||
|
||||
public OrderBook(string security_desc)
|
||||
{
|
||||
this.security_desc = security_desc;
|
||||
_mbo = new MBOBook(security_desc);
|
||||
Utils.init_book(_working_book);
|
||||
Utils.init_book(_current_book);
|
||||
}
|
||||
|
||||
public void process_md(MarketDataIncrementalRefresh md, Func<MDEntry, OrderIDEntry, bool> filter, string debug_fix = null)
|
||||
{
|
||||
bool bidoffer = false, trade = false;
|
||||
foreach (var entry in md.MdEntries)
|
||||
{
|
||||
if(!filter(entry, null))
|
||||
continue;
|
||||
if (this.security_key == 0)
|
||||
this.security_key = entry.SecurityId;
|
||||
if (entry.MdEntryType == MDEntryType.Bid || entry.MdEntryType == MDEntryType.Offer)
|
||||
{
|
||||
Utils.keep_book(_working_book, entry);
|
||||
if (Utils.quote_event_done(md)) //end of event https://www.cmegroup.com/confluence/display/EPICSANDBOX/MDP+3.0+-+Market+Data+Incremental+Refresh
|
||||
{
|
||||
_current_book = _working_book.Clone();
|
||||
Utils.validate_book(_current_book, debug_fix);
|
||||
}
|
||||
bidoffer = true;
|
||||
}
|
||||
else if(entry.MdEntryType == MDEntryType.Trade)
|
||||
{
|
||||
trade = true;
|
||||
}
|
||||
}
|
||||
this.security_timestamp = md.timestamp().ToDateTime();
|
||||
Log.assert( !(bidoffer && trade), "Saw trade and bids / offers in same md packet");
|
||||
if(bidoffer)
|
||||
process_orders(md, filter);
|
||||
}
|
||||
|
||||
|
||||
void process_orders(MarketDataIncrementalRefresh md, Func<MDEntry, OrderIDEntry, bool> filter)
|
||||
{
|
||||
foreach (var order in md.OrderIdEntries)
|
||||
{
|
||||
if (order.ReferenceId == 0)
|
||||
continue;
|
||||
// entries is indexed by 0 but ref is indexed by 1 :facepalm:
|
||||
int mdidx = ((int)order.ReferenceId) - 1;
|
||||
Log.assert((mdidx <= md.MdEntries.Count));
|
||||
|
||||
MDEntry mdval = md.MdEntries[mdidx];
|
||||
if (!filter(mdval, order))
|
||||
continue;
|
||||
_mbo.process_one_mbo(md.timestamp(), MBOUtils.make_mbo(md, mdval, order));
|
||||
}
|
||||
foreach (var mdval in md.MdEntries)
|
||||
{
|
||||
if (mdval.OrderId > 0 && md.OrderIdEntries.Count == 0)
|
||||
_mbo.process_one_mbo(md.timestamp(), MBOUtils.make_mbo(md, mdval, null));
|
||||
}
|
||||
}
|
||||
|
||||
public List<TradeMessage> process_market_trades(MarketDataIncrementalRefresh md, Func<MDEntry, OrderIDEntry, bool> filter)
|
||||
{
|
||||
bool has_trade = false;
|
||||
List<TradeMessage> list = new List<TradeMessage>();
|
||||
foreach (var entry in md.MdEntries)
|
||||
{
|
||||
if (!filter(entry, null))
|
||||
continue;
|
||||
bool trade = entry.MdEntryType == MDEntryType.Trade;
|
||||
if (trade)
|
||||
{
|
||||
this.total_exchange_volume += entry.MdEntrySize;
|
||||
if (entry.AggressorSide == 1)
|
||||
this.total_exchange_bought += entry.MdEntrySize;
|
||||
else if (entry.AggressorSide == 2)
|
||||
this.total_exchange_sold += entry.MdEntrySize;
|
||||
|
||||
this.last_trade_size = entry.MdEntrySize;
|
||||
this.last_trade_price = entry.MdEntryPx;
|
||||
|
||||
var tm = create_trade(md, entry);
|
||||
list.Add(tm);
|
||||
}
|
||||
has_trade |= trade;
|
||||
}
|
||||
if (this.on_market_trade != null)
|
||||
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;
|
||||
tm.OrderId = entry.OrderId;
|
||||
return tm;
|
||||
}
|
||||
|
||||
public (int, int) get_my_piq(ulong orderid)
|
||||
{
|
||||
return _mbo.get_my_piq(orderid);
|
||||
}
|
||||
|
||||
public OrderEntry insert_my_order(OrderEntry order)
|
||||
{
|
||||
return _mbo.insert_my_order(order);
|
||||
}
|
||||
|
||||
public OrderEntry change_my_order(Timestamp asof, ulong order_id, double price, uint size = 0)
|
||||
{
|
||||
return _mbo.change_my_order(asof, order_id, price, size);
|
||||
}
|
||||
|
||||
public bool cancel_my_order(Timestamp asof, ulong my_order_id)
|
||||
{
|
||||
return _mbo.cancel_my_order(asof, my_order_id);
|
||||
}
|
||||
|
||||
public void match_our_trades(MarketDataIncrementalRefresh md)
|
||||
{
|
||||
foreach (var trade in md.OrderIdEntries)
|
||||
{
|
||||
MDEntry tradeentry = null;
|
||||
if (trade.ReferenceId == 0)
|
||||
{
|
||||
tradeentry = md.MdEntries[0];
|
||||
tradeentry.OrderId = trade.OrderId;
|
||||
tradeentry.LastQty = trade.LastQty;
|
||||
Log.assert(tradeentry.MdEntryType == MDEntryType.Trade);
|
||||
}
|
||||
else
|
||||
{
|
||||
int mdidx = ((int)trade.ReferenceId) - 1;
|
||||
Log.assert((mdidx <= md.MdEntries.Count));
|
||||
tradeentry = md.MdEntries[mdidx];
|
||||
tradeentry.OrderId = trade.OrderId;
|
||||
tradeentry.LastQty = trade.LastQty;
|
||||
if (tradeentry.MdEntryType != MDEntryType.Trade)
|
||||
continue;
|
||||
}
|
||||
_mbo.process_one_trade(md.timestamp(), create_trade(md, tradeentry));
|
||||
}
|
||||
}
|
||||
|
||||
public void match_crosses(Timestamp ts)
|
||||
{
|
||||
_mbo.match_crosses(ts);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -42,10 +42,7 @@ namespace bts.history
|
||||
t = System.Type.GetType("bts.history." + o.algo_type);
|
||||
if (t != null)
|
||||
{
|
||||
if(typeof(AlgoBase).IsAssignableFrom(t))
|
||||
anal.Add(new AlgoAnalyzer(o, t, o.algo_params));
|
||||
else
|
||||
anal.Add((IAnalyzer)Activator.CreateInstance(t, new[] { algo_security }));
|
||||
anal.Add((IAnalyzer)Activator.CreateInstance(t, new[] { algo_security }));
|
||||
}
|
||||
else
|
||||
anal.Add(new BookAnalyzer(algo_security, o));
|
||||
|
||||
@@ -5,133 +5,93 @@ using Google.Protobuf.WellKnownTypes;
|
||||
using MathNet.Numerics.Statistics;
|
||||
using bts.co2;
|
||||
using System.Threading.Tasks;
|
||||
using bts.history;
|
||||
using mbts.co2;
|
||||
using bts.api;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public class FIFOFillModel : IFillModel
|
||||
{
|
||||
readonly SortedList<Timestamp, OrderStatus> _myorders =
|
||||
readonly SortedList<Timestamp, OrderStatus> _myorders =
|
||||
new SortedList<Timestamp, OrderStatus>(HistoricalExtensions.timestamp_comparer);
|
||||
private ILookup<ulong, MBOMessage> _exchangeorders;
|
||||
public FIFOFillModel() {}
|
||||
|
||||
public IEnumerable<MBOMessage> exchange_orders_raw { get; private set;}
|
||||
public void process_exchange_orders(IEnumerable<MBOMessage> exchange_orders)
|
||||
readonly Dictionary<ulong, List<MBOMessage>> _exchangeorders =
|
||||
new Dictionary<ulong, List<MBOMessage>>();
|
||||
|
||||
readonly Dictionary<string, co2.BookMessage> _books = new Dictionary<string, co2.BookMessage>();
|
||||
readonly Dictionary<ulong, uint> _disqual = new Dictionary<ulong, uint>();
|
||||
|
||||
public Bucket transmit_latency { get; }
|
||||
public FIFOFillModel(Bucket transmit_latency)
|
||||
{
|
||||
exchange_orders_raw = exchange_orders;
|
||||
_exchangeorders = exchange_orders.ToLookup(x => x.OrderId);
|
||||
}
|
||||
public async Task process_exchange_orders_async(IEnumerable<MBOMessage> exchange_orders)
|
||||
{
|
||||
await Task.Run( () =>
|
||||
{
|
||||
process_exchange_orders(exchange_orders);
|
||||
});
|
||||
this.transmit_latency = transmit_latency;
|
||||
}
|
||||
public IEnumerable<MBOMessage> exchange_orders_raw => _exchangeorders.SelectValues(_exchangeorders.Keys).SelectMany(x => x);
|
||||
public IEnumerable<OrderStatus> my_orders => _myorders.Values;
|
||||
public void process_my_orders(IEnumerable<OrderStatus> algo_orders)
|
||||
public event Action<FillEntry> on_fill;
|
||||
public event Action<OrderStatus> on_status;
|
||||
|
||||
public void record_order_status(OrderStatus stat)
|
||||
{
|
||||
foreach(var stat in algo_orders)
|
||||
if(!check_cross(stat))
|
||||
{
|
||||
add_order(stat);
|
||||
}
|
||||
}
|
||||
|
||||
void add_order(OrderStatus stat)
|
||||
{
|
||||
int tries = 0; bool done = false;
|
||||
while (tries++ < 99) //100 nano resolution from CME data makes this sorta ok
|
||||
{
|
||||
try
|
||||
int tries = 0; bool done = false;
|
||||
while (tries++ < 99) //100 nano resolution from CME data makes this sorta ok
|
||||
{
|
||||
_myorders.Add(stat.timestamp, stat);
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
catch (ArgumentException)
|
||||
{
|
||||
stat.timestamp.Nanos += 1;
|
||||
}
|
||||
}
|
||||
if(!done)
|
||||
throw new ArgumentOutOfRangeException("can't place 100th dupe timestamp");
|
||||
}
|
||||
|
||||
public async Task process_my_orders_async(IEnumerable<OrderStatus> algo_orders)
|
||||
{
|
||||
await Task.Run(() =>
|
||||
{
|
||||
process_my_orders(algo_orders);
|
||||
});
|
||||
}
|
||||
|
||||
public IEnumerable<FillEntry> compute_fills<T>(IEnumerable<T> trade_stream, uint reup_nanoseconds = 0,
|
||||
int framelimit = int.MaxValue)
|
||||
where T : class, IHasMBO, IHasTrade, IHasTimestamp
|
||||
{
|
||||
var q = new List<FillEntry>();
|
||||
int count = 0;
|
||||
Dictionary<ulong, uint> spent_lots = new Dictionary<ulong, uint>();
|
||||
var ienum = Query.stream_data(new[] { trade_stream }, (T[] valcache, int min) =>
|
||||
{
|
||||
q.Clear();
|
||||
var curr = valcache[min];
|
||||
if (count++ > framelimit)
|
||||
throw new System.IO.EndOfStreamException();
|
||||
|
||||
if (curr.Trade != null)
|
||||
try
|
||||
{
|
||||
Log.assert(curr.MdEntry.MdEntryType == MDEntryType.Trade);
|
||||
//q.AddRange(this.get_fills_for_trade(curr.TransactTime, curr.Trade, reup_nanoseconds));
|
||||
var trades = MBOUtils.extract_mbo(curr.Md, curr.MdEntry, curr.EntryIndex, curr.Orders);
|
||||
foreach (var trade in trades)
|
||||
{
|
||||
if (curr.Trade.OrderId != trade.OrderId)
|
||||
{
|
||||
ITradeWithOrderIDAndSize clone = curr.Trade.Clone();
|
||||
clone.OrderId = trade.OrderId;
|
||||
//price is the same
|
||||
clone.Size = trade.LastQty;
|
||||
q.AddRange(this.get_fills_for_trade(curr.TransactTime, clone, reup_nanoseconds, spent_lots));
|
||||
}
|
||||
}
|
||||
_myorders.Add(stat.TransactTime, stat);
|
||||
done = true;
|
||||
break;
|
||||
}
|
||||
return q;
|
||||
});
|
||||
return ienum;
|
||||
catch (ArgumentException)
|
||||
{
|
||||
stat.TransactTime.Nanos += 1;
|
||||
}
|
||||
}
|
||||
if (!done)
|
||||
throw new ArgumentOutOfRangeException("can't place 100th dupe timestamp");
|
||||
}
|
||||
}
|
||||
|
||||
public void process_order(Timestamp transact_time, MBOMessage mbo)
|
||||
{
|
||||
get_mbo(mbo.OrderId).Add(mbo);
|
||||
}
|
||||
|
||||
IEnumerable<FillEntry> get_fills_for_trade(Timestamp transact_time, co2.ITradeWithOrderIDAndSize trade,
|
||||
uint reup_nanoseconds, Dictionary<ulong, uint> spent_lots)
|
||||
public void process_book(Timestamp transact_time, string security_desc, BookMessage book)
|
||||
{
|
||||
_books[security_desc] = book;
|
||||
}
|
||||
|
||||
public void process_trade(Timestamp transact_time, string security_desc, ITradeWithOrderIDAndSize trade)
|
||||
{
|
||||
if(_exchangeorders == null || _myorders == null)
|
||||
throw new InvalidOperationException("uninitialized data");
|
||||
var order = _exchangeorders[trade.OrderId];
|
||||
if(order == null || !order.Any()) //can't find the order, must have been here forever, they get filled not us
|
||||
return Enumerable.Empty<FillEntry>();
|
||||
return ;
|
||||
var market_operations = order.OrderBy(x => x.TransactTime, HistoricalExtensions.timestamp_comparer).ToList();
|
||||
var market_operation_index = find_first_greater_or_equal(market_operations, transact_time, x=>x.TransactTime,
|
||||
HistoricalExtensions.timestamp_comparer);
|
||||
if(market_operation_index == 0) //transact_time is before first market operation on this order, they get filled not us
|
||||
return Enumerable.Empty<FillEntry>();
|
||||
return ;
|
||||
var curr_market_operation = market_operations[market_operation_index-1];
|
||||
Log.assert(curr_market_operation.OrderUpdateAction != MDUpdateAction.Delete); //a deleted order should not get filled
|
||||
|
||||
int our_operation_index = find_first_greater_or_equal(_myorders, transact_time, HistoricalExtensions.timestamp_comparer);
|
||||
if(our_operation_index == 0) //transact_time before I'm in the market, they get filled not us
|
||||
return Enumerable.Empty<FillEntry>();
|
||||
return ;
|
||||
|
||||
string market_secdesc = curr_market_operation.SecurityDesc;
|
||||
double market_price = curr_market_operation.MdEntryPx;
|
||||
api.Side market_side = Utils.same_side(curr_market_operation.MdEntryType);
|
||||
List<FillEntry> fills = new List<FillEntry>();
|
||||
uint fill_qty = trade.Size;
|
||||
List<OrderStatus> reup = new List<OrderStatus>();
|
||||
for(int i = our_operation_index - 1; i >= 0; i--)
|
||||
{
|
||||
//the closest operation to this trade time
|
||||
OrderStatus curr_operation = _myorders.Values[i];
|
||||
if(!curr_operation.timestamp.less_or_equal(curr_market_operation.TransactTime))
|
||||
if(!curr_operation.TransactTime.less_or_equal(curr_market_operation.TransactTime))
|
||||
{
|
||||
Log.Testing.warn("should be sorted");
|
||||
break;
|
||||
@@ -140,7 +100,7 @@ namespace bts.history
|
||||
continue;
|
||||
if(curr_operation.order.side != market_side)
|
||||
continue;
|
||||
if(spent_lots.TryGetValue(curr_operation.order.order_id, out uint spent_value) && spent_value == uint.MaxValue)
|
||||
if(_disqual.TryGetValue(curr_operation.order.order_id, out uint spent_value))
|
||||
continue;
|
||||
if (( market_side == api.Side.Buy && curr_operation.state.Price >= market_price || //fill us if we are better?
|
||||
market_side == api.Side.Sell && curr_operation.state.Price <= market_price) )
|
||||
@@ -149,24 +109,18 @@ namespace bts.history
|
||||
//if the latest state of this order is terminal, disqualify the order
|
||||
if (curr_operation.is_terminal())
|
||||
{
|
||||
spent_lots[curr_operation.order.order_id] = int.MaxValue; //this order is completely spent
|
||||
_disqual[curr_operation.order.order_id] = int.MaxValue; //this order is completely spent
|
||||
continue;
|
||||
}
|
||||
uint size = Math.Min(fill_qty, curr_operation.state.Quantity - spent_value);
|
||||
if (size > 0)
|
||||
{
|
||||
FillEntry f = new FillEntry(transact_time, curr_operation.order, market_side, curr_operation.state.Price, size);
|
||||
FillEntry f = generate_fill(transact_time, curr_operation, curr_operation.state.Price, size);
|
||||
f.SendingTime = transact_time.add_nanos((int)transmit_latency.LowerBound);
|
||||
f.fill_id = trade.OrderId;
|
||||
fills.Add(f);
|
||||
var total_spent = size + spent_value;
|
||||
if(total_spent >= curr_operation.state.Quantity)
|
||||
{
|
||||
Log.assert(total_spent == curr_operation.state.Quantity);
|
||||
spent_lots[curr_operation.order.order_id] = int.MaxValue;
|
||||
check_reup(reup_nanoseconds, curr_operation, reup);
|
||||
}
|
||||
else
|
||||
spent_lots[curr_operation.order.order_id] = total_spent;
|
||||
if(f.fully_filled)
|
||||
_disqual[curr_operation.order.order_id] = int.MaxValue; //this order is completely spent
|
||||
fill_qty -= size;
|
||||
}
|
||||
if (fill_qty <= 0)
|
||||
@@ -176,24 +130,25 @@ namespace bts.history
|
||||
}
|
||||
}
|
||||
}
|
||||
foreach(var new_order in reup)
|
||||
add_order(new_order);
|
||||
return fills;
|
||||
}
|
||||
|
||||
//simulate an iceberg on a fill
|
||||
private void check_reup(uint reup_nanoseconds, OrderStatus our_operation, List<OrderStatus> reup)
|
||||
List<MBOMessage> get_mbo(ulong id)
|
||||
{
|
||||
if (reup_nanoseconds > 0)
|
||||
if (!_exchangeorders.TryGetValue(id, out List<MBOMessage> list))
|
||||
{
|
||||
var new_order = our_operation.clone();
|
||||
new_order.timestamp = our_operation.timestamp.add_nanos((int)reup_nanoseconds);
|
||||
new_order.state.Quantity = (uint)new_order.order.size;
|
||||
reup.Add(new_order);
|
||||
_exchangeorders[id] = list = new List<MBOMessage>();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
co2.BookMessage get_book(string security_desc)
|
||||
{
|
||||
if (!_books.TryGetValue(security_desc, out co2.BookMessage book))
|
||||
{
|
||||
_books[security_desc] = book = new co2.BookMessage();
|
||||
}
|
||||
return book;
|
||||
}
|
||||
|
||||
|
||||
|
||||
static int binary_search<T,U>(IList<U> list, T value, Func<U, T> selector, Comparer<T> comparer = null)
|
||||
{
|
||||
@@ -207,7 +162,6 @@ namespace bts.history
|
||||
int lo = 0, hi = list.Count - 1;
|
||||
while (lo < hi)
|
||||
{
|
||||
//int m = (hi + lo) / 2; // this might overflow; be careful.
|
||||
int m = lo + (hi - lo) / 2;
|
||||
if (comp.Compare( selector(list[m]), value) < 0) lo = m + 1;
|
||||
else hi = m - 1;
|
||||
@@ -216,14 +170,97 @@ namespace bts.history
|
||||
return lo;
|
||||
}
|
||||
|
||||
public static int find_first_greater_or_equal<T,U>(IList<U> sorted_list, T key, Func<U, T> selector, Comparer<T> comp)
|
||||
static int find_first_greater_or_equal<T,U>(IList<U> sorted_list, T key, Func<U, T> selector, Comparer<T> comp)
|
||||
{
|
||||
return binary_search(sorted_list, key, selector, comp);
|
||||
}
|
||||
|
||||
public static int find_first_greater_or_equal<T, U>(SortedList<T, U> sorted_list, T key, Comparer<T> comp)
|
||||
static int find_first_greater_or_equal<T, U>(SortedList<T, U> sorted_list, T key, Comparer<T> comp)
|
||||
{
|
||||
return binary_search(sorted_list.Keys, key, x => x, comp);
|
||||
}
|
||||
|
||||
bool check_cross(OrderStatus status)
|
||||
{
|
||||
var fills = check_my_cross(status);
|
||||
if (fills.Count > 0)
|
||||
return fills.Last().fully_filled;
|
||||
return false;
|
||||
}
|
||||
|
||||
List<FillEntry> check_my_cross(OrderStatus status)
|
||||
{
|
||||
List<FillEntry> fills = new List<FillEntry>();
|
||||
var book = get_book(status.order.security_desc);
|
||||
if (status.order.side == Side.Buy)
|
||||
{
|
||||
int level = 0; int nasks = Math.Min(book.Asks.Count, 10);
|
||||
while (status.state.Quantity > 0 && level < nasks)
|
||||
{
|
||||
var currask = book.ask_at(level);
|
||||
if (status.state.Price >= currask || status.order.market_order)
|
||||
{
|
||||
var qty = Math.Min(status.state.Quantity, book.asksize_at(level));
|
||||
if (qty > 0)
|
||||
fills.Add(generate_fill(status.TransactTime, status, currask, (uint)qty, book, "CROSS"));
|
||||
}
|
||||
else
|
||||
break;
|
||||
level++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int level = 0; int nbids = Math.Min(book.Bids.Count, 10);
|
||||
while (status.state.Quantity > 0 && level < nbids)
|
||||
{
|
||||
var currbid = book.bid_at(level);
|
||||
if (status.state.Price <= currbid || status.order.market_order)
|
||||
{
|
||||
var qty = Math.Min(status.state.Quantity, book.bidsize_at(level));
|
||||
if (qty > 0)
|
||||
fills.Add(generate_fill(status.TransactTime, status, currbid, (uint)qty, book, "CROSS"));
|
||||
}
|
||||
else
|
||||
break;
|
||||
level++;
|
||||
}
|
||||
}
|
||||
return fills;
|
||||
}
|
||||
|
||||
FillEntry generate_fill(Timestamp asof, OrderStatus status, double price, uint qty, co2.BookMessage book = null, string tag = null)
|
||||
{
|
||||
var f = new FillEntry(asof, status.order, status.order.side, price, qty);
|
||||
// f.piq = piq;
|
||||
// f.queue_len = qlen;
|
||||
f.bidsize = book?.bidsize_at(0) ?? 0;
|
||||
f.bid = book?.bid_at(0) ?? 0;
|
||||
f.ask = book?.ask_at(0) ?? 0;
|
||||
f.asksize = book?.asksize_at(0) ?? 0;
|
||||
f.tag = tag;
|
||||
Log.assert(qty <= status.order.size && qty <= status.state.Quantity);
|
||||
status.state.Quantity -= qty;
|
||||
if (status.state.Quantity == 0)
|
||||
{
|
||||
Log.Testing.info("Full FILL " + Stringizer.to_string(f) + (tag ?? ""));
|
||||
f.fully_filled = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Testing.info("Partial FILL " + Stringizer.to_string(f));
|
||||
}
|
||||
status.state.LastPrice = f.price;
|
||||
status.state.AvgPrice = status.state.AvgPrice * status.state.FilledQuantity + f.price * f.size;
|
||||
status.state.FilledQuantity += (uint)f.size;
|
||||
status.state.AvgPrice /= status.state.FilledQuantity;
|
||||
if (f.fully_filled)
|
||||
status.state.Status = api.orderman.OrderStatus.Completed;
|
||||
if (this.on_status != null)
|
||||
this.on_status(status.clone());
|
||||
if (this.on_fill != null)
|
||||
this.on_fill(f);
|
||||
return f;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,14 +10,14 @@ namespace bts.history
|
||||
{
|
||||
IEnumerable<OrderStatus> my_orders { get; }
|
||||
IEnumerable<MBOMessage> exchange_orders_raw { get; }
|
||||
|
||||
void record_order_status(OrderStatus stat);
|
||||
void process_order(Timestamp transact_time, MBOMessage mbo);
|
||||
void process_trade(Timestamp transact_time, string security_desc, co2.ITradeWithOrderIDAndSize trade);
|
||||
void process_book(Timestamp transact_time, string security_desc, co2.BookMessage book);
|
||||
|
||||
void process_exchange_orders(IEnumerable<MBOMessage> exchange_orders);
|
||||
void process_my_orders(IEnumerable<OrderStatus> algo_orders);
|
||||
Task process_exchange_orders_async(IEnumerable<MBOMessage> exchange_orders);
|
||||
Task process_my_orders_async(IEnumerable<OrderStatus> algo_orders);
|
||||
|
||||
IEnumerable<FillEntry> compute_fills<T> (IEnumerable<T> datastream, uint reup_nanoseconds = 0,
|
||||
int framelimit = int.MaxValue)
|
||||
where T : class, IHasMBO, IHasTrade, IHasTimestamp;
|
||||
event Action<FillEntry> on_fill;
|
||||
event Action<OrderStatus> on_status;
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using MathNet.Numerics.Statistics;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public interface IOrderSink
|
||||
{
|
||||
void send(OrderEntry order);
|
||||
void update(string security_desc, Timestamp asof, ulong order_id, double price, uint size = uint.MinValue);
|
||||
void cancel(string security_desc, Timestamp asof, ulong order_id);
|
||||
bool operations_are_in_flight { get; }
|
||||
event Action<OrderStatus> on_status;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using System.Linq;
|
||||
|
||||
using Update = System.ValueTuple<Google.Protobuf.WellKnownTypes.Timestamp, ulong, double, uint>;
|
||||
using Cancel = System.ValueTuple<Google.Protobuf.WellKnownTypes.Timestamp, ulong>;
|
||||
using MathNet.Numerics.Statistics;
|
||||
using mbts.co2;
|
||||
using bts.api;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public class LatencyOrderSink : IOrderSink
|
||||
{
|
||||
Dictionary<ulong, OrderEntry> _orders = new Dictionary<ulong, OrderEntry>();
|
||||
Dictionary<ulong, OrderStatus> _status = new Dictionary<ulong, OrderStatus>();
|
||||
|
||||
public Bucket transact_latency { get; }
|
||||
public Bucket transmit_latency { get; }
|
||||
public event Action<OrderStatus> on_status;
|
||||
public LatencyOrderSink(Bucket transact_latency, Bucket transmit_latency)
|
||||
{
|
||||
this.transact_latency = transact_latency;
|
||||
this.transmit_latency = transmit_latency;
|
||||
}
|
||||
public bool operations_are_in_flight => _status.Any(x => !x.Value.is_terminal());
|
||||
|
||||
public void send(OrderEntry order)
|
||||
{
|
||||
var state = new api.orderman.OrderState
|
||||
{
|
||||
Status = api.orderman.OrderStatus.Working,
|
||||
Quantity = (uint)order.size,
|
||||
Price = order.price
|
||||
};
|
||||
var status = new OrderStatus(order, state);
|
||||
status.TransactTime = order.create_time.add_nanos((int)this.transact_latency.LowerBound);
|
||||
status.SendingTime = status.TransactTime.add_nanos((int)this.transmit_latency.LowerBound);
|
||||
_orders[order.order_id] = order;
|
||||
_status[order.order_id] = status;
|
||||
send_status(status.clone());
|
||||
}
|
||||
|
||||
public void update(string security_desc, Timestamp asof, ulong order_id, double price, uint size = 0)
|
||||
{
|
||||
Log.assert(_orders.TryGetValue(order_id, out OrderEntry order));
|
||||
order.price = price;
|
||||
if (size > uint.MinValue)
|
||||
order.size = size;
|
||||
|
||||
Log.assert(_status.TryGetValue(order_id, out OrderStatus status));
|
||||
if(!status.is_terminal())
|
||||
{
|
||||
status.TransactTime = asof.add_nanos((int)this.transact_latency.LowerBound);
|
||||
status.SendingTime = status.TransactTime.add_nanos((int)this.transmit_latency.LowerBound);
|
||||
status.state.Quantity = (uint)order.size;
|
||||
status.state.Price = order.price;
|
||||
send_status(status.clone());
|
||||
}
|
||||
}
|
||||
|
||||
public void cancel(string security_desc, Timestamp asof, ulong order_id)
|
||||
{
|
||||
Log.assert(_orders.TryGetValue(order_id, out OrderEntry order));
|
||||
|
||||
Log.assert(_status.TryGetValue(order_id, out OrderStatus status));
|
||||
if (!status.is_terminal())
|
||||
{
|
||||
status.TransactTime = asof.add_nanos((int)this.transact_latency.LowerBound);
|
||||
status.SendingTime = status.TransactTime.add_nanos((int)this.transmit_latency.LowerBound);
|
||||
status.state.Status = api.orderman.OrderStatus.Canceled;
|
||||
send_status(status.clone());
|
||||
}
|
||||
}
|
||||
|
||||
void send_status(OrderStatus stat)
|
||||
{
|
||||
if (this.on_status != null)
|
||||
this.on_status(stat);
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
-1
@@ -1,6 +1,8 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using bts.co2;
|
||||
using mbts.co2;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
@@ -43,6 +45,21 @@ namespace bts.history
|
||||
OrderEntry = order
|
||||
};
|
||||
return mbo;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
tm.OrderId = entry.OrderId;
|
||||
return tm;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,7 +13,6 @@ namespace bts.history
|
||||
string tag = null)
|
||||
{
|
||||
this.create_time = create_time;
|
||||
this.last_change = create_time;
|
||||
this.order_id = order_id;
|
||||
this.order_priority = order_priority;
|
||||
this.reference_id = reference_id;
|
||||
@@ -31,7 +30,6 @@ namespace bts.history
|
||||
string tag = null)
|
||||
{
|
||||
this.create_time = create_time;
|
||||
this.last_change = create_time;
|
||||
this.order_id = order_id;
|
||||
this.order_priority = order_priority;
|
||||
this.reference_id = reference_id;
|
||||
@@ -46,7 +44,6 @@ namespace bts.history
|
||||
}
|
||||
|
||||
public Timestamp create_time { get; private set; }
|
||||
public Timestamp last_change { get; set; }
|
||||
public ulong order_id { get; }
|
||||
public ulong order_priority { get; set;}
|
||||
public uint reference_id { get; }
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
using System;
|
||||
using bts.api;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public class OrderStatus
|
||||
public class OrderStatus : IHasTimestamp
|
||||
{
|
||||
public OrderEntry order { get; private set;}
|
||||
public api.orderman.OrderState state { get; private set; }
|
||||
@@ -13,15 +14,15 @@ namespace bts.history
|
||||
var stat = new OrderStatus(this.order, this.state.Clone()); //same order
|
||||
return stat;
|
||||
}
|
||||
|
||||
public Timestamp timestamp { get; set ;}
|
||||
public bts.api.Side side => order.side;
|
||||
|
||||
public Timestamp SendingTime { get; set; }
|
||||
public Timestamp TransactTime { get; set; }
|
||||
public Side side => order.side;
|
||||
|
||||
public OrderStatus(OrderEntry ord, api.orderman.OrderState state)
|
||||
{
|
||||
this.order = ord;
|
||||
this.state = state;
|
||||
this.timestamp = order.last_change.Clone(); //this is the timestamp of this state
|
||||
}
|
||||
|
||||
public bool is_terminal()
|
||||
|
||||
@@ -1,213 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using System.Linq;
|
||||
|
||||
using Update = System.ValueTuple<Google.Protobuf.WellKnownTypes.Timestamp, ulong, double, uint>;
|
||||
using Cancel = System.ValueTuple<Google.Protobuf.WellKnownTypes.Timestamp, ulong>;
|
||||
using MathNet.Numerics.Statistics;
|
||||
using mbts.co2;
|
||||
using bts.api;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public class BasicMatchingModel : IMatchingModel
|
||||
{
|
||||
IDictionary<string, co2.BookMessage> _books = new Dictionary<string, co2.BookMessage>();
|
||||
Dictionary<ulong, OrderEntry> _orders = new Dictionary<ulong, OrderEntry>();
|
||||
Dictionary<ulong, OrderStatus> _status = new Dictionary<ulong, OrderStatus>();
|
||||
|
||||
public Bucket latency_bucket { get; }
|
||||
public BasicMatchingModel(Bucket latency)
|
||||
{
|
||||
this.latency_bucket = latency;
|
||||
}
|
||||
public bool operations_are_in_flight
|
||||
{
|
||||
get { return false; }
|
||||
}
|
||||
|
||||
(int, int) IMatchingModel.get_my_piq(string _ , ulong __)
|
||||
{
|
||||
return (0,0);
|
||||
}
|
||||
|
||||
public double tick_size(string security_desc)
|
||||
{
|
||||
var book = get_book(security_desc);
|
||||
return book.ask_at(0) - book.bid_at(0);
|
||||
}
|
||||
|
||||
public void send(OrderEntry order)
|
||||
{
|
||||
order.last_change = order.last_change.add_nanos((int)this.latency_bucket.LowerBound);
|
||||
var state = new api.orderman.OrderState { Status = api.orderman.OrderStatus.Working,
|
||||
Quantity = (uint)order.size, Price = order.price };
|
||||
var status = new OrderStatus(order, state);
|
||||
_orders[order.order_id] = order;
|
||||
_status[order.order_id] = status;
|
||||
// if(!check_fills(status))
|
||||
// {
|
||||
if(order.on_status != null)
|
||||
order.on_status(status.clone());
|
||||
// }
|
||||
}
|
||||
|
||||
public void update(string security_desc, Timestamp asof, ulong order_id, double price, uint size = 0)
|
||||
{
|
||||
Log.assert(_orders.TryGetValue(order_id, out OrderEntry order));
|
||||
order.last_change = asof.add_nanos((int)this.latency_bucket.LowerBound);
|
||||
order.price = price;
|
||||
if(size > uint.MinValue)
|
||||
order.size = size;
|
||||
|
||||
Log.assert(_status.TryGetValue(order_id, out OrderStatus status));
|
||||
status.state.Quantity = (uint)order.size;
|
||||
status.state.Price = order.price;
|
||||
// if(!check_fills(status))
|
||||
// {
|
||||
if (order.on_status != null)
|
||||
order.on_status(status.clone());
|
||||
// }
|
||||
}
|
||||
|
||||
public void cancel(string security_desc, Timestamp asof, ulong order_id)
|
||||
{
|
||||
Log.assert(_orders.TryGetValue(order_id, out OrderEntry order));
|
||||
order.last_change = asof.add_nanos((int)this.latency_bucket.LowerBound);
|
||||
|
||||
Log.assert(_status.TryGetValue(order_id, out OrderStatus status));
|
||||
if(!status.is_terminal())
|
||||
{
|
||||
status.state.Status = api.orderman.OrderStatus.Canceled;
|
||||
// if (order.on_status != null)
|
||||
// order.on_status(status.clone());
|
||||
}
|
||||
}
|
||||
|
||||
public void process_external_fill(FillEntry external_fill)
|
||||
{
|
||||
if(_orders.TryGetValue(external_fill.order.order_id, out OrderEntry value))
|
||||
{
|
||||
if(value.on_fill != null)
|
||||
value.on_fill(external_fill);
|
||||
}
|
||||
}
|
||||
public void process_external_trade(Timestamp transact_time, string security_desc, co2.TradeMessage trade) { }
|
||||
|
||||
public void process_external_order(Timestamp transact_time, MBOMessage mbo) { }
|
||||
|
||||
public void process_external_book(Timestamp transact_time, string security_desc, co2.BookMessage b)
|
||||
{
|
||||
_books[security_desc] = b;
|
||||
}
|
||||
|
||||
co2.BookMessage get_book(string security_desc)
|
||||
{
|
||||
if(!_books.TryGetValue(security_desc, out co2.BookMessage book))
|
||||
{
|
||||
_books[security_desc] = book = new co2.BookMessage();
|
||||
}
|
||||
return book;
|
||||
}
|
||||
|
||||
bool check_fills(OrderStatus status)
|
||||
{
|
||||
var fills = check_my_cross(status);
|
||||
if(fills.Count > 0)
|
||||
{
|
||||
post_process_fill(fills);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
List<FillEntry> check_my_cross(OrderStatus status)
|
||||
{
|
||||
List<FillEntry> fills = new List<FillEntry>();
|
||||
var book = get_book(status.order.security_desc);
|
||||
if (status.order.side == Side.Buy)
|
||||
{
|
||||
int level = 0; int nasks = Math.Min(book.Asks.Count, 10);
|
||||
while (status.state.Quantity > 0 && level < nasks)
|
||||
{
|
||||
var currask = book.ask_at(level);
|
||||
if (status.state.Price >= currask || status.order.market_order)
|
||||
{
|
||||
var qty = Math.Min(status.state.Quantity, book.asksize_at(level));
|
||||
if (qty > 0)
|
||||
fills.Add(generate_fill(status.order.last_change, status, currask, (uint)qty, book, "CROSS"));
|
||||
}
|
||||
else
|
||||
break;
|
||||
level++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int level = 0; int nbids = Math.Min(book.Bids.Count, 10);
|
||||
while (status.state.Quantity > 0 && level < nbids)
|
||||
{
|
||||
var currbid = book.bid_at(level);
|
||||
if (status.state.Price <= currbid || status.order.market_order)
|
||||
{
|
||||
var qty = Math.Min(status.state.Quantity, book.bidsize_at(level));
|
||||
if (qty > 0)
|
||||
fills.Add(generate_fill(status.order.last_change, status, currbid, (uint)qty, book, "CROSS"));
|
||||
}
|
||||
else
|
||||
break;
|
||||
level++;
|
||||
}
|
||||
}
|
||||
return fills;
|
||||
}
|
||||
|
||||
static FillEntry generate_fill(Timestamp asof, OrderStatus status, double price, uint qty, co2.BookMessage book = null, string tag = null)
|
||||
{
|
||||
var f = new FillEntry(asof, status.order, status.order.side, price, qty);
|
||||
// f.piq = piq;
|
||||
// f.queue_len = qlen;
|
||||
f.bidsize = book?.bidsize_at(0) ?? 0;
|
||||
f.bid = book?.bid_at(0) ?? 0;
|
||||
f.ask = book?.ask_at(0) ?? 0;
|
||||
f.asksize = book?.asksize_at(0) ?? 0;
|
||||
f.tag = tag;
|
||||
Log.assert(qty <= status.order.size && qty <= status.state.Quantity);
|
||||
status.state.Quantity -= qty;
|
||||
if (status.state.Quantity == 0)
|
||||
{
|
||||
Log.Testing.info("Full FILL " + Stringizer.to_string(f) + (tag ?? ""));
|
||||
f.fully_filled = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Testing.info("Partial FILL " + Stringizer.to_string(f));
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
void post_process_fill(IEnumerable<FillEntry> fills)
|
||||
{
|
||||
foreach (var f in fills)
|
||||
{
|
||||
// if (f.fully_filled)
|
||||
// remove_my_order(f.order.order_id);
|
||||
if (f.order.on_fill != null)
|
||||
f.order.on_fill(f);
|
||||
if (_status.TryGetValue(f.order.order_id, out OrderStatus status))
|
||||
{
|
||||
status.state.LastPrice = f.price;
|
||||
status.state.AvgPrice = status.state.AvgPrice * status.state.FilledQuantity + f.price * f.size;
|
||||
status.state.FilledQuantity += (uint)f.size;
|
||||
status.state.AvgPrice /= status.state.FilledQuantity;
|
||||
if (f.fully_filled)
|
||||
status.state.Status = api.orderman.OrderStatus.Completed;
|
||||
if (f.order.on_status != null)
|
||||
f.order.on_status(status.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,173 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using System.Linq;
|
||||
|
||||
using Update = System.ValueTuple<Google.Protobuf.WellKnownTypes.Timestamp, ulong, double, uint>;
|
||||
using Cancel = System.ValueTuple<Google.Protobuf.WellKnownTypes.Timestamp, ulong>;
|
||||
using MathNet.Numerics.Statistics;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public class FIFOMatchingModel : IMatchingModel
|
||||
{
|
||||
IDictionary<string, MBOBook> _books = new Dictionary<string, MBOBook>();
|
||||
|
||||
Dictionary<string, List<OrderEntry> > _create = new Dictionary<string, List<OrderEntry>>();
|
||||
Dictionary<string, List<Update>> _update = new Dictionary<string, List<Update>>();
|
||||
Dictionary<string, List<Cancel>> _cancel = new Dictionary<string, List<Cancel>>();
|
||||
|
||||
public Bucket latency_bucket { get; }
|
||||
public FIFOMatchingModel(Bucket latency)
|
||||
{
|
||||
this.latency_bucket = latency;
|
||||
}
|
||||
public bool operations_are_in_flight
|
||||
{
|
||||
get
|
||||
{
|
||||
var n = _create.Sum(x=> x.Value.Count) +
|
||||
_update.Sum(x => x.Value.Count) +
|
||||
_cancel.Sum(x => x.Value.Count);
|
||||
return n > 0;
|
||||
}
|
||||
}
|
||||
|
||||
public FIFOMatchingModel(IDictionary<string, IOrderBook> obs, Bucket latency_us)
|
||||
{
|
||||
this.latency_bucket = latency_us;
|
||||
foreach(var val in obs)
|
||||
{
|
||||
_books[val.Key] = val.Value.mbo_book;
|
||||
}
|
||||
}
|
||||
//TODO sucks
|
||||
public double tick_size(string security_desc)
|
||||
{
|
||||
var book = get_book(security_desc);
|
||||
return book.ask_at(0) - book.bid_at(0);
|
||||
}
|
||||
public void send(OrderEntry order)
|
||||
{
|
||||
var q = get_queue(order.security_desc, _create);
|
||||
q.Add (order);
|
||||
}
|
||||
|
||||
public void update(string security_desc, Timestamp asof, ulong order_id, double price, uint size = 0)
|
||||
{
|
||||
var q = get_queue(security_desc, _update);
|
||||
q.Add ( (asof, order_id, price, size) );
|
||||
}
|
||||
|
||||
public void cancel(string security_desc, Timestamp asof, ulong order_id)
|
||||
{
|
||||
var q = get_queue(security_desc, _cancel);
|
||||
q.Add( (asof, order_id) );
|
||||
}
|
||||
|
||||
public (int, int) get_my_piq(string security_desc, ulong orderid)
|
||||
{
|
||||
return get_book(security_desc).get_my_piq(orderid);
|
||||
}
|
||||
|
||||
public void process_external_trade(Timestamp transact_time, string security_desc, co2.TradeMessage trade)
|
||||
{
|
||||
process_queue(transact_time);
|
||||
var book = get_book(security_desc);
|
||||
book.process_one_trade(transact_time, trade);
|
||||
}
|
||||
|
||||
public void process_external_order(Timestamp transact_time, MBOMessage mbo)
|
||||
{
|
||||
process_queue(transact_time);
|
||||
var book = get_book(mbo.SecurityDesc);
|
||||
book.process_one_mbo(transact_time, mbo);
|
||||
}
|
||||
|
||||
public void process_external_book(Timestamp transact_time, string security_desc, co2.BookMessage b)
|
||||
{
|
||||
process_queue(transact_time);
|
||||
var book = get_book(security_desc);
|
||||
|
||||
book.process_external_book(transact_time, b);
|
||||
// double bb = mbts.co2.NativePriceHelpers.to_double (b.Bids[0].Mantissa, (sbyte)b.Bids[0].Exponent);
|
||||
// double ba = mbts.co2.NativePriceHelpers.to_double(b.Asks[0].Mantissa, (sbyte)b.Asks[0].Exponent);
|
||||
// double bbb = book.bid_at(0);
|
||||
// double baa = book.ask_at(0);
|
||||
// if(bb != bbb && !double.IsNaN(bbb) || ba != baa && !double.IsNaN(baa))
|
||||
// Log.Testing.error("order book and book book don't match " + _mismatch++);
|
||||
book.match_crosses(transact_time);
|
||||
}
|
||||
|
||||
public void process_external_fill(FillEntry external_fill) {}
|
||||
|
||||
MBOBook get_book(string security_desc)
|
||||
{
|
||||
if(!_books.TryGetValue(security_desc, out MBOBook book))
|
||||
{
|
||||
_books[security_desc] = book = new MBOBook(security_desc);
|
||||
}
|
||||
return book;
|
||||
}
|
||||
IList<T> get_queue<T>(string security_desc, Dictionary<string, List<T>> dict)
|
||||
{
|
||||
if (!dict.TryGetValue(security_desc, out List<T> q))
|
||||
{
|
||||
dict[security_desc] = q = new List<T>();
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
void process_queue(Timestamp transact_time)
|
||||
{
|
||||
foreach (var key in _books.Keys)
|
||||
{
|
||||
var book = get_book(key);
|
||||
{
|
||||
var create = get_queue(key, _create);
|
||||
var remove = new List<OrderEntry>();
|
||||
for (int i = 0; i < create.Count; i++)
|
||||
{
|
||||
if (create[i].create_time.add_nanos( (int)latency_bucket.LowerBound ).less_or_equal(transact_time))
|
||||
{
|
||||
book.insert_my_order(create[i]);
|
||||
remove.Add(create[i]);
|
||||
}
|
||||
}
|
||||
foreach (var i in remove)
|
||||
create.Remove(i); //ref equals is fine here
|
||||
}
|
||||
{
|
||||
var update = get_queue(key, _update);
|
||||
var remove = new List<Update>();
|
||||
for (int i = 0; i < update.Count; i++)
|
||||
{
|
||||
var upd = update[i];
|
||||
if (upd.Item1.add_nanos( (int)latency_bucket.LowerBound ).less_or_equal(transact_time))
|
||||
{
|
||||
book.change_my_order(upd.Item1, upd.Item2, upd.Item3, upd.Item4);
|
||||
remove.Add(upd);
|
||||
}
|
||||
}
|
||||
foreach (var i in remove)
|
||||
update.Remove(i);
|
||||
}
|
||||
{
|
||||
var cancel = get_queue(key, _cancel);
|
||||
var remove = new List<Cancel>();
|
||||
for (int i = 0; i < cancel.Count; i++)
|
||||
{
|
||||
var can = cancel[i];
|
||||
if (can.Item1.add_nanos( (int)latency_bucket.LowerBound ).less_or_equal(transact_time))
|
||||
{
|
||||
book.cancel_my_order(can.Item1, can.Item2);
|
||||
remove.Add(can);
|
||||
}
|
||||
}
|
||||
foreach (var i in remove)
|
||||
cancel.Remove(i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
using System;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using MathNet.Numerics.Statistics;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public interface IMatchingModel
|
||||
{
|
||||
void send(OrderEntry order);
|
||||
void update(string security_desc, Timestamp asof, ulong order_id, double price, uint size = uint.MinValue);
|
||||
void cancel(string security_desc, Timestamp asof, ulong order_id);
|
||||
|
||||
void process_external_order(Timestamp transact_time, MBOMessage mbo);
|
||||
void process_external_trade(Timestamp transact_time, string security_desc, co2.TradeMessage trade);
|
||||
void process_external_book(Timestamp transact_time, string security_desc, co2.BookMessage book);
|
||||
void process_external_fill(FillEntry external_fill);
|
||||
|
||||
//TODO sucks
|
||||
(int, int) get_my_piq(string security_desc, ulong orderid);
|
||||
double tick_size(string security_desc);
|
||||
bool operations_are_in_flight { get; }
|
||||
Bucket latency_bucket { get; }
|
||||
}
|
||||
}
|
||||
@@ -1,473 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using bts.api;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
using bts.co2;
|
||||
using mbts.co2;
|
||||
|
||||
using QueueType = System.Collections.Generic.SortedList<ulong, bts.history.OrderEntry>;
|
||||
using MathNet.Numerics.Statistics;
|
||||
|
||||
namespace bts.history
|
||||
{
|
||||
public class MBOBook
|
||||
{
|
||||
public string security_desc { get; private set; }
|
||||
|
||||
//price -> queue, queue above is priority -> order
|
||||
readonly Dictionary<double, QueueType> _mbobuy = new Dictionary<double, QueueType>();
|
||||
readonly Dictionary<double, QueueType> _mbosell = new Dictionary<double, QueueType>();
|
||||
//orderid -> { side, price, priority }
|
||||
readonly Dictionary<ulong, Tuple<api.Side, double, ulong>> _mbokey = new Dictionary<ulong, Tuple<api.Side, double, ulong>>();
|
||||
readonly SortedList<ulong, OrderEntry> _myorders = new SortedList<ulong, OrderEntry>();
|
||||
readonly SortedList<ulong, OrderStatus> _mystatus = new SortedList<ulong, OrderStatus>();
|
||||
BookMessage _book;
|
||||
|
||||
public double bid_at(int level)
|
||||
{
|
||||
return _book.bid_at(level);
|
||||
//var b = _mbobuy.Keys.OrderByDescending(x => x).Skip(level).FirstOrDefault(x => true, double.NaN);
|
||||
//return b;
|
||||
}
|
||||
|
||||
public double ask_at(int level)
|
||||
{
|
||||
return _book.ask_at(level);
|
||||
//var a = _mbosell.Keys.OrderBy(x => x).Skip(level).FirstOrDefault(x => true, double.NaN);
|
||||
//return a;
|
||||
}
|
||||
|
||||
public uint bidsize_at(int level)
|
||||
{
|
||||
return _book.bidsize_at(level);
|
||||
//double bid = bid_at(level);
|
||||
//int sz = _mbobuy[bid].Values.Sum( x => (int)x.size );
|
||||
//return (uint)sz;
|
||||
}
|
||||
|
||||
public uint asksize_at(int level)
|
||||
{
|
||||
return _book.asksize_at(level);
|
||||
//double ask = ask_at(level);
|
||||
//int sz = _mbosell[ask].Values.Sum(x => (int)x.size);
|
||||
//return (uint)sz;
|
||||
}
|
||||
|
||||
public MBOBook(string security_desc)
|
||||
{
|
||||
this.security_desc = security_desc;
|
||||
}
|
||||
|
||||
public (int, int) get_my_piq(ulong orderid)
|
||||
{
|
||||
int piq = 0, count = 0;
|
||||
if (_myorders.TryGetValue(orderid, out OrderEntry myorder))
|
||||
{
|
||||
var mbo = get_mbo(myorder.side);
|
||||
if (mbo.TryGetValue(myorder.price, out QueueType q))
|
||||
{
|
||||
foreach (var ent in q.Values)
|
||||
{
|
||||
if (!ent.deleted)
|
||||
{
|
||||
if (ent.order_priority < myorder.order_priority)
|
||||
piq++;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return (piq, count);
|
||||
}
|
||||
}
|
||||
return (piq, count);
|
||||
}
|
||||
|
||||
//once you're in, they can't get in front of you
|
||||
const ulong _first_in_q = 999ul;
|
||||
public OrderEntry insert_my_order(OrderEntry myorder)
|
||||
{
|
||||
QueueType queue = get_mbo(myorder.side).GetOrAdd(myorder.price, x =>
|
||||
{
|
||||
Log.Testing.error("FIRST in Q at " + myorder.price);
|
||||
return new QueueType();
|
||||
});
|
||||
|
||||
Log.assert(myorder.order_id != 0);
|
||||
|
||||
var key = queue.LastOrDefault(kvp => kvp.Value.last_change.less_or_equal(myorder.last_change), new KeyValuePair<ulong, OrderEntry>(0u, null));
|
||||
if (key.Value != null)
|
||||
myorder.order_priority = key.Key;
|
||||
else
|
||||
myorder.order_priority = _first_in_q;
|
||||
|
||||
Log.Testing.info($"insert myorder {key} at price { myorder.price } piq { queue.Count } ");
|
||||
|
||||
_myorders.Add(myorder.order_id, myorder);
|
||||
var state = new api.orderman.OrderState { Status = api.orderman.OrderStatus.Working,
|
||||
Quantity = (uint)myorder.size, Price = myorder.price };
|
||||
var status = new OrderStatus(myorder, state);
|
||||
_mystatus.Add(myorder.order_id, status);
|
||||
|
||||
if(myorder.on_status != null)
|
||||
myorder.on_status(status.clone());
|
||||
return myorder;
|
||||
}
|
||||
|
||||
public OrderEntry change_my_order(Timestamp asof, ulong order_id, double price, uint size = uint.MinValue)
|
||||
{
|
||||
if (!_myorders.TryGetValue(order_id, out OrderEntry myorder))
|
||||
return null;
|
||||
|
||||
if(price == myorder.price && size <= myorder.size && size > uint.MinValue)
|
||||
{
|
||||
myorder.size = size;
|
||||
}
|
||||
else
|
||||
{
|
||||
myorder.price = price;
|
||||
if (size > uint.MinValue)
|
||||
myorder.size = size;
|
||||
var mbo = get_mbo(myorder.side);
|
||||
if (mbo.TryGetValue(price, out QueueType queue))
|
||||
{
|
||||
var key = queue.LastOrDefault(kvp => kvp.Value.last_change.less_or_equal(asof), new KeyValuePair<ulong, OrderEntry>(0u, null));
|
||||
if (key.Value != null)
|
||||
myorder.order_priority = key.Key;
|
||||
else
|
||||
myorder.order_priority = _first_in_q;
|
||||
Log.Testing.info($"update myorder {order_id} at price { price } piq { queue.Count } ");
|
||||
}
|
||||
}
|
||||
myorder.last_change = asof;
|
||||
|
||||
if (_mystatus.TryGetValue(order_id, out OrderStatus status))
|
||||
{
|
||||
status.state.Quantity = (uint)myorder.size;
|
||||
status.state.Price = myorder.price;
|
||||
if (myorder.on_status != null)
|
||||
myorder.on_status(status.clone());
|
||||
}
|
||||
return myorder;
|
||||
}
|
||||
|
||||
bool remove_my_order(ulong my_order_id)
|
||||
{
|
||||
return _myorders.Remove(my_order_id);
|
||||
}
|
||||
|
||||
public bool cancel_my_order(Timestamp asof, ulong my_order_id)
|
||||
{
|
||||
if (!_myorders.TryGetValue(my_order_id, out OrderEntry myorder))
|
||||
return false;
|
||||
|
||||
if (_mystatus.TryGetValue(my_order_id, out OrderStatus status))
|
||||
{
|
||||
if(!status.is_terminal())
|
||||
{
|
||||
status.state.Status = api.orderman.OrderStatus.Canceled;
|
||||
if (myorder.on_status != null)
|
||||
myorder.on_status(status.clone());
|
||||
}
|
||||
}
|
||||
return remove_my_order(my_order_id);
|
||||
}
|
||||
|
||||
public void process_one_trade(Timestamp ts, co2.ITradeWithOrderIDAndSize tradeentry)
|
||||
{
|
||||
//look for the order that got filled, if we have it (could have been here since last Tuesday)
|
||||
var q = find_queue(tradeentry.OrderId, out Side side, out double price, out ulong priority_key);
|
||||
if (q != null)
|
||||
{
|
||||
if (!q.TryGetValue(priority_key, out OrderEntry order))
|
||||
Log.assert(false);
|
||||
if(order.deleted)
|
||||
Log.Testing.warn("fill for deleted order, probably ok " + tradeentry.OrderId);
|
||||
//if the priority is greater than the priority of any of my orders, fill me first
|
||||
//the real order still gets decremented later by CME which isn't quite right TODO
|
||||
List<FillEntry> tfills = new List<FillEntry>();
|
||||
foreach (var myorder in _myorders.Values)
|
||||
{
|
||||
if (order.price == myorder.price && side == myorder.side)
|
||||
{
|
||||
if (priority_key >= myorder.order_priority)
|
||||
{
|
||||
Log.assert(!order.deleted);
|
||||
var (piq, count) = get_my_piq(myorder.order_id);
|
||||
// int piq = q.IndexOfKey(myorder.order_priority); int count = q.Count;
|
||||
var f = generate_fill(ts, myorder, order.price, (uint)Math.Min(tradeentry.Size, myorder.size),
|
||||
piq, count, $" {piq} of {count} ");
|
||||
tfills.Add(f);
|
||||
}
|
||||
}
|
||||
}
|
||||
post_process_fill(tfills);
|
||||
}
|
||||
}
|
||||
|
||||
public void process_one_mbo(Timestamp ts, IMBOMessage order)
|
||||
{
|
||||
process_mbo(ts, order);
|
||||
}
|
||||
|
||||
public void process_external_book(Timestamp transact_time, BookMessage b)
|
||||
{
|
||||
_book = b;
|
||||
}
|
||||
|
||||
public void match_crosses(Timestamp ts)
|
||||
{
|
||||
List<FillEntry> fills = new List<FillEntry>();
|
||||
foreach (var myorder in _myorders.Values)
|
||||
{
|
||||
if (myorder.market_order)
|
||||
{
|
||||
double px = myorder.side == Side.Buy ? ask_at(0) : bid_at(0);
|
||||
var f = generate_fill(ts, myorder, px, (uint)myorder.size, 0, 0, "MARKET");
|
||||
fills.Add(f);
|
||||
}
|
||||
else
|
||||
fills.AddRange(check_my_cross(ts, myorder));
|
||||
}
|
||||
post_process_fill(fills);
|
||||
}
|
||||
|
||||
static public IDictionary<string, List<MBOMessage>> extract_mbo(MarketDataIncrementalRefresh md)
|
||||
{
|
||||
Dictionary<string, List<MBOMessage>> cache = new Dictionary<string, List<MBOMessage>>();
|
||||
foreach (var order in md.OrderIdEntries)
|
||||
{
|
||||
if (order.ReferenceId == 0)
|
||||
continue;
|
||||
// entries is indexed by 0 but ref is indexed by 1 :facepalm:
|
||||
int mdidx = ((int)order.ReferenceId) - 1;
|
||||
Log.assert((mdidx <= md.MdEntries.Count));
|
||||
|
||||
MDEntry mdval = md.MdEntries[mdidx];
|
||||
cache_mbo( MBOUtils.make_mbo(md, mdval, order) );
|
||||
}
|
||||
foreach (var mdval in md.MdEntries)
|
||||
{
|
||||
if (mdval.OrderId > 0 && md.OrderIdEntries.Count == 0)
|
||||
cache_mbo( MBOUtils.make_mbo(md, mdval, null) );
|
||||
}
|
||||
|
||||
return cache;
|
||||
|
||||
void cache_mbo(MBOMessage mbo)
|
||||
{
|
||||
if (!cache.TryGetValue(mbo.SecurityDesc, out List<MBOMessage> list))
|
||||
cache[mbo.SecurityDesc] = list = new List<MBOMessage>();
|
||||
list.Add(mbo);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Dictionary<double, QueueType> get_mbo(api.Side side)
|
||||
{
|
||||
if (side == Side.Buy)
|
||||
return _mbobuy;
|
||||
else
|
||||
return _mbosell;
|
||||
}
|
||||
|
||||
FillEntry generate_fill(Timestamp ts, OrderEntry myorder, double price, uint qty, int piq, int qlen, string tag = null)
|
||||
{
|
||||
var f = new FillEntry(ts, myorder, myorder.side, price, qty);
|
||||
f.piq = piq;
|
||||
f.queue_len = qlen;
|
||||
f.bidsize = bidsize_at(0);
|
||||
f.bid = bid_at(0);
|
||||
f.ask = ask_at(0);
|
||||
f.asksize = asksize_at(0);
|
||||
f.tag = tag;
|
||||
Log.assert(qty <= myorder.size);
|
||||
myorder.size -= qty;
|
||||
if (myorder.size == 0)
|
||||
{
|
||||
Log.Testing.info("Full FILL " + Stringizer.to_string(f) + (tag ?? ""));
|
||||
f.fully_filled = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Log.Testing.info("Partial FILL " + Stringizer.to_string(f));
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
void post_process_fill(IEnumerable<FillEntry> fills)
|
||||
{
|
||||
foreach (var f in fills)
|
||||
{
|
||||
if (f.fully_filled)
|
||||
remove_my_order(f.order.order_id);
|
||||
if (f.order.on_fill != null)
|
||||
f.order.on_fill(f);
|
||||
if(_mystatus.TryGetValue(f.order.order_id, out OrderStatus status))
|
||||
{
|
||||
status.state.LastPrice = f.price;
|
||||
status.state.AvgPrice = status.state.AvgPrice * status.state.FilledQuantity + f.price * f.size;
|
||||
status.state.FilledQuantity += (uint)f.size;
|
||||
status.state.AvgPrice /= status.state.FilledQuantity;
|
||||
if (f.fully_filled)
|
||||
status.state.Status = api.orderman.OrderStatus.Completed;
|
||||
if(f.order.on_status != null)
|
||||
f.order.on_status(status.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
OrderEntry find_order(ulong order_id)
|
||||
{
|
||||
OrderEntry order = null;
|
||||
find_queue(order_id, out Side _, out double _, out ulong prior)?.TryGetValue(prior, out order);
|
||||
return order;
|
||||
}
|
||||
|
||||
QueueType find_queue(ulong order_id, out api.Side side, out double price, out ulong priority_key)
|
||||
{
|
||||
QueueType q = null; side = Side.Undefined; price = double.NaN; priority_key = 0;
|
||||
if (_mbokey.TryGetValue(order_id, out Tuple<api.Side, double, ulong> tup))
|
||||
{
|
||||
var mbo = get_mbo(tup.Item1);
|
||||
mbo.TryGetValue(tup.Item2, out q);
|
||||
side = tup.Item1;
|
||||
price = tup.Item2;
|
||||
priority_key = tup.Item3;
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
List<FillEntry> check_my_cross(Timestamp ts, OrderEntry myorder)
|
||||
{
|
||||
List<FillEntry> fills = new List<FillEntry>();
|
||||
if (myorder.side == Side.Buy)
|
||||
{
|
||||
int level = 0; int nasks = Math.Min(_mbosell.Keys.Count, 10);
|
||||
while (myorder.size > 0 && level < nasks)
|
||||
{
|
||||
var currask = ask_at(level);
|
||||
if (myorder.price >= currask)
|
||||
{
|
||||
var qty = Math.Min(myorder.size, asksize_at(level));
|
||||
if (qty > 0)
|
||||
fills.Add(generate_fill(ts, myorder, currask, (uint)qty, 0, 0, "CROSS"));
|
||||
}
|
||||
else
|
||||
break;
|
||||
level++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int level = 0; int nbids = Math.Min(_mbobuy.Keys.Count, 10);
|
||||
while (myorder.size > 0 && level < nbids)
|
||||
{
|
||||
var currbid = bid_at(level);
|
||||
if (myorder.price <= currbid)
|
||||
{
|
||||
var qty = Math.Min(myorder.size, bidsize_at(level));
|
||||
if (qty > 0)
|
||||
fills.Add(generate_fill(ts, myorder, currbid, (uint)qty, 0, 0, "CROSS"));
|
||||
}
|
||||
else
|
||||
break;
|
||||
level++;
|
||||
}
|
||||
}
|
||||
return fills;
|
||||
}
|
||||
|
||||
void process_mbo(Timestamp ts, IMBOMessage order)
|
||||
{
|
||||
if (order.MdEntryType != MDEntryType.Bid && order.MdEntryType != MDEntryType.Offer)
|
||||
return;
|
||||
var mbo = get_mbo(Utils.same_side(order.MdEntryType));
|
||||
if (order.OrderUpdateAction == MDUpdateAction.New)
|
||||
{
|
||||
var q = mbo.GetOrAdd(order.MdEntryPx, x => new QueueType());
|
||||
var side = Utils.same_side(order.MdEntryType);
|
||||
var neworder = new OrderEntry(ts, order.OrderId, order.MdOrderPriority, order.ReferenceId,
|
||||
this.security_desc, side, order.MdEntryPx, order.MdDisplayQty);
|
||||
q.Add(order.MdOrderPriority, neworder);
|
||||
_mbokey[order.OrderId] = Tuple.Create(Utils.same_side(order.MdEntryType), order.MdEntryPx, order.MdOrderPriority);
|
||||
}
|
||||
else if (order.OrderUpdateAction == MDUpdateAction.Change)
|
||||
{
|
||||
var currq = find_queue(order.OrderId, out Side _, out double _, out ulong priority_key);
|
||||
if (currq != null)
|
||||
currq.Remove(priority_key); //this could have been previously deleted
|
||||
var newq = mbo.GetOrAdd(order.MdEntryPx, x => new QueueType());
|
||||
newq.AddOrUpdate(order.MdOrderPriority,
|
||||
x =>
|
||||
{
|
||||
var side = Utils.same_side(order.MdEntryType); var refid = 0u;
|
||||
var neworder = new OrderEntry(ts, order.OrderId, order.MdOrderPriority, refid,
|
||||
this.security_desc, side, order.MdEntryPx, order.MdDisplayQty);
|
||||
|
||||
Log.assert(neworder.order_priority == order.MdOrderPriority, "bad priority");
|
||||
_mbokey[order.OrderId] = Tuple.Create(Utils.same_side(order.MdEntryType), order.MdEntryPx, order.MdOrderPriority);
|
||||
return neworder;
|
||||
},
|
||||
(id, x) =>
|
||||
{
|
||||
x.last_change = ts;
|
||||
if (x.order_priority != order.MdOrderPriority)
|
||||
{
|
||||
Log.assert(false, "kd dec 12 2019, this is keyed on priority so this doens't make sense");
|
||||
// var myorder = _myorders.Values.FirstOrDefault(o => o.order_priority == x.order_priority);
|
||||
// if (myorder != null)
|
||||
// {
|
||||
// //target order got better, go with
|
||||
// if (order.MdOrderPriority < myorder.order_priority)
|
||||
// {
|
||||
// _myorders.Remove(myorder.order_id);
|
||||
// myorder.order_priority = order.MdOrderPriority;
|
||||
// _myorders[myorder.order_id] = myorder;
|
||||
// }
|
||||
// else //target order got worse, attach to prior
|
||||
// slide_order_up(currq, order);
|
||||
// }
|
||||
// x.order_priority = myorder.order_priority;
|
||||
}
|
||||
x.price = order.MdEntryPx;
|
||||
x.size = order.MdDisplayQty;
|
||||
Log.assert(x.order_id == order.OrderId, "orderid invariant");
|
||||
_mbokey[x.order_id] = Tuple.Create(Utils.same_side(order.MdEntryType), x.price, x.order_priority);
|
||||
return x;
|
||||
});
|
||||
}
|
||||
else if (order.OrderUpdateAction == MDUpdateAction.Delete)
|
||||
{
|
||||
var currq = find_queue(order.OrderId, out Side _, out double _, out ulong _);
|
||||
if (currq == null)
|
||||
Log.assert(true);
|
||||
if (currq != null && currq.TryGetValue(order.MdOrderPriority, out OrderEntry removed_order))
|
||||
{
|
||||
removed_order.deleted = true;
|
||||
removed_order.last_change = ts;
|
||||
slide_order_up(currq, order);
|
||||
//can't take this out because this could actually be a trade
|
||||
//currq.Remove(order.MdOrderPriority);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void slide_order_up(QueueType currq, IMBOMessage order)
|
||||
{
|
||||
var myorder = _myorders.Values.FirstOrDefault(o => o.order_priority == order.MdOrderPriority);
|
||||
if (myorder != null)
|
||||
{
|
||||
_myorders.Remove(myorder.order_id);
|
||||
var idx = currq.IndexOfKey(order.MdOrderPriority);
|
||||
if (idx > 0)
|
||||
{
|
||||
var prev = currq.ElementAt(idx - 1);
|
||||
myorder.order_priority = prev.Key;
|
||||
}
|
||||
else
|
||||
myorder.order_priority = _first_in_q;
|
||||
_myorders[myorder.order_id] = myorder;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -261,7 +261,7 @@
|
||||
"var algo_type = typeof(RoundTrip);\n",
|
||||
"var algo_params = \"size=10;tick_size=0.015625,0.0078125,0.015625;hedge_factors=1,1,-1\";\n",
|
||||
"\n",
|
||||
"//var algo = AlgoFactory.algo_factory(typeof(RoundTrip), matching_model, security_list, algo_params);"
|
||||
"//var algo = AlgoFactory.algo_factory(typeof(RoundTrip), sink, security_list, algo_params);"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -272,8 +272,8 @@
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"var matching_model = new FIFOModel(new Bucket(0, 1));\n",
|
||||
"var stream = run_algo<HistoryRow,AlgoReport>(algo_type, matching_model, algo_params,\n",
|
||||
"var sink = new FIFOModel(new Bucket(0, 1));\n",
|
||||
"var stream = run_algo<HistoryRow,AlgoReport>(algo_type, sink, algo_params,\n",
|
||||
" bts.api.Side.Undefined, 0.0, 10, security_list, \n",
|
||||
" new[] {c2f, c3f, c1f}, x => x.Select(xx => new AlgoReport(xx)) );\n",
|
||||
"\n",
|
||||
|
||||
+2
-2
@@ -186,8 +186,8 @@
|
||||
"var algo_params = \"size=10;tick_size=0.015625,0.015625;hedge_factors=1,-1;profit_ticks=0\";\n",
|
||||
"\n",
|
||||
"var latency_ns = 50_000u;\n",
|
||||
"var matching_model = new BasicMatchingModel(new Bucket(latency_ns, latency_ns+1));\n",
|
||||
"var first_pass = algo_orders<HistoryRow>(matching_model, algo_type, algo_params, \n",
|
||||
"var sink = new BasicMatchingModel(new Bucket(latency_ns, latency_ns+1));\n",
|
||||
"var first_pass = algo_orders<HistoryRow>(sink, algo_type, algo_params, \n",
|
||||
" bts.api.Side.Sell, -0.046875, 10, \n",
|
||||
" security_list, //must match below\n",
|
||||
" new[] {z9f, h0f});"
|
||||
|
||||
@@ -261,7 +261,7 @@
|
||||
"var algo_type = typeof(RoundTrip);\n",
|
||||
"var algo_params = \"size=10;tick_size=0.015625,0.0078125,0.015625;hedge_factors=1,1,-1\";\n",
|
||||
"\n",
|
||||
"//var algo = AlgoFactory.algo_factory(typeof(RoundTrip), matching_model, security_list, algo_params);"
|
||||
"//var algo = AlgoFactory.algo_factory(typeof(RoundTrip), sink, security_list, algo_params);"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -272,8 +272,8 @@
|
||||
},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"var matching_model = new FIFOModel(new Bucket(0, 1));\n",
|
||||
"var stream = run_algo<HistoryRow,AlgoReport>(algo_type, matching_model, algo_params,\n",
|
||||
"var sink = new FIFOModel(new Bucket(0, 1));\n",
|
||||
"var stream = run_algo<HistoryRow,AlgoReport>(algo_type, sink, algo_params,\n",
|
||||
" bts.api.Side.Undefined, 0.0, 10, security_list, \n",
|
||||
" new[] {c2f, c3f, c1f}, x => x.Select(xx => new AlgoReport(xx)) );\n",
|
||||
"\n",
|
||||
|
||||
@@ -186,8 +186,8 @@
|
||||
"var algo_params = \"size=10;tick_size=0.015625,0.015625;hedge_factors=1,-1;profit_ticks=0\";\n",
|
||||
"\n",
|
||||
"var latency_ns = 50_000u;\n",
|
||||
"var matching_model = new BasicMatchingModel(new Bucket(latency_ns, latency_ns+1));\n",
|
||||
"var first_pass = algo_orders<HistoryRow>(matching_model, algo_type, algo_params, \n",
|
||||
"var sink = new BasicMatchingModel(new Bucket(latency_ns, latency_ns+1));\n",
|
||||
"var first_pass = algo_orders<HistoryRow>(sink, algo_type, algo_params, \n",
|
||||
" bts.api.Side.Sell, -0.046875, 10, \n",
|
||||
" security_list, //must match below\n",
|
||||
" new[] {z9f, h0f});"
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
#if false
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -9,7 +11,7 @@ namespace bts.history
|
||||
{
|
||||
public class AlgoRunner
|
||||
{
|
||||
static public IEnumerable<U> run_algo<T, U>(System.Type algo_type, IMatchingModel matching_model, string algo_params,
|
||||
static public IEnumerable<U> run_algo<T, U>(System.Type algo_type, IOrderSink sink, string algo_params,
|
||||
api.Side side, double price, uint size,
|
||||
string[] security_list, IEnumerable<T>[] datastream,
|
||||
Func<IEnumerable<AlgoResults>, IEnumerable<U>> selector = null,
|
||||
@@ -32,7 +34,7 @@ namespace bts.history
|
||||
|
||||
if (count == 0 || algo.is_completed())
|
||||
{
|
||||
algo = AlgoFactory.algo_factory(algo_type, matching_model, security_list, algo_params);
|
||||
algo = AlgoFactory.algo_factory(algo_type, sink, security_list, algo_params);
|
||||
AlgoBase.activate_self((AlgoBase)algo, side, price, size, Timestamp.FromDateTime(DateTime.UtcNow),
|
||||
(h, f) => q.Add(new AlgoResults(curr, f, last_trade.GetValueOrDefault(f.order.security_desc), last_book.GetValueOrDefault(f.order.security_desc))),
|
||||
(h, s) => q.Add(new AlgoResults(curr, s, last_trade.GetValueOrDefault(s.order.security_desc), last_book.GetValueOrDefault(s.order.security_desc))));
|
||||
@@ -44,11 +46,11 @@ namespace bts.history
|
||||
if (curr.MdEntry.MdEntryType == MDEntryType.Bid || curr.MdEntry.MdEntryType == MDEntryType.Offer)
|
||||
{
|
||||
foreach (var order in orders)
|
||||
algo.matching_model.process_external_order(curr.Md.TransactTime, order);
|
||||
algo.sink.process_external_order(curr.Md.TransactTime, order);
|
||||
}
|
||||
if (curr.Book != null)
|
||||
{
|
||||
algo.matching_model.process_external_book(curr.Md.TransactTime, secdesc, curr.Book);
|
||||
algo.sink.process_external_book(curr.Md.TransactTime, secdesc, curr.Book);
|
||||
|
||||
algo.process_book(secdesc, curr.MdEntry.SecurityId, curr.Book, curr.Book, curr.Md);
|
||||
Log.assert(curr.Trade == null, "new schema");
|
||||
@@ -56,7 +58,7 @@ namespace bts.history
|
||||
}
|
||||
if (curr.Trade != null)
|
||||
{
|
||||
algo.matching_model.process_external_trade(curr.Md.TransactTime, secdesc, curr.Trade);
|
||||
algo.sink.process_external_trade(curr.Md.TransactTime, secdesc, curr.Trade);
|
||||
foreach (var order in orders)
|
||||
{
|
||||
if (curr.Trade.OrderId != order.OrderId)
|
||||
@@ -70,7 +72,7 @@ namespace bts.history
|
||||
clone.Mantissa = ip.mantissa;
|
||||
clone.Exponent = ip.exponent;
|
||||
clone.Size = (uint)order.MdDisplayQty;
|
||||
algo.matching_model.process_external_trade(curr.Md.TransactTime, secdesc, clone);
|
||||
algo.sink.process_external_trade(curr.Md.TransactTime, secdesc, clone);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,4 +112,5 @@ namespace bts.history
|
||||
public co2.BookMessage book { get; }
|
||||
public co2.TradeMessage trade { get; }
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -233,7 +233,7 @@ namespace bts.history
|
||||
}
|
||||
else if (entry.MdEntryType == MDEntryType.Trade)
|
||||
{
|
||||
co2.TradeMessage tm = OrderBook.create_trade(md, entry);
|
||||
co2.TradeMessage tm = MBOUtils.create_trade(md, entry);
|
||||
if (!_trades.ContainsKey(entry.security_desc()))
|
||||
_trades[entry.security_desc()] = tm;
|
||||
|
||||
|
||||
@@ -142,7 +142,7 @@ namespace bts.history
|
||||
}
|
||||
else if (entry.MdEntryType == MDEntryType.Trade)
|
||||
{
|
||||
co2.TradeMessage tm = OrderBook.create_trade(md, entry);
|
||||
co2.TradeMessage tm = MBOUtils.create_trade(md, entry);
|
||||
if (!_trades.ContainsKey(entry.security_desc()))
|
||||
setup_table_and_queue(entry.security_desc());
|
||||
_trades[entry.security_desc()] = tm;
|
||||
|
||||
@@ -202,65 +202,101 @@ namespace bts.history
|
||||
});
|
||||
}
|
||||
|
||||
static public IEnumerable<OrderOrFill> algo_orders<T>(IMatchingModel matching_model, System.Type algo_type, string algo_params,
|
||||
api.Side side, double price, uint size, string[] security_list,
|
||||
IEnumerable<T>[] datastream, IEnumerable<FillEntry> backfills = null,
|
||||
int framelimit = int.MaxValue)
|
||||
// static public IEnumerable<FillEntry> compute_fills<T>(IFillModel fill_model, IEnumerable<T> tradestream,
|
||||
// uint reup_nanoseconds = 0,
|
||||
// int framelimit = int.MaxValue)
|
||||
// where T : class, IHasMBO, IHasTrade, IHasTimestamp
|
||||
// {
|
||||
// return fill_model.compute_fills(tradestream, reup_nanoseconds, framelimit);
|
||||
// }
|
||||
|
||||
// public IEnumerable<FillEntry> compute_fills<T>(IFillModel fill_model, IEnumerable<OrderStatus> my_orders, IEnumerable<T> datastream, int framelimit = int.MaxValue)
|
||||
// where T : class, IHasMBO, IHasTrade, IHasTimestamp
|
||||
// {
|
||||
// var q = new List<FillEntry>();
|
||||
// int count = 0;
|
||||
// Dictionary<ulong, uint> spent_lots = new Dictionary<ulong, uint>();
|
||||
// List<IEnumerable<IHasTimestamp>> ilist = new List<IEnumerable<IHasTimestamp>>();
|
||||
// ilist.Add(my_orders); ilist.Add(datastream);
|
||||
// var ienum = Query.stream_data(ilist, (IHasTimestamp[] valcache, int min) =>
|
||||
// {
|
||||
// q.Clear();
|
||||
// if (count++ > framelimit)
|
||||
// throw new System.IO.EndOfStreamException();
|
||||
|
||||
// if(valcache[min] is OrderStatus)
|
||||
// {
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// T curr = (T)valcache[min];
|
||||
// if (curr.Trade != null)
|
||||
// {
|
||||
// Log.assert(curr.MdEntry.MdEntryType == MDEntryType.Trade);
|
||||
// //q.AddRange(this.get_fills_for_trade(curr.TransactTime, curr.Trade, reup_nanoseconds));
|
||||
// var trades = MBOUtils.extract_mbo(curr.Md, curr.MdEntry, curr.EntryIndex, curr.Orders);
|
||||
// foreach (var trade in trades)
|
||||
// {
|
||||
// if (curr.Trade.OrderId != trade.OrderId)
|
||||
// {
|
||||
// ITradeWithOrderIDAndSize clone = curr.Trade.Clone();
|
||||
// clone.OrderId = trade.OrderId;
|
||||
// //price is the same
|
||||
// clone.Size = trade.LastQty;
|
||||
// q.AddRange(this.get_fills_for_trade(curr.TransactTime, clone, reup_nanoseconds, spent_lots));
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return q;
|
||||
// });
|
||||
// return ienum;
|
||||
// }
|
||||
|
||||
static public IEnumerable<OrderOrFill> algo_orders<T>(IOrderSink sink, IFillModel fill_model,
|
||||
System.Type algo_type, string algo_params,
|
||||
api.Side side, double price, uint size, string[] security_list,
|
||||
IEnumerable<T>[] datastream, int framelimit = int.MaxValue)
|
||||
where T : class, IHasBook, IHasTrade, IHasTimestamp
|
||||
{
|
||||
var q = new List<OrderOrFill>();
|
||||
|
||||
IAlgo algo = null;
|
||||
int count = 0;
|
||||
List< IEnumerable<IHasTimestamp> > ilist = new List<IEnumerable<IHasTimestamp>>(datastream);
|
||||
if(backfills != null)
|
||||
ilist.Add(backfills);
|
||||
var ienum = stream_data(ilist.ToArray(), (IHasTimestamp[] valcache, int min) =>
|
||||
var ienum = stream_data(datastream, (T[] valcache, int min) =>
|
||||
{
|
||||
q.Clear();
|
||||
if(count == 0 || algo.is_completed()) //spreader case will never complete
|
||||
{
|
||||
algo = AlgoFactory.algo_factory(algo_type, matching_model, security_list, algo_params);
|
||||
algo = AlgoFactory.algo_factory(algo_type, sink, security_list, algo_params);
|
||||
AlgoBase.activate_self((AlgoBase)algo, side, price, size, Timestamp.FromDateTime(DateTime.UtcNow),
|
||||
(h, f) => q.Add(new OrderOrFill(f)),
|
||||
(h, s) => q.Add(new OrderOrFill(s)));
|
||||
(h, s) =>
|
||||
{
|
||||
q.Add(new OrderOrFill(s));
|
||||
});
|
||||
}
|
||||
if (count++ > framelimit)
|
||||
throw new System.IO.EndOfStreamException();
|
||||
|
||||
var secdesc = security_list[min];
|
||||
if(valcache[min] is FillEntry)
|
||||
T curr = (T)valcache[min];
|
||||
if (curr.Book != null)
|
||||
{
|
||||
var extfill = (FillEntry)(object)valcache[min];
|
||||
matching_model.process_external_fill(extfill);
|
||||
q.Add(new OrderOrFill(extfill));
|
||||
fill_model.process_book(curr.Md.TransactTime, secdesc, curr.Book);
|
||||
algo.process_book(secdesc, curr.MdEntry.SecurityId, curr.Book, curr.Book, curr.Md);
|
||||
}
|
||||
else
|
||||
if (curr.Trade != null)
|
||||
{
|
||||
T curr = (T)valcache[min];
|
||||
if (curr.Book != null)
|
||||
{
|
||||
algo.matching_model.process_external_book(curr.Md.TransactTime, secdesc, curr.Book);
|
||||
algo.process_book(secdesc, curr.MdEntry.SecurityId, curr.Book, curr.Book, curr.Md);
|
||||
}
|
||||
if (curr.Trade != null)
|
||||
{
|
||||
algo.matching_model.process_external_trade(curr.Md.TransactTime, secdesc, curr.Trade);
|
||||
algo.process_trades(secdesc, curr.MdEntry.SecurityId, new[] { curr.Trade }, curr.Md);
|
||||
}
|
||||
fill_model.process_trade(curr.Md.TransactTime, secdesc, curr.Trade);
|
||||
algo.process_trades(secdesc, curr.MdEntry.SecurityId, new[] { curr.Trade }, curr.Md);
|
||||
}
|
||||
return q;
|
||||
});
|
||||
return ienum;
|
||||
}
|
||||
|
||||
static public IEnumerable<FillEntry> compute_fills<T>(IFillModel fill_model, IEnumerable<T> tradestream,
|
||||
uint reup_nanoseconds = 0,
|
||||
int framelimit = int.MaxValue)
|
||||
where T : class, IHasMBO, IHasTrade, IHasTimestamp
|
||||
{
|
||||
return fill_model.compute_fills(tradestream, reup_nanoseconds, framelimit);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -82,7 +82,8 @@ namespace bts.history
|
||||
public OrderDisplay(OrderStatus res) { _res = new OrderOrFill(res); }
|
||||
public ulong? order_id => _res.order?.order.order_id;
|
||||
public string security_desc => _res.order?.order.security_desc;
|
||||
public string our_order_timestamp => _res.order?.timestamp.ToString();
|
||||
public string our_order_sendingtime => _res.order?.SendingTime.ToString();
|
||||
public string our_order_transacttime => _res.order?.TransactTime.ToString();
|
||||
public string our_order_side => _res.order?.side.ToString();
|
||||
public string our_order_status => _res.order?.state.Status.ToString();
|
||||
public double? our_order_price => _res.order?.state.Price;
|
||||
|
||||
Reference in new issue
Block a user