282 lines
12 KiB
C#
282 lines
12 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Reactive.Linq;
|
|
using System.Reactive.Concurrency;
|
|
using System.Text;
|
|
|
|
using QuickFix;
|
|
using QuickFix.Fields;
|
|
|
|
using bts.api;
|
|
using bts.api.core;
|
|
using bts.api.orderman;
|
|
using bts.api.user;
|
|
using bts.api.admin;
|
|
using System.Collections.Concurrent;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
using QuickFix.FIX42;
|
|
using Message = QuickFix.Message;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace bts.fix
|
|
{
|
|
class DropCopySession : SessionBase
|
|
{
|
|
protected IDisposable _fillsdisp;
|
|
protected IDisposable _ordersdisp;
|
|
protected static Lazy<OrderService> _orderservice = new Lazy<OrderService>(() => bts.api.Locator.locate<OrderService>(), true);
|
|
|
|
protected readonly ConcurrentDictionary<uint, OrderRecordImmutable> _order_cache = new ConcurrentDictionary<uint, OrderRecordImmutable>();
|
|
protected readonly ConcurrentDictionary<uint, string> _fix_clorderids = new ConcurrentDictionary<uint, string>();
|
|
public DropCopySession(IFixRouter router, SessionID sess) : base(router, sess)
|
|
{
|
|
}
|
|
|
|
override public void OnLogon(SessionID sessionID)
|
|
{
|
|
Log.assert_d(sessionID.Equals(_sess));
|
|
var msg = sessionID.ToString() + " Logged on";
|
|
log_info(msg);
|
|
|
|
subscribe_fills_and_orders(sessionID);
|
|
}
|
|
override public void OnLogout(SessionID sessionID)
|
|
{
|
|
Log.assert_d(sessionID.Equals(_sess));
|
|
var msg = sessionID.ToString() + " Logged out";
|
|
log_info(msg);
|
|
|
|
if (_ordersdisp != null)
|
|
_ordersdisp.Dispose();
|
|
if (_fillsdisp != null)
|
|
_fillsdisp.Dispose();
|
|
}
|
|
|
|
override public void FromApp(Message message, SessionID sessionID)
|
|
{
|
|
Log.assert_d(sessionID.Equals(_sess));
|
|
MsgType type = Message.IdentifyType(message.ToString());
|
|
switch (type.getValue())
|
|
{
|
|
case MsgType.ORDER_STATUS_REQUEST:
|
|
case MsgType.SECURITYDEFINITIONREQUEST:
|
|
log_info("IN: " + message);
|
|
Crack(message, sessionID);
|
|
break;
|
|
default:
|
|
log_info("UNSUPPORTED MESSAGE IN: " + type.getValue());
|
|
throw new UnsupportedMessageType();
|
|
}
|
|
}
|
|
|
|
virtual public void OnMessage(OrderStatusRequest req, SessionID s)
|
|
{
|
|
uint oid = uint.Parse(req.OrderID.getValue());
|
|
if (_order_cache.TryGetValue(oid, out OrderRecordImmutable order))
|
|
{
|
|
var ostat = build_order_status(s, order);
|
|
//ostat.OrdStatusReqID = new OrdStatusReqID(req.OrdStatusReqID.getValue());
|
|
//TODO
|
|
_router.send(ostat, s);
|
|
}
|
|
}
|
|
|
|
virtual public void OnMessage(SecurityDefinitionRequest req, SessionID s)
|
|
{
|
|
if (req.SecurityRequestType.getValue() == SecurityRequestType.REQUEST_LIST_SECURITIES)
|
|
{
|
|
var secs = _router.get_securities();
|
|
if (req.IsSetSymbol())
|
|
secs = secs.Where(x => x.Symbol.ToLower() == req.Symbol.getValue().ToLower());
|
|
if (req.IsSetSecurityType())
|
|
secs = secs.Where(x => security_types_equal(x.security_type(), req.SecurityType));
|
|
if (req.IsSetSecurityExchange())
|
|
secs = secs.Where(x => exchanges_equal(x.Exchange, req.SecurityExchange));
|
|
|
|
var def = new SecurityDefinition(req.SecurityReqID,
|
|
new SecurityResponseID(Guid.NewGuid().ToString()),
|
|
new TotalNumSecurities(secs.Count()));
|
|
_router.send(def, s);
|
|
}
|
|
else
|
|
throw new IncorrectTagValue(QuickFix.Fields.Tags.SecurityRequestType);
|
|
}
|
|
|
|
|
|
|
|
virtual async protected void subscribe_fills_and_orders(SessionID sessionID)
|
|
{
|
|
var scheduler = TaskPoolScheduler.Default;
|
|
var interval = TimeSpan.FromMilliseconds(500);
|
|
var on_orders = _orderservice.Value.subscribei_orders().Naggle(interval, scheduler).PermissionFilter(_adminobservable).Table().Cache();
|
|
var on_fills = _orderservice.Value.subscribei_fills().Naggle(interval, scheduler).PermissionFilter(_adminobservable).Table().Cache();
|
|
|
|
var odone = new TaskCompletionSource<int>();
|
|
_ordersdisp = on_orders.Subscribe(o =>
|
|
{
|
|
foreach (var order in o.added)
|
|
{
|
|
var ostat = build_order_status(sessionID, order);
|
|
_order_cache[order.Key] = order;
|
|
_router.send(ostat, sessionID);
|
|
}
|
|
foreach (var order in o.changed)
|
|
{
|
|
var ostat = build_order_status(sessionID, order, true);
|
|
_router.send(ostat, sessionID);
|
|
}
|
|
odone.TrySetResult(0);
|
|
});
|
|
|
|
await odone.Task;
|
|
_fillsdisp = on_fills.Subscribe(f =>
|
|
{
|
|
foreach (var fill in f.added)
|
|
{
|
|
var fi = build_fill(sessionID, fill);
|
|
_router.send(fi, sessionID);
|
|
}
|
|
foreach (var fill in f.changed)
|
|
{
|
|
var fi = build_fill(sessionID, fill, true);
|
|
_router.send(fi, sessionID);
|
|
}
|
|
});
|
|
}
|
|
|
|
|
|
virtual protected void process_order_state(in OrderStateImmutable state, ref uint filled, ref uint leaves, ref double avgprx,
|
|
ref QuickFix.Fields.OrdStatus fstatus, ref NativeOrderStateImmutable? native, FillImmutable? fill = null)
|
|
{
|
|
filled = state.FilledQuantity;
|
|
leaves = state.Quantity - state.FilledQuantity;
|
|
avgprx = state.AvgPrice;
|
|
fstatus = translate_status(state, ref native);
|
|
}
|
|
|
|
protected bts.api.SecurityImmutable? resolve_execution_report_security(bts.api.SecurityImmutable? sec, ExecutionReport report)
|
|
{
|
|
report.SecurityExchange = convert_exchange(sec.Value.Exchange);
|
|
var sectype = sec.Value.security_type();
|
|
report.SecurityType = convert_security_type(sectype);
|
|
if (sec.Value.HasGlbx)
|
|
report.SecurityDesc = new SecurityDesc(sec.Value.Glbx.SecurityDesc);
|
|
|
|
switch (sectype)
|
|
{
|
|
case bts.api.SecurityType.Future:
|
|
report.MaturityMonthYear = new MaturityMonthYear(sec.Value.EarliestExpiration().ToString("yyyyMMdd"));
|
|
break;
|
|
case bts.api.SecurityType.Spread: //TODO this is not quite right for spreads of spreads
|
|
var leg = sec.Value.Spread.Legs.OrderBy(x => x.Security.EarliestExpiration()).First();
|
|
report.MaturityMonthYear = new MaturityMonthYear(leg.Security.EarliestExpiration().ToString("yyyyMMdd"));
|
|
break;
|
|
default:
|
|
throw new UnsupportedMessageType();
|
|
}
|
|
return sec;
|
|
}
|
|
|
|
virtual protected ExecutionReport build_fill(SessionID sess, in FillImmutable fill, bool change = false)
|
|
{
|
|
var exec = new QuickFix.Fields.ExecType(QuickFix.Fields.ExecType.PARTIAL_FILL);
|
|
QuickFix.Fields.OrdStatus status = new QuickFix.Fields.OrdStatus();
|
|
uint filled = 0; uint leaves = 0; double prx = 0.0; uint orig_qty = 0;
|
|
OrderRecordImmutable order; NativeOrderStateImmutable? native = null;
|
|
if (_order_cache.TryGetValue(fill.OrderKey, out order))
|
|
{
|
|
orig_qty = order.State.Quantity;
|
|
process_order_state(order.State, ref filled, ref leaves, ref prx, ref status, ref native);
|
|
if(Convert.ToDouble(order.State.Quantity) == fill.LastShares)
|
|
exec = new QuickFix.Fields.ExecType(QuickFix.Fields.ExecType.FILL);
|
|
}
|
|
if (change)
|
|
exec = new QuickFix.Fields.ExecType(QuickFix.Fields.ExecType.TRADE_CORRECT);
|
|
|
|
var sec = _router.lookup(fill.SecurityKey);
|
|
ExecutionReport report = new ExecutionReport(
|
|
new OrderID(fill.OrderKey.ToString()),
|
|
new ExecID(fill.FillKey.ToString()),
|
|
new QuickFix.Fields.ExecTransType( ExecTransType.NEW ),
|
|
exec,
|
|
status,
|
|
new Symbol(sec?.Symbol ?? string.Empty),
|
|
new QuickFix.Fields.Side(fill.Side == bts.api.Side.Buy ? QuickFix.Fields.Side.BUY : QuickFix.Fields.Side.SELL),
|
|
new LeavesQty(leaves),
|
|
new CumQty(filled),
|
|
new AvgPx(Convert.ToDecimal(prx)));
|
|
|
|
report.Account = new Account(fill.Account);
|
|
report.OrderQty = new OrderQty(orig_qty);
|
|
report.LastShares = new LastShares(Convert.ToDecimal(fill.LastShares));
|
|
report.LastPx = new LastPx(Convert.ToDecimal(fill.LastPrice));
|
|
var ts = fill.HasTimestamp ? fill.Timestamp.ToDateTime() : DateTime.MinValue;
|
|
report.TransactTime = new TransactTime(ts, true);
|
|
report.TradeDate = new TradeDate(ts.ToString("yyyyMMdd"));
|
|
sec = resolve_execution_report_security(sec, report);
|
|
if (native.HasValue && !string.IsNullOrEmpty(native.Value.ExchangeOrderId))
|
|
report.SecondaryOrderID = new SecondaryOrderID(native.Value.ExchangeOrderId);
|
|
|
|
if (sec.HasValue && sec.Value.security_type() == bts.api.SecurityType.Spread ||
|
|
sec.Value.security_type() == bts.api.SecurityType.Synthetic)
|
|
{
|
|
if (fill.FillKind == bts.api.orderman.Fill.Types.FillKind.Leg)
|
|
report.MultiLegReportingType = new MultiLegReportingType('2');
|
|
else
|
|
report.MultiLegReportingType = new MultiLegReportingType('3');
|
|
}
|
|
return report;
|
|
}
|
|
|
|
virtual protected ExecutionReport build_order_status(SessionID sess, in OrderRecordImmutable order, bool change = false)
|
|
{
|
|
var exec = new QuickFix.Fields.ExecType(QuickFix.Fields.ExecType.NEW);
|
|
if (_order_cache.TryGetValue(order.Key, out OrderRecordImmutable _))
|
|
exec = new QuickFix.Fields.ExecType(QuickFix.Fields.ExecType.ORDER_STATUS);
|
|
|
|
QuickFix.Fields.OrdStatus status = new QuickFix.Fields.OrdStatus();
|
|
uint filled = 0; uint leaves = 0; double prx = 0.0; NativeOrderStateImmutable? native = null;
|
|
process_order_state(order.State, ref filled, ref leaves, ref prx, ref status, ref native);
|
|
|
|
var sec = _router.lookup(order.Def.SecurityKey);
|
|
ExecutionReport report = new ExecutionReport(
|
|
new OrderID(order.Key.ToString()),
|
|
new ExecID("0"),
|
|
new QuickFix.Fields.ExecTransType(ExecTransType.STATUS),
|
|
exec,
|
|
status,
|
|
new Symbol(sec?.Symbol ?? string.Empty),
|
|
new QuickFix.Fields.Side(order.Def.Side == bts.api.Side.Buy ? QuickFix.Fields.Side.BUY : QuickFix.Fields.Side.SELL),
|
|
new LeavesQty(leaves),
|
|
new CumQty(filled),
|
|
new AvgPx(Convert.ToDecimal(prx)));
|
|
|
|
report.Account = new Account(order.Def.Account);
|
|
report.OrderQty = new OrderQty(order.State.Quantity);
|
|
report.Price = new Price(Convert.ToDecimal(order.State.Price));
|
|
report.TimeInForce = new QuickFix.Fields.TimeInForce((char)order.Def.TimeInForce);
|
|
var ts = order.State.LastChange.ToDateTime();
|
|
report.TransactTime = new TransactTime(ts, true);
|
|
if(!string.IsNullOrEmpty(order.State.LastMsg))
|
|
report.Text = new Text(order.State.LastMsg);
|
|
|
|
sec = resolve_execution_report_security(sec, report);
|
|
if (native.HasValue)
|
|
{
|
|
report.OrdType = new OrdType((char)native.Value.NativeType);
|
|
if(!string.IsNullOrEmpty(native.Value.ExchangeOrderId))
|
|
report.SecondaryOrderID = new SecondaryOrderID(native.Value.ExchangeOrderId);
|
|
}
|
|
//TODO Big race here, we need a correlation id of some sort
|
|
if (_fix_clorderids.TryGetValue(order.Key, out string clorderid))
|
|
{
|
|
report.ClOrdID = new ClOrdID(clorderid);
|
|
}
|
|
return report;
|
|
}
|
|
|
|
}
|
|
} |