281 lines
12 KiB
C#
281 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.core;
|
|
using bts.api.orderman;
|
|
using bts.api.user;
|
|
using bts.api.admin;
|
|
using System.Collections.Concurrent;
|
|
using System.Runtime.CompilerServices;
|
|
|
|
namespace bts.fix
|
|
{
|
|
class DropCopySession : SessionBase, QuickFix.IApplication
|
|
{
|
|
protected IDisposable _fillsdisp;
|
|
protected IDisposable _ordersdisp;
|
|
|
|
|
|
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(QuickFix.FIX44.OrderStatusRequest req, SessionID s)
|
|
{
|
|
if (req.IsSetOrderID() && req.IsSetOrdStatusReqID())
|
|
{
|
|
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());
|
|
send(ostat, s);
|
|
}
|
|
else
|
|
send_reject(s, "Can't find order " + oid, req);
|
|
}
|
|
else
|
|
send_reject(s, "clorderid null", req);
|
|
}
|
|
|
|
virtual public void OnMessage(QuickFix.FIX44.SecurityDefinitionRequest req, SessionID s)
|
|
{
|
|
if (req.IsSetSecurityReqID() && req.IsSetSecurityRequestType() &&
|
|
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 QuickFix.FIX44.SecurityDefinition(req.SecurityReqID,
|
|
new SecurityResponseID(Guid.NewGuid().ToString()),
|
|
new SecurityResponseType(SecurityResponseType.LIST_OF_SECURITIES_RETURNED_PER_REQUEST));
|
|
send(def, s);
|
|
}
|
|
else
|
|
send_reject(s, "Can't parse secdef request", req);
|
|
}
|
|
|
|
|
|
|
|
virtual protected void subscribe_fills_and_orders(SessionID sessionID)
|
|
{
|
|
|
|
|
|
var scheduler = TaskPoolScheduler.Default;
|
|
var interval = TimeSpan.FromMilliseconds(500);
|
|
var on_orders = _orderservice.subscribei_orders().Naggle(interval, scheduler).PermissionFilter(_adminobservable).Table().Cache();
|
|
var on_fills = _orderservice.subscribei_fills().Naggle(interval, scheduler).PermissionFilter(_adminobservable).Table().Cache();
|
|
|
|
_ordersdisp = on_orders.Subscribe(o =>
|
|
{
|
|
foreach (var order in o.added)
|
|
{
|
|
var ostat = build_order_status(sessionID, order);
|
|
_order_cache[order.Key] = order;
|
|
send(ostat, sessionID);
|
|
}
|
|
foreach (var order in o.changed)
|
|
{
|
|
var ostat = build_order_status(sessionID, order, true);
|
|
send(ostat, sessionID);
|
|
}
|
|
});
|
|
|
|
_fillsdisp = on_fills.Subscribe(f =>
|
|
{
|
|
foreach (var fill in f.added)
|
|
{
|
|
var fi = build_fill(sessionID, fill);
|
|
send(fi, sessionID);
|
|
}
|
|
foreach (var fill in f.changed)
|
|
{
|
|
var fi = build_fill(sessionID, fill);
|
|
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)
|
|
{
|
|
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, QuickFix.FIX44.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(bts.api.SecurityHelper.expiration_date(sec.Value.Future).ToString("yyyyMMdd"));
|
|
break;
|
|
case bts.api.SecurityType.Option:
|
|
throw new NotSupportedException("No options yet");
|
|
case bts.api.SecurityType.Spread:
|
|
//report.MaturityMonthYear = new MaturityMonthYear(bts.api.SecurityHelper.EarliestExpiration(sec.Value).ToString("yyyyMMdd"));
|
|
//TODO
|
|
//bug here need to kill MDCLIENT
|
|
break;
|
|
default:
|
|
report.MaturityMonthYear = new MaturityMonthYear(bts.api.SecurityHelper.EarliestExpiration(sec.Value).ToString("yyyyMMdd"));
|
|
break;
|
|
}
|
|
return sec;
|
|
}
|
|
|
|
virtual protected QuickFix.FIX44.ExecutionReport build_fill(SessionID sess, in FillImmutable fill, bool change = false)
|
|
{
|
|
var exec = new QuickFix.Fields.ExecType(QuickFix.Fields.ExecType.FILL);
|
|
QuickFix.Fields.OrdStatus status = new QuickFix.Fields.OrdStatus();
|
|
uint filled = 0; uint leaves = 0; double prx = 0.0;
|
|
OrderRecordImmutable order; NativeOrderStateImmutable? native = null;
|
|
if (_order_cache.TryGetValue(fill.OrderKey, out order))
|
|
{
|
|
process_order_state(order.State, ref filled, ref leaves, ref prx, ref status, ref native);
|
|
if (leaves > 0)
|
|
exec = new QuickFix.Fields.ExecType(QuickFix.Fields.ExecType.PARTIAL_FILL);
|
|
}
|
|
if (change)
|
|
exec = new QuickFix.Fields.ExecType(QuickFix.Fields.ExecType.TRADE_CORRECT);
|
|
|
|
var sec = _router.lookup(fill.SecurityKey);
|
|
QuickFix.FIX44.ExecutionReport report = new QuickFix.FIX44.ExecutionReport(
|
|
new OrderID(fill.OrderKey.ToString()),
|
|
new ExecID(fill.FillKey.ToString()),
|
|
exec,
|
|
status,
|
|
new Symbol(sec?.Symbol ?? string.Empty),
|
|
new Side(fill.Side == bts.api.Side.Buy ? Side.BUY : Side.SELL),
|
|
new LeavesQty(leaves),
|
|
new CumQty(filled),
|
|
new AvgPx(Convert.ToDecimal(prx)));
|
|
|
|
report.Account = new Account(fill.Account);
|
|
report.LastQty = new LastQty(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)
|
|
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 QuickFix.FIX44.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);
|
|
QuickFix.FIX44.ExecutionReport report = new QuickFix.FIX44.ExecutionReport(
|
|
new OrderID(order.Key.ToString()),
|
|
new ExecID("0"),
|
|
exec,
|
|
status,
|
|
new Symbol(sec?.Symbol ?? string.Empty),
|
|
new Side(order.Def.Side == bts.api.Side.Buy ? Side.BUY : 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.SecondaryOrderID = new SecondaryOrderID(native.Value.ExchangeOrderId);
|
|
report.OrdType = new OrdType((char)native.Value.NativeType);
|
|
}
|
|
//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;
|
|
}
|
|
|
|
}
|
|
} |