using System;
using System.Collections.Generic;
using Blackwood.Framework;
using Blackwood.CBWMessages;
using TradeLink.API;
using TradeLink.Common;
namespace ServerBlackwood
{
public delegate void BWConnectedEventHandler(object sender, bool BWConnected);
public delegate void TLSendDelegate(string message, MessageTypes type, string client);
public class ServerBlackwood
{
// broker members
private BWSession m_Session;
private System.ComponentModel.IContainer components;
private uint bwHistReqID = 5000;
public event BWConnectedEventHandler BWConnectedEvent;
protected virtual void OnBWConnectedEvent(bool BWConnected) { BWConnectedEvent(this, BWConnected); }
// tradelink members
public event DebugDelegate SendDebug;
private bool _valid = false;
public bool isValid { get { return _valid; } }
PositionTracker pt = new PositionTracker();
public ServerBlackwood(TLServer tls)
{
tl = tls;
// broker stuff
m_Session = new BWSession();
m_Session.OnAccountMessage2 += new BWSession.AccountMessageHandler2(m_Session_OnAccountMessage);
m_Session.OnHistMessage2 += new BWSession.HistoricMessageHandler2(m_Session_OnHistMessage);
m_Session.OnTimeMessage2 += new BWSession.TimeMessageHandler2(m_Session_OnTimeMessage);
m_Session.OnOrderMessage += new BWSession.OrderMessageHandler(m_Session_OnOrderMessage);
m_Session.OnPositionMessage2 += new BWSession.PositionMessageHandler2(m_Session_OnPositionMessage);
m_Session.OnExecutionMessage2 += new BWSession.ExecutionMessageHandler2(m_Session_OnExecutionMessage);
m_Session.OnCancelMessage2 += new BWSession.CancelMessageHandler2(m_Session_OnCancelMessage);
m_Session.OnRejectMessage2 += new BWSession.RejectMessageHandler2(m_Session_OnRejectMessage);
// tradelink stuff
tl.newProviderName = Providers.Blackwood;
tl.newAcctRequest += new StringDelegate(ServerBlackwood_newAccountRequest);
tl.newUnknownRequest += new UnknownMessageDelegate(ServerBlackwood_newUnknownRequest);
tl.newFeatureRequest += new MessageArrayDelegate(ServerBlackwood_newFeatureRequest);
tl.newOrderCancelRequest += new LongDelegate(ServerBlackwood_newOrderCancelRequest);
tl.newSendOrderRequest += new OrderDelegateStatus(ServerBlackwood_newSendOrderRequest);
tl.newRegisterSymbols += new SymbolRegisterDel(tl_newRegisterSymbols);
tl.newPosList += new PositionAccountArrayDelegate(ServerBlackwood_newPosList);
//DOMRequest += new IntDelegate(ServerBlackwood_DOMRequest);
}
bool _noverb = true;
public bool VerbuseDebugging { get { return !_noverb; } set { _noverb = !value; tl.VerboseDebugging = VerbuseDebugging; } }
void v(string msg)
{
if (_noverb)
return;
debug(msg);
}
void tl_newRegisterSymbols(string client, string symbols)
{
Basket b = BasketImpl.FromString(symbols);
foreach (Security s in b)
{
// make sure we don't already have a subscription for this
if (_symstk.Contains(s.symbol)) continue;
BWStock stk = m_Session.GetStock(s.symbol);
stk.Subscribe();
stk.OnTrade2 += new BWStock.TradeHandler2(stk_OnTrade);
stk.OnLevel1Update2 += new BWStock.Level1UpdateHandler2(stk_OnLevel1Update);
_stocks.Add(stk);
_symstk.Add(s.symbol);
v("added level1 subscription for: " + s.symbol);
}
// get existing list
Basket list = tl.AllClientBasket;
// remove old subscriptions
for (int i = 0; i < _symstk.Count; i++)
{
if (!list.ToString().Contains(_symstk[i]) && (_stocks[i] != null))
{
debug(_symstk[i] + " not needed, removing...");
try
{
_stocks[i].Unsubscribe();
_stocks[i] = null;
_symstk[i] = string.Empty;
}
catch { }
}
}
}
Position[] ServerBlackwood_newPosList(string account)
{
foreach (BWStock s in m_Session.GetOpenPositions())
{
Position p = new PositionImpl(s.Symbol, (decimal)s.Price, s.Size, (decimal)s.ClosedPNL);
pt.Adjust(p);
v(p.symbol + " found position: " + p.ToString());
}
return pt.ToArray();
}
List<BWStock> _stocks = new List<BWStock>();
List<string> _symstk = new List<string>();
void ServerBlackwood_newImbalanceRequest()
{
v("received imbalance request.");
m_Session.RequestNYSEImbalances();
}
bool isunique(Order o)
{
bool ret = !_longint.ContainsKey(o.id); return ret;
}
IdTracker _id = new IdTracker();
long ServerBlackwood_newSendOrderRequest(Order o)
{
v(o.symbol + " received sendorder request for: " + o.ToString());
if ((o.id != 0) && !isunique(o)) {
v(o.symbol + " dropping duplicate order: " + o.ToString());
return (long)MessageTypes.DUPLICATE_ORDERID;
}
{
v("no order id from TL, setting...");
}
string sSymbol = o.symbol;
ORDER_SIDE orderSide = (o.side ? ORDER_SIDE.BUY : ORDER_SIDE.SELL);
FEED_ID orderVenue = getVenueFromBW(o); // need to add pegged order types
ORDER_TYPE orderType = (o.isStop ? (o.isLimit ? ORDER_TYPE.STOP_LIMIT : ORDER_TYPE.STOP_MARKET) : (o.isLimit ? ORDER_TYPE.LIMIT : ORDER_TYPE.MARKET));
int orderTIF = (int)getDurationFromBW(o);
uint orderSize = (uint)o.UnsignedSize;
int orderReserve = o.UnsignedSize;
double orderPrice = System.Convert.ToDouble(o.price); //(float)o.price;
double orderStopPrice = System.Convert.ToDouble(o.stopp); // (float)o.stopp;
// create a new BWOrder with these parameters
BWOrder bwOrder = new BWOrder(m_Session, sSymbol, orderSide, orderSize, orderPrice, orderType, orderTIF, orderVenue, false, orderSize);
SENDORDERUPDATE(bwOrder, o);
// check market connection
try
{
// GetStock throws an exception if not connected to Market Data
BWStock stock = m_Session.GetStock(bwOrder.Symbol);
}
catch (ClientPortalConnectionException e)
{
debug(e.Message);
}
// send the order
bwOrder.Send();
return (long)MessageTypes.OK;
}
void ServerBlackwood_newOrderCancelRequest(long tlID)
{
v("cancel request received for: " + tlID);
int bwID = 0;
bool match = false;
if (_longint.TryGetValue(tlID, out bwID))
{
if (bwID != 0)
{
v("ServerBlackwood_newOrderCancelRequest: smartID: [" + bwID + "]");
foreach (BWOrder o in m_Session.GetOpenOrders())
{
if (o.SmartID == bwID)
{
match = true;
o.Cancel();
v("found blackwood order: [" + o.SmartID + "] for tlid: [" + tlID + "] and requested cancel.");
// update map
if (!tl_canceledids.ContainsKey(tlID) && !bw_cancelids.ContainsKey(bwID))
{
debug(String.Format("Cancel request for smartID: {1} received from TL_ID: {0}", bwID, tlID));
//mark it has having had a cancel request
bw_cancelids.Add(bwID, true);
}
else if (!tl_canceledids.ContainsKey(tlID) && bw_cancelids.ContainsKey(bwID))
{
//this order has had a cancel request but has not completed
debug(String.Format("WARNING: Repeated cancel request for order {0} received from TradeLink. BWOrder is {1}. Checking if complete", tlID, bwID));
}
}
}
}
else
{
v("ERROR: bwID is zero [" + bwID + "]");
}
}
if (!match) v("could not cancel smartID: [" + bwID + "] as no matching blackwood order was found.");
}
MessageTypes[] ServerBlackwood_newFeatureRequest()
{
v("received feature request.");
List<MessageTypes> f = new List<MessageTypes>();
f.Add(MessageTypes.LIVEDATA);
f.Add(MessageTypes.LIVETRADING);
f.Add(MessageTypes.SIMTRADING);
f.Add(MessageTypes.SENDORDER);
f.Add(MessageTypes.ORDERCANCELREQUEST);
f.Add(MessageTypes.ORDERCANCELRESPONSE);
f.Add(MessageTypes.OK);
f.Add(MessageTypes.BROKERNAME);
f.Add(MessageTypes.CLEARCLIENT);
f.Add(MessageTypes.CLEARSTOCKS);
f.Add(MessageTypes.FEATUREREQUEST);
f.Add(MessageTypes.FEATURERESPONSE);
f.Add(MessageTypes.ORDERNOTIFY);
f.Add(MessageTypes.REGISTERCLIENT);
f.Add(MessageTypes.REGISTERSTOCK);
f.Add(MessageTypes.SENDORDER);
f.Add(MessageTypes.TICKNOTIFY);
f.Add(MessageTypes.VERSION);
f.Add(MessageTypes.IMBALANCEREQUEST);
//f.Add(MessageTypes.IMBALANCERESPONSE);
f.Add(MessageTypes.POSITIONREQUEST);
f.Add(MessageTypes.POSITIONRESPONSE);
f.Add(MessageTypes.ACCOUNTREQUEST);
f.Add(MessageTypes.ACCOUNTRESPONSE);
f.Add(MessageTypes.SENDORDERSTOP);
f.Add(MessageTypes.SENDORDERMARKET);
f.Add(MessageTypes.SENDORDERLIMIT);
f.Add(MessageTypes.EXECUTENOTIFY);
f.Add(MessageTypes.BARREQUEST);
f.Add(MessageTypes.BARRESPONSE);
return f.ToArray();
}
long ServerBlackwood_newUnknownRequest(MessageTypes t, string msg)
{
int _depth = 0;
MessageTypes ret = MessageTypes.UNKNOWN_MESSAGE;
switch (t)
{
case MessageTypes.DOMREQUEST:
_depth = Convert.ToInt32(msg);
v("received DOM request for depth: " + _depth);
ret = MessageTypes.OK;
break;
case MessageTypes.ISSHORTABLE:
return (long)(m_Session.GetStock(msg).IsHardToBorrow() ? 0 : 1);
case MessageTypes.BARREQUEST:
v("received bar request: " + msg);
string[] r = msg.Split(',');
DBARTYPE barType = getBarTypeFromBW(r[(int)BarRequestField.BarInt]);
int tlDateS = int.Parse(r[(int)BarRequestField.StartDate]);
int tlTimeS = int.Parse(r[(int)BarRequestField.StartTime]);
DateTime dtStart = TradeLink.Common.Util.ToDateTime(tlDateS, tlTimeS);
int tlDateE = int.Parse(r[(int)BarRequestField.StartDate]);
int tlTimeE = int.Parse(r[(int)BarRequestField.StartTime]);
DateTime dtEnd = TradeLink.Common.Util.ToDateTime(tlDateE, tlTimeE);
uint custInt = 1;
if (!uint.TryParse(r[(int)BarRequestField.CustomInterval], out custInt))
{
custInt = 1;
}
m_Session.RequestHistoricData(r[(int)BarRequestField.Symbol], barType, dtStart, dtEnd, custInt, ++bwHistReqID);
ret = MessageTypes.OK;
break;
}
return (long)ret;
}
string ServerBlackwood_newAccountRequest()
{
return _acct;
}
void stk_OnLevel1Update(object sender, CBWMsgLevel1 quote)
{
Tick k = new TickImpl(quote.Symbol.Value);
k.depth = 0;
k.bid = System.Convert.ToDecimal(quote.Bid.Value); // (decimal) quote.Bid;
k.BidSize = quote.BidSize.Value; //*****
k.ask = System.Convert.ToDecimal(quote.Ask.Value); // (decimal)quote.Ask;
k.os = quote.AskSize.Value; //*****
k.date = date;
k.time = TradeLink.Common.Util.ToTLTime();
tl.newTick(k);
}
int date = TradeLink.Common.Util.ToTLDate();
int time = 0;
void m_Session_OnTimeMessage(object sender, CBWMsgTime timeMsg)
{
date = TradeLink.Common.Util.ToTLDate(timeMsg.Time.Value); //(timeMsg.ServerTime);
time = TradeLink.Common.Util.ToTLTime(timeMsg.Time.Value); //(timeMsg.ServerTime);
}
void stk_OnLevel2Update(object sender, CBWMsgLevel2 quote)
{
Tick k = new TickImpl(quote.Symbol);
k.depth = quote.EcnOrder;
k.bid = System.Convert.ToDecimal(quote.Bid.Value); // (decimal)quote.Bid;
k.BidSize = quote.BidSize.Value;
k.be = quote.MarketMaker; k.ask = System.Convert.ToDecimal(quote.Ask.Value); // (decimal)quote.Ask;
k.os = quote.AskSize.Value;
k.oe = quote.MarketMaker;
k.date = date;
k.time = TradeLink.Common.Util.ToTLTime();
tl.newTick(k);
}
void stk_OnTrade(object sender, CBWMsgTrade print)
{
Tick k = new TickImpl(print.Symbol.Value);
k.trade = System.Convert.ToDecimal(print.Price.Value); // (decimal)print.Price;
k.size = print.TradeSize.Value; // .Size;
k.ex = print.MarketMaker.Value;
k.date = date;
k.time = TradeLink.Common.Util.ToTLTime();
tl.newTick(k);
}
TLServer tl;
public void Start()
{
if (tl != null)
tl.Start();
}
//Redundant, already subscribing to order update event.
void m_Session_OnOrderMessage(object sender, BWOrder bwo) // orderMsg
{
v(String.Format("ORDER.MSG.{0}: for BWOrder: [{1}]",bwo.Status.ToString(), bwo.SmartID));
switch (bwo.Status)
{
case STATUS.SERVER:
{
STATUSSERVERUPDATE(bwo);
}
break;
case STATUS.MARKET:
{
STATUSMARKETUPDATE(bwo);
}
break;
case STATUS.REJECT:
{
debug(String.Format("STATUS.REJECT: for BWOrder: {0}", bwo.ToString()));
}
break;
case STATUS.DONE:
{
if (bwo.SizeRemaining == 0)
{
debug(String.Format("STATUS.DONE: for BWOrder: {0}", bwo.ToString()));
}
}
break;
}
}
double _cpl = 0;
string _acct = string.Empty;
void m_Session_OnAccountMessage(object sender, CBWMsgAccount accountMsg) //BWAccount accountMsg)
{
string str = m_Session.Account;
string[] strArr = str.Split('~');
_acct = strArr[0];
_cpl = accountMsg.ClosedProfit;
}
void m_Session_OnExecutionMessage(object sender, CBWMsgExecution executionMsg)
{
if (executionMsg.Left != 0)
{
v("validating order... Left != 0");
return;
}
v("execution event for " + executionMsg.Symbol.Value + " SmartID: " + executionMsg.SmartID.Value); // revision
//foreach (KeyValuePair<long, string> ordID in _bwOrdIds)
foreach (KeyValuePair<long, int> ordID in _longint)
if (ordID.Value == executionMsg.SmartID.Value)
{
Trade t = new TradeImpl(executionMsg.Symbol.Value, System.Convert.ToDecimal(executionMsg.Price.Value), executionMsg.ExecSize.Value);
t.side = (executionMsg.Side == ORDER_SIDE.COVER) || (executionMsg.Side == ORDER_SIDE.BUY);
t.xtime = TradeLink.Common.Util.DT2FT(executionMsg.ExecutionTime.Value);
t.xdate = TradeLink.Common.Util.ToTLDate(executionMsg.ExecutionTime.Value);
t.Account = executionMsg.UserID.ToString();
t.ex = executionMsg.MarketMaker.Value;
pt.Adjust(t); // revision 2.21.13
tl.newFill(t);
v(t.symbol + " [MATCHED] sent fill notification for: " + t.ToString());
if (t.isFilled)
{
debug(String.Format("TL order has been filled: {0}", t.ToString()));
}
}
}
void m_Session_OnCancelMessage(object sender, CBWMsgCancel cancelMsg)
{
CANCELUPDATE(cancelMsg);
}
void m_Session_OnPositionMessage(object sender, CBWMsgPosition positionMsg)
{
string sym = positionMsg.Symbol.Value;
int size = positionMsg.PosSize.Value; //.Size;
decimal price = System.Convert.ToDecimal(positionMsg.Price.Value); // (decimal)positionMsg.Price;
decimal cpl = System.Convert.ToDecimal(positionMsg.CloseProfit.Value); // (decimal)positionMsg.CloseProfit;
//string ac = positionMsg.UserID.ToString();
Position p = new PositionImpl(sym, price, size, cpl, _acct);
pt.NewPosition(p);
//v(p.symbol + " new position information: " + p.ToString());
}
public bool Start(string user, string pw, string ipaddress, int data2)
{
v("got start request on blackwood connector.");
System.Net.IPAddress bwIP = System.Net.IPAddress.Parse(ipaddress);
// register for notification of a disconnection from the client portal
m_Session.OnMarketDataClientPortalConnectionChange += new BWSession.ClientPortalConnectionChangeHandler(OnMarketConnectionChange);
try
{
m_Session.ConnectToOrderRouting(user, pw, bwIP, Properties.Settings.Default.orderport, true, true, true, true); // added "true" as 7th argument
m_Session.ConnectToHistoricData(user, pw, bwIP, Properties.Settings.Default.historicalport);
m_Session.ConnectToMarketData(user, pw, bwIP, Properties.Settings.Default.dataport, true);
}
catch (Blackwood.Framework.ClientPortalConnectionException)
{
debug("error: Unable to connect to market data client portal.");
_valid = false;
return _valid;
}
_valid = true;
return _valid;
}
public /*new*/ void Stop()
{
try
{
v("got stop request on blackwood connector.");
m_Session.DisconnectFromOrders();
m_Session.DisconnectFromHistoricData();
m_Session.DisconnectFromMarketData();
m_Session.CloseSession();
m_Session.OnMarketDataClientPortalConnectionChange -= new BWSession.ClientPortalConnectionChangeHandler(OnMarketConnectionChange);
}
catch { }
}
private void OnMarketConnectionChange(object sender, bool Connected)
{
//Make sure both market data and order routing is alive before connected is true.
if (m_Session.IsConnectedToMarketData & m_Session.IsConnectedToOrderRouting)
{
OnBWConnectedEvent(Connected);
}
else
{
OnBWConnectedEvent(false);
}
//Send to debug window detailed connection info.
debug("connected market data: " + m_Session.IsConnectedToMarketData.ToString());
debug("connected order port: " + m_Session.IsConnectedToOrderRouting.ToString());
debug("connected history port: " + m_Session.IsConnectedToHistoricData.ToString());
}
private void m_Session_OnHistMessage(object sender, CBWMsgHistResponse histMsg)
{
if (histMsg.Error.Value.Length > 0)
{
debug("ERROR: " + histMsg.Error);
}
else
{
v(histMsg.Symbol + " received bar history data containing " + histMsg.Bars.Length + " bars."); // histMsg.bars.Length
if (histMsg.Bars != null && histMsg.Bars.Length > 0)
{
string sym = histMsg.Symbol;
foreach (CBWMsgHistResponse.BarData bar in histMsg.Bars)
{
int tlDate = TradeLink.Common.Util.ToTLDate(bar.Time); // .time
int tlTime = TradeLink.Common.Util.ToTLTime(bar.Time); // .time
Bar tlBar = new BarImpl((decimal)bar.Open, (decimal)bar.High, (decimal)bar.Low, (decimal)bar.Close, (int)bar.Volume, tlDate, tlTime, sym, Convert.ToInt32(histMsg.Interval)); //(int)histMsg.Interval);
for (int i = 0; i < tl.NumClients; i++)
tl.TLSend(BarImpl.Serialize(tlBar), MessageTypes.BARRESPONSE, i.ToString());
}
}
}
}
private BWTIF getDurationFromBW(Order o)
{
BWTIF bwTIF;
string strTIF = o.TIF;
switch (strTIF)
{
case "DAY":
bwTIF = BWTIF.DAY;
break;
case "IOC":
bwTIF = BWTIF.IOC;
break;
case "FOK":
bwTIF = BWTIF.FOK;
break;
case "CLO":
bwTIF = BWTIF.CLO;
break;
case "OPG":
bwTIF = BWTIF.OPG;
break;
default:
bwTIF = BWTIF.DAY;
break;
}
return bwTIF;
}
private FEED_ID getVenueFromBW(Order o)
{
FEED_ID bwVenue;
string strFeed = o.ex;
switch (strFeed)
{
case "ARCA":
bwVenue = FEED_ID.ARCA;
break;
case "BATS":
bwVenue = FEED_ID.BATS;
break;
case "INET":
bwVenue = FEED_ID.INET;
break;
case "NASDAQ":
bwVenue = FEED_ID.NASDAQ;
break;
case "SDOT":
bwVenue = FEED_ID.NYSE; // .SDOT
break;
case "NITE":
bwVenue = FEED_ID.NITE;
break;
case "EDGA":
bwVenue = FEED_ID.EDGA;
break;
case "EDGX":
bwVenue = FEED_ID.EDGX;
break;
case "CSFB":
bwVenue = FEED_ID.CSFB;
break;
default:
bwVenue = FEED_ID.NONE;
break;
}
return bwVenue;
}
private DBARTYPE getBarTypeFromBW(string str)
{
DBARTYPE bwType;
switch (str)
{
case "DAILY":
bwType = DBARTYPE.DAILY;
break;
case "WEEKLY":
bwType = DBARTYPE.WEEKLY;
break;
case "MONTHLY":
bwType = DBARTYPE.MONTHLY;
break;
case "TICK":
bwType = DBARTYPE.TICK;
break;
case "INTRADAY":
default:
bwType = DBARTYPE.INTRADAY;
break;
}
return bwType;
}
// used for order mapping
Dictionary<long, int> _longint = new Dictionary<long, int>();
Dictionary<int, long> _intlong = new Dictionary<int, long>();
List<long> sentNewOrders = new List<long>();
Dictionary<long, BWOrder> orderz = new Dictionary<long, BWOrder>();
Dictionary<int, bool> bw_cancelids = new Dictionary<int, bool>();
Dictionary<long, bool> tl_canceledids = new Dictionary<long, bool>();
void debug(string msg)
{
if (SendDebug != null)
SendDebug(msg);
}
// added 2.21.13
private void SENDORDERUPDATE(BWOrder bwo, Order o)
{
int _bwid = bwo.ClientOrderID;
// update order map
if (_tlid != 0)
{
// TL 2 broker
if (!_longint.ContainsKey(_tlid))
{
v(String.Format("Mapping TL:{0} to BW:{1}", _tlid, _bwid));
_longint.Add(_tlid, _bwid);
}
else
{
// update the existing ID
v(String.Format("-----WARNING! Updating TL:{0} with BW:{1}", _tlid, _bwid));
_longint[_tlid] = _bwid;
}
// broker 2 TL
if (!_intlong.ContainsKey(_bwid))
{
v(String.Format("Mapping BW:{0} to TL:{1}", _bwid, _tlid));
_intlong.Add(_bwid, _tlid);
}
else
{
// update the existing ID
v(String.Format("-----WARNING! Updating BW:{0} with TL:{1}", _bwid, _tlid));
_intlong[_bwid] = _tlid; // this actually shouldn't be called...!
}
// end for now...
v(String.Format("Mapped!! TL order {0} to BW {1}", _tlid, _bwid));
}
else
{
v("WARNING! Incoming TL order does not have an id. It will be generated.");
}
}
// added 2.21.13
private void STATUSSERVERUPDATE(BWOrder bwo)
{
long _tlid = 0;
int _bwid = bwo.ClientOrderID;
// rectify ClientOrderID to SmartID
int _smartID = bwo.SmartID;
// check for ClientOrderID 'key'
if (_intlong.ContainsKey(_bwid))
{
_intlong.TryGetValue(_bwid, out _tlid);
if (_tlid != 0)
{
// update TL with BWid
_intlong.Remove(_bwid);
_intlong.Add(_smartID, _tlid);
_longint[_tlid] = _smartID;
v(String.Format("RECTIFYING! Updating order map, TL:{0} with BW:{1}", _tlid, _smartID));
}
else
{
v("TL Order id is ZERO [" + _tlid + "] ");
}
}
else
{
if (_intlong.ContainsKey(_smartID))
{
v(String.Format("We have already updated BW and TL to reflect smartID [{0}]", _smartID));
}
else
{
debug(String.Format("STATUS.SERVER.UPDATE: ClientOrderID {0} cannot be found! TL_ID:{1}", _bwid, _tlid));
}
}
}
// added 2.21.13
private void STATUSMARKETUPDATE(BWOrder bwo)
{
long _tlid = 0;
int _bwid = bwo.SmartID;
if (_intlong.ContainsKey(_bwid))
{
// locate TL order via bwo.SmartID
_intlong.TryGetValue(_bwid, out _tlid);
}
else
{
v(String.Format("STATUS.MARKET.UPDATE: smartID {0} cannot be found...", _bwid));
}
// create TL order
Order o = new OrderImpl(bwo.Symbol, Convert.ToInt32(bwo.Size));
o.side = (bwo.OrderSide == ORDER_SIDE.BUY) || (bwo.OrderSide == ORDER_SIDE.COVER);
o.price = System.Convert.ToDecimal(bwo.LimitPrice);
o.stopp = System.Convert.ToDecimal(bwo.StopPrice);
o.Account = _acct;
o.ex = bwo.FeedID.ToString();
// update new orders list
if (!sentNewOrders.Contains(o.id)) {
tl.newOrder(o);
v(String.Format("------->sent order ack for TL_ID: {0}", o.id)); }
else
{
v(String.Format("STATUS.MARKET ...sentNewOrders already contains TL_ID: {0}", o.id)); }
// update orderz map
if (!orderz.ContainsKey(o.id)) {
v(String.Format("STATUS.MARKET ...adding to orderz: TL_ID: {0} with bwo: {1}.", o.id, bwo.ToString())); }
else
{
v(String.Format("STATUS.MARKET ...orderz already contains TL_ID: {0} with bwo: {1}.", o.id, bwo.ToString())); }
}
// added 2.22.13
private void CANCELUPDATE(CBWMsgCancel cancelMsg)
{
v("ServerID: " + cancelMsg.ServerID.ToString() + ", CancelID: " + cancelMsg.CancelID.ToString() + ", CancelTime: " + cancelMsg.CancelTime.ToString() +
", CIOrdID: " + cancelMsg.ClOrdID.ToString() + ", FeedID: " + cancelMsg.FeedID.ToString() + ", OrderSize: " + cancelMsg.OrderSize.ToString() +
", OrderType: " + cancelMsg.OrderType.ToString() + ", Price: " + cancelMsg.Price.ToString() + ", OrderTime: " + cancelMsg.OrderTime.ToString());
int _smartID = cancelMsg.SmartID;
long _tlid = 0;
if (_intlong.ContainsKey(_smartID))
{
if (_intlong.TryGetValue(_smartID, out _tlid))
{
debug(String.Format("Order _smartID: {0} cancelled and matched TL order {1} and sending newOrderCancel to TradeLink", _smartID, _tlid));
//remove the order mappings
_intlong.Remove(_smartID);
if (_longint.ContainsKey(_tlid)) _longint.Remove(_tlid);
// remove ids from map
if (bw_cancelids.ContainsKey(_smartID)) bw_cancelids.Remove(_smartID);
if (orderz.ContainsKey(_tlid)) orderz.Remove(_tlid);
// add TL cancel attempt
if (!tl_canceledids.ContainsKey(_tlid)) tl_canceledids.Add(_tlid, true);
// send cancel to TL and update canceded map
tl.newCancel(_tlid);
}
else
{
v("error in getting value for _intlong");
}
}
else
{
v("appears to have already sent cancel for " + _smartID);
}
}
// added revision 2.14.13
private void m_Session_OnRejectMessage(object sender, CBWMsgReject rejectMsg)
{
long _tlid = 0;
int _bwid = rejectMsg.ClientOrderID;
_intlong.TryGetValue(_bwid, out _tlid);
debug(String.Format("REJECT_TYPE.{0} for TL order [{1}]", rejectMsg.Type, _tlid));
switch (rejectMsg.RejectType.Value)
{
case REJECT_TYPE.REJECT_ORDER:
{
if (!tl_canceledids.ContainsValue(true))
{
tl.newCancel(_tlid);
tl_canceledids.Add(_tlid, true);
// possibly remove: _intlong.Remove(_tlid);
debug(String.Format("REJECT_ORDER: order has been rejected...sending cancel to TL {0} for BWOrder [{1}]", _tlid, _bwid));
}
else
{
debug(String.Format("REJECT_ORDER: has allready been called {0} for TL order [{1}]", rejectMsg.Type, _tlid));
}
//ORDERSTATUS - REJECTED - this represents the old BWOrderStatus.REJECTED
break;
}
case REJECT_TYPE.REJECT_CANCEL:
{
v("REJECT_CANCEL - m_Session_OnRejectMessage");
//ORDERSTATUS - REJECTED_CANCEL - this represents the old BWOrderStatus.REJECTED_CANCEL
break;
}
case REJECT_TYPE.REJECT_CANCEL_REPLACE:
{
v("REJECT_CANCEL_REPLACE - m_Session_OnRejectMessage");
//ORDERSTATUS - REJECTED_CANCEL_REPLACE - this represents the old BWOrderStatus.REJECTED_CANCEL_REPLACE
break;
}
default:
{
//ORDERSTATUS - UNDEFINED_REJECTION - this represents the old BWOrderStatus.UNDEFINED_REJECTION
break;
}
}
}
}
}