Files
spark/src/client/spark_historical/FillModel/FIFOFillModel.cs
T
2019-12-31 12:14:37 -05:00

209 lines
9.4 KiB
C#

using System;
using System.Linq;
using System.Collections.Generic;
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 : FillModelBase, IFillModel
{
readonly Dictionary<ulong, List<MBOMessage>> _exchangeorders =
new Dictionary<ulong, List<MBOMessage>>();
public IEnumerable<MBOMessage> exchange_orders_raw => _exchangeorders.SelectValues(_exchangeorders.Keys).SelectMany(x => x);
readonly protected SortedList<Timestamp, OrderStatus> _myorders =
new SortedList<Timestamp, OrderStatus>(HistoricalExtensions.timestamp_comparer);
public IEnumerable<OrderStatus> my_orders => _myorders.Values;
public FIFOFillModel(Bucket outgoing_latency) : base(outgoing_latency)
{
}
public override void reset()
{
base.reset();
_myorders.Clear();
_exchangeorders.Clear();
}
public virtual void record_order_status(OrderStatus stat)
{
if (_disqual.ContainsKey(stat.order.order_id))
{
Log.Testing.error($"new status for disqualified error, not recording");
}
else if (!check_cross(stat))
{
int tries = 0; bool done = false;
while (tries++ < 99) //100 nano resolution from CME data makes this sorta ok
{
try
{
_myorders.Add(stat.TransactTime, stat);
done = true;
break;
}
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);
}
public void process_trade(Timestamp transact_time, string security_desc, co2.TradeMessage trade_summary,
IEnumerable<ITradeDetail> orders)
{
foreach(var order in orders)
{
if(!_exchangeorders.TryGetValue(order.OrderId, out List<MBOMessage> operations))
continue;
if(!operations.Any()) //can't find the order, must have been here forever, they get filled not us
continue;
if(_myorders.Count == 0)
continue;
var market_operations = operations.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 we saw, on this order, they get filled not us
continue;
//this is the latest market operation for the filled order at the time of fill
var curr_market_operation = market_operations[market_operation_index-1];
//now we slide backwards to find the first operation that kept priority at the time of fill
for (int i = market_operation_index - 2; i >= 0; i--)
{
if(market_operations[i].MdOrderPriority == curr_market_operation.MdOrderPriority)
{
curr_market_operation = market_operations[i];
}
}
Log.assert(curr_market_operation.OrderUpdateAction != MDUpdateAction.Delete); //a deleted order should not get filled
//now we find the first operation for our order greater or equal to the transact time
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
continue;
string market_secdesc = curr_market_operation.SecurityDesc;
api.Side market_side = Utils.same_side(curr_market_operation.MdEntryType);
List<FillEntry> fills = new List<FillEntry>();
uint fill_qty = order.LastQty;
Dictionary<ulong, OrderStatus> latest_state = new Dictionary<ulong, 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.order.security_desc != market_secdesc)
continue;
if(curr_operation.order.side != market_side)
continue;
//this order is completely spent, disqualify it from future fills in case a the algo behind it tries to keep updating,
//thus creating new states ahead of this termnal state
if(_disqual.ContainsKey(curr_operation.order.order_id))
continue;
if (curr_operation.is_terminal())
{
_disqual[curr_operation.order.order_id] = 0;
continue;
}
//when we begin searching, we only want to consider the latest valid, non terminal state of our order
//FOR THIS ONE SEARCH, this is to prevent the case where an old state at a previous price is erronenously filled
if(latest_state.ContainsKey(curr_operation.order.order_id))
continue;
latest_state[curr_operation.order.order_id] = curr_operation;
//If our operation did not occur before the market's we are not filled
if (!curr_operation.TransactTime.less_or_equal(curr_market_operation.TransactTime))
continue;
//here we have the latest status of an order on the right side of the market for the right security and the right price
if (( market_side == api.Side.Buy && curr_operation.state.Price >= trade_summary.price || //fill us if we are better?
market_side == api.Side.Sell && curr_operation.state.Price <= trade_summary.price) )
//this has to be be trade price, not mdentryprx because cme will report orders down in the book that suddenly aggress
{
uint size = Math.Min(fill_qty, curr_operation.state.Quantity);
if (size > 0)
{
FillEntry f = generate_fill(transact_time, curr_operation, curr_operation.state.Price, size, null, "FIFO");
f.fill_id = order.OrderId;
if(market_side == Side.Buy)
f.bid = trade_summary.price;
else
f.ask = trade_summary.price;
f.total_traded = trade_summary.Size;
f.num_orders = curr_market_operation.NumberOfOrders;
bool same = curr_operation.order.side == Utils.same_side(trade_summary.AggressorSide);
if(same)
f.tag = $"FIFO agg side same {curr_operation.order.side}";
if(f.fully_filled)
{
f.tag = $"FIFO {f.order.order_id} FULLFILL " + (same ? $"agg side same {curr_operation.order.side}" : "");
}
fills.Add(f);
fill_qty -= size;
}
if (fill_qty <= 0)
{
Log.assert(fill_qty == 0);
break;
}
}
}
}
}
static int binary_search<T,U>(IList<U> list, T value, Func<U, T> selector, Comparer<T> comparer = null)
{
if (list == null)
throw new ArgumentNullException("list");
var comp = Comparer<T>.Default;
if (comparer != null)
comp = comparer;
if(selector == null)
selector = (x => (T)(object)x);
int lo = 0, hi = list.Count - 1;
while (lo < hi)
{
int m = lo + (hi - lo) / 2;
if (comp.Compare( selector(list[m]), value) < 0) lo = m + 1;
else hi = m - 1;
}
if (comp.Compare( selector(list[lo]), value) < 0) lo++;
return lo;
}
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);
}
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);
}
List<MBOMessage> get_mbo(ulong id)
{
if (!_exchangeorders.TryGetValue(id, out List<MBOMessage> list))
{
_exchangeorders[id] = list = new List<MBOMessage>();
}
return list;
}
}
}