public string BuildJSONFromString(string s, bool validateMsg = false, bool correctChks = true)
        {
            DateTime?logTimeStamp = null;
            int      fixStart     = s.IndexOf("8=FIX");

            if (fixStart > 0)
            {
                string dateString = s.Substring(0, fixStart - 1);
                dateString = dateString.TrimEnd('\x01', ':', ' ');
                string   format = "yyyyMMdd-HH:mm:ss.fff";
                DateTime dateTime;
                if (DateTime.TryParseExact(dateString, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
                {
                    logTimeStamp = dateTime;
                }
                s = s.Substring(fixStart);
            }


            var msg = new QuickFix.Message();

            var    chksTuple = new Tuple <string, string>(string.Empty, string.Empty);
            string sOrigChks = null;

            if (correctChks)
            {
                if (!Utils.VerifyChecksum(ref s, out chksTuple, fixChecksum: true))
                {
                    sOrigChks = chksTuple.Item1;
                }
            }

            //---------------------------------------------------------------------------------------
            msg.FromString(s, validateMsg, sessionDataDictionary, dataDictionary, messageFactory);
            //---------------------------------------------------------------------------------------


            MsgType msgType = QuickFix.Message.IdentifyType(s);
            //Very inefficient. Need to rewrite to build JSON myself.
            XElement xElem    = BuildXML(msg, msgType, logTimeStamp, sOrigChks);
            string   jsonText = JsonConvert.SerializeXmlNode(xElem.GetXmlNode());

            //=================================================================
            return(jsonText);

            //JTokenWriter writer = new JTokenWriter();
            //writer.WriteStartObject();
            //writer.WritePropertyName("name1");
            //writer.WriteValue("value1");
            //writer.WritePropertyName("name2");
            //writer.WriteStartArray();
            //writer.WriteValue(1);
            //writer.WriteValue(2);
            //writer.WriteEndArray();
            //writer.WriteEndObject();

            //JObject o = (JObject)writer.Token;

            //return o.ToString();
        }
示例#2
0
        public new void crack(QuickFix.Message message, QuickFix.SessionID sessionID)
        {
            BeginString beginString = new BeginString();

            message.getHeader().getField(beginString);
            String value = beginString.getValue();

            if (value.Equals("FIX.4.0"))
            {
                ((QuickFix40.MessageCracker) this).crack(message, sessionID);
            }
            else if (value.Equals("FIX.4.1"))
            {
                ((QuickFix41.MessageCracker) this).crack(message, sessionID);
            }
            else if (value.Equals("FIX.4.2"))
            {
                ((QuickFix42.MessageCracker) this).crack(message, sessionID);
            }
            else if (value.Equals("FIX.4.3"))
            {
                ((QuickFix43.MessageCracker) this).crack(message, sessionID);
            }
            else if (value.Equals("FIX.4.4"))
            {
                ((QuickFix44.MessageCracker) this).crack(message, sessionID);
            }
            else
            {
                onMessage(message, sessionID);
            }
        }
示例#3
0
        // convenience constructor
        public Message(float step, Lifeline from, Lifeline to, String msg, float actlen, QuickFix.Message m) : this()
        {
            this.Step = step;
            GoText lab = this.FromLabel as GoText;

            if (lab != null)
            {
                lab.Text = msg;
            }
            if (from != null)
            {
                this.FromPort = from.Port;
            }
            if (to != null)
            {
                this.ToPort = to.Port;
            }
            if (actlen > 0 && to != null)
            {
                Activation act = new Activation();
                act.Begin = step;
                act.End   = step + actlen;
                to.Add(act);
            }
            FixMessage = m;
        }
示例#4
0
        //See onGatewayStatusMessage or MarketDataSnapshotFullRefresh for example of parsing a group
        public void parseMessage(QuickFix.Message message, QuickFix.SessionID sessionID)
        {
            try
            {
                updateDisplay(message.GetType().FullName);

                QuickFix.SenderSubID     senderID = new SenderSubID();
                QuickFix.TargetSubID     targetID = new TargetSubID();
                QuickFix.OnBehalfOfSubID oboID    = new OnBehalfOfSubID();

                if (message.getHeader().isSetField(senderID))
                {
                    updateDisplay(string.Format("SenderSubID: {0}", message.getHeader().getField(senderID)));
                }

                if (message.getHeader().isSetField(targetID))
                {
                    updateDisplay(string.Format("TargetSubID: {0}", message.getHeader().getField(targetID)));
                }

                if (message.getHeader().isSetField(oboID))
                {
                    updateDisplay(string.Format("OnBehalfOfSubID: {0}", message.getHeader().getField(oboID)));
                }

                foreach (QuickFix.Field f in message)
                {
                    updateDisplay(string.Format("TAG: {0} = {1}", f.getField(), f));
                }
            }
            catch (Exception ex)
            {
                updateDisplay(ex.ToString());
            }
        }
        public string BuildJSON(QuickFix.Message msg, MsgType msgType, DateTime?logTimeStamp = null, string origChkSum = null)
        {
            ////Debug.WriteLine(" ~~~> " + msg.GetType().ToString());
            //SessionID sessionID = msg.GetSessionID(msg);

            //FIXClassInfo fixClass = null;
            //if (msg.GetType() == typeof(QuickFix.Message))
            //{
            //    var classes = fixClasses[msgType.ToString(), Utils.NormalizeFIXNameSpace(sessionID.BeginString)];
            //    if (classes != null && classes.Count > 0)
            //        fixClass = classes[0];
            //}

            ////var root = new XElement(msg.GetType().ToString());
            //var root = new XElement((fixClass != null) ? fixClass.type.FullName : msg.GetType().ToString());
            //root.Add(new XAttribute("MessageType", msgType.ToString()));
            //root.Add(new XAttribute("Session", sessionID.ToString()));
            //if (logTimeStamp.HasValue)
            //    root.Add(new XAttribute("LogTimeStamp", logTimeStamp.Value));

            //var header = new XElement(msg.Header.GetType().ToString());
            //ProcessFieldMapToXML(header, msg.Header);
            //root.Add(header);

            //var body = new XElement(msg.GetType().ToString() + ".Body");
            //ProcessFieldMapToXML(body, msg);
            //root.Add(body);

            //var trailer = new XElement(msg.Trailer.GetType().ToString());
            //ProcessFieldMapToXML(trailer, msg.Trailer, origChkSum);
            //root.Add(trailer);

            //return root;
            return("");
        }
示例#6
0
        public override string ProcCancelOrder(ref bool comp, string symbol, string id, int qty)
        {
            QuickFix.Message co = (QuickFix.Message)MessageFactory.OrderCancelRequest(TradingSession());
            string           SecType = string.Empty, IndexSymbol = string.Empty, expiry = string.Empty, exchangeMarket = string.Empty;

            if (!SplitSymbol(symbol, ref SecType, ref IndexSymbol, ref expiry, ref exchangeMarket))
            {
                return(string.Empty);
            }
            if (co == null)
            {
                return(string.Empty);
            }

            Dictionary <EFixTags, string> cancelOrderTags = new Dictionary <EFixTags, string>();

            Debug.Assert(orderTypeList.ContainsKey(id), "Unable to cancel Not Exist Order Id: " + id);
            if (orderTypeList.ContainsKey(id))
            {
                cancelOrderTags[EFixTags.OrigClOrderID] = id;
                cancelOrderTags[EFixTags.ClOrdID]       = orderTypeList[id].mainOrderId + "." + (++orderTypeList[id].subOrderId);
                cancelOrderTags[EFixTags.Symbol]        = IndexSymbol;
                cancelOrderTags[EFixTags.HandInst]      = "2";
                cancelOrderTags[EFixTags.Side]          = IsBuy(qty) ? BUY : SELL;
                cancelOrderTags[EFixTags.OrderQty]      = Math.Abs(qty).ToString();
                cancelOrderTags[EFixTags.OrderType]     = orderTypeList[id].IsLimit?LIMIT:MARKET;
                fillFixMessageStructure(cancelOrderTags, ref co);

                return(SendMessageToSession(co) ? cancelOrderTags[EFixTags.ClOrdID] : string.Empty);
            }
            else
            {
                return(string.Empty);
            }
        }
示例#7
0
        public virtual void fromAdmin(QuickFix.Message message, QuickFix.SessionID sessionID)
        {
            Console.WriteLine("fromAdmin: " + message);
            updateDisplay("fromAdmin: " + DateTime.Now.ToString("hh:mm:ss.fff"));

            crack(message, sessionID);
        }
示例#8
0
        public bool SENT_REJECT(int reason, int refTag)
        {
            if (!SENT_REJECT())
            {
                return(false);
            }

            QuickFix.Message msg = responder.msgLookup[QuickFix.Fields.MsgType.REJECT].First();

            if (!msg.IsSetField(QuickFix.Fields.Tags.SessionRejectReason))
            {
                return(false);
            }

            QuickFix.Fields.SessionRejectReason reasonField = new QuickFix.Fields.SessionRejectReason();
            msg.GetField(reasonField);
            if (reasonField.getValue() != reason)
            {
                return(false);
            }

            if (!msg.IsSetField(QuickFix.Fields.Tags.RefTagID))
            {
                return(false);
            }

            QuickFix.Fields.RefTagID refTagField = new QuickFix.Fields.RefTagID();
            msg.GetField(refTagField);
            if (refTagField.getValue() != refTag)
            {
                return(false);
            }

            return(true);
        }
        public QuickFix.FixMessageDescriptor GetDescriptor()
        {
            try
            {
                QuickFix.Message msg = new QuickFix.Message();

                msg.FromString(_message, false, null, null);

                string beginString = msg.Header.GetField(QuickFix.Fields.Tags.BeginString);

                QuickFix.DataDictionary.DataDictionary dict = _dicSource.GetDictionaryForBeginString(beginString);

                QuickFix.Message theMsg = new QuickFix.Message();

                theMsg.FixMessageDescriptorEnabled = true;

                theMsg.FromString(_message, true, dict, dict);

                return theMsg.GetDescriptor();

            }
            catch (Exception ex)
            {
                Trace.TraceError("{0}: Error while parsing fix message: {1}", this, ex);

                return null;
            }
        }
        public IList <FixMesageValidationErrorDescriptor> GetValidationErrors()
        {
            try
            {
                QuickFix.Message msg = new QuickFix.Message();

                msg.FromString(_message, false, null, null);

                string beginString = msg.Header.GetField(QuickFix.Fields.Tags.BeginString);
                string msgType     = msgType = msg.Header.GetField(QuickFix.Fields.Tags.MsgType);
                QuickFix.DataDictionary.DataDictionary dict = _dicSource.GetDictionaryForBeginString(beginString);


                dict.Validate(msg, beginString, msgType);
                return(null);
            }
            catch (Exception ex)
            {
                //TODO: create a validation method on fix dictionary that retuns a list of errors instead of just throwing on the first one
                FixMesageValidationErrorDescriptor descr = new FixMesageValidationErrorDescriptor();

                descr.Message = ex.Message;

                return(new List <FixMesageValidationErrorDescriptor>(new FixMesageValidationErrorDescriptor[] { descr }));
            }
        }
示例#11
0
        public void UnwrapMessage_AsMsgType_Ok_Sandbox()
        {
            // arrange
            var jsonFixMsg = new JsonFixMessageReceived
            {
                localPseudoHeader = "myPseudoHeader",
                messageTypeCode35 = "D",
                rawFixPayload     = "8=FIX.4.2\u00019=00\u000135=D\u000149=Sender\u000156=Target\u000134=0\u000152=99990909-17:17:17.777\u000154=1\u000155=ABC\u000111=BUY000000001\u000138=1000\u000140=2\u000144=1001.000\u000159=3\u0001117=A001\u000146=A001\u000110=000\u0001"
            };

            // act
            QuickFix.Message fixMsg = _jsonFixWrapper.Unwrap(jsonFixMsg);
            // QuickFix.FIX42.NewOrderSingle newOrderD = new QuickFix.FIX42.NewOrderSingle();

            QuickFix.FIX42.NewOrderSingle newOrderD = _jsonFixWrapper.UnwrapAsType <NewOrderSingle>(jsonFixMsg);


            // issue how to downcast

            // assert
            var expectedTicker = "ABC";
            var expectedTarget = "Target";

            var actualTarget = newOrderD.Header.GetField(new QuickFix.Fields.TargetCompID()).getValue();
            var actualTicker = newOrderD.Header.GetField(new QuickFix.Fields.Symbol()).getValue();

            Assert.Equal(expectedTicker, actualTicker);
            Assert.Equal(expectedTarget, actualTarget);
        }
示例#12
0
        public new void crack(QuickFix.Message message, QuickFix.SessionID sessionID)
        {
            BeginString beginString = new BeginString();

            message.getHeader().getField(beginString);
            crack(message, sessionID, beginString);
        }
示例#13
0
        public bool Send(string msgStr)
        {
            QuickFix.Fields.MsgType msgType = QuickFix.Message.IdentifyType(msgStr);
            string beginString = QuickFix.Message.ExtractBeginString(msgStr);

            QuickFix.Message message = messageFactory.Create(beginString, msgType.Obj);
            QuickFix.DataDictionary.DataDictionary dd = new QuickFix.DataDictionary.DataDictionary();
            message.FromString(msgStr, false, dd, dd, _defaultMsgFactory);

            if (!msgLookup.ContainsKey(msgType.getValue()))
            {
                msgLookup.Add(msgType.getValue(), new Queue <QuickFix.Message>());
            }

            msgLookup[msgType.getValue()].Enqueue(message);

            QuickFix.Fields.PossDupFlag possDup = new QuickFix.Fields.PossDupFlag(false);
            if (message.Header.IsSetField(possDup))
            {
                message.Header.GetField(possDup);
            }

            if (possDup.getValue() && msgType.getValue() != QuickFix.Fields.MsgType.SEQUENCE_RESET)
            {
                dups.Enqueue(message);
            }

            return(true);
        }
        public override bool HandleMessage(Message message)
        {
            var ack = message as CollateralInquiryAck;
            var pr  = message as CollateralReport;

            if (ack == null && pr == null)
            {
                return(false);
            }

            var id = ack?.CollInquiryID.Obj ?? pr?.CollInquiryID.Obj;

            if (!Requests.TryGetValue(id, out var request))
            {
                Log.WriteWarningAsync(nameof(HandleMessage), "Handle collateral report from Jfd", $"Received response with unknown id {id}").GetAwaiter().GetResult();
                return(false);
            }
            if (ack != null)
            {
                request.ProcessResponse(ack);
            }
            else
            {
                request.ProcessResponse(pr);
            }
            if (request.Status == RequestStatus.Completed)
            {
                Requests.Remove(request.Id);
            }
            return(true);
        }
示例#15
0
 internal static void ReplicateFixMessage(QuickFix.Message msg)
 {
     try
     {
         lock (m_LockedObj)
         {
             string msgTypeString   = msg.getHeader().getField(m_msgTypeTag);
             Guid[] subscribersKeys = GetFixMsgSubscribers(msgTypeString);
             if (subscribersKeys != null && subscribersKeys.Length > 0)
             {
                 foreach (Guid key in subscribersKeys)
                 {
                     PushUpdates(new IReplicationResponse[] { new ReplicatedFixMsg()
                                                              {
                                                                  ClientKey = key, FixMessage = msg.ToString(), ResponseDateTime = DateTime.Now, FixVersion = msg.getHeader().getField(m_fixMsgVersionTag)
                                                              } });
                 }
             }
         }
     }
     catch (Exception ex)
     {
         Counters.IncrementCounter(CountersConstants.ExceptionMessages);
         SystemLogger.WriteOnConsoleAsync(true, string.Format("ReplicateFixMessage, Error: {0} ", ex.Message), ConsoleColor.Red, ConsoleColor.Black, true);
     }
 }
示例#16
0
        public static string PrettyPrint(this Message msg)
        {
            var fields = ListFields(msg);
            var str    = string.Join("; ", from f in fields select $"{f.Name}={f.Value}");

            return(str);
        }
示例#17
0
        private static IEnumerable <FixField> ListFields(Message msg)
        {
            var str   = msg.ToString();
            var parts = str.Split(new[] { '\x01' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var part in parts)
            {
                var i = part.IndexOf('=');
                if (i < 0)
                {
                    continue;
                }

                var name  = part.Substring(0, i);
                var value = part.Substring(i + 1);

                int.TryParse(name, out var tag);
                if (_Fields.TryGetValue(tag, out var tagName))
                {
                    name = tagName;
                }

                if (_FieldFormatters.TryGetValue(tag, out var formatter))
                {
                    value = formatter(value);
                }

                yield return(new FixField
                {
                    Name = name,
                    Value = value
                });
            }
        }
示例#18
0
        public QuickFix.Message ReadNewOrderMultilegBytes()
        {
            var msg = new QuickFix.Message();

            msg.FromString(newOrderMultilegBytes, true, dataDictionary, dataDictionary, msgFactory);
            return(msg);
        }
示例#19
0
        public QuickFix.Message ReadQuoteStatusRequestWithNestedGrp()
        {
            var msg = new QuickFix.Message();

            msg.FromString(quoteStatusRequestWithNestedGrpsBytes, true, dataDictionary, dataDictionary, msgFactory);
            return(msg);
        }
示例#20
0
        public QuickFix.Message ReadMarketDataRequest()
        {
            var msg = new QuickFix.Message();

            msg.FromString(marketDataRequestBytes, true, dataDictionary, dataDictionary, msgFactory);
            return(msg);
        }
        public QuickFix.FixMessageDescriptor GetDescriptor()
        {
            try
            {
                QuickFix.Message msg = new QuickFix.Message();

                msg.FromString(_message, false, null, null);

                string beginString = msg.Header.GetField(QuickFix.Fields.Tags.BeginString);

                QuickFix.DataDictionary.DataDictionary dict = _dicSource.GetDictionaryForBeginString(beginString);


                QuickFix.Message theMsg = new QuickFix.Message();

                theMsg.FixMessageDescriptorEnabled = true;

                theMsg.FromString(_message, true, dict, dict);

                return(theMsg.GetDescriptor());
            }
            catch (Exception ex)
            {
                Trace.TraceError("{0}: Error while parsing fix message: {1}", this, ex);

                return(null);
            }
        }
示例#22
0
        public virtual void fromApp(QuickFix.Message message, QuickFix.SessionID sessionID)
        {
            try
            {
                QuickFix.MsgType msgType = new QuickFix.MsgType();
                message.getHeader().getField(msgType);
                string msgTypeValue = msgType.getValue();

                log.WriteLog(string.Format("fromApp: {0}", msgTypeValue));

                switch (msgTypeValue)
                {
                case "UAT":
                    onGatewayStatusMessage((QuickFix42.Message)message, sessionID);
                    break;

                case "UAP":
                    onPositionReportMessage((QuickFix42.Message)message, sessionID);
                    break;

                default:
                    crack(message, sessionID);
                    break;
                }
            }
            catch (QuickFix.UnsupportedMessageType umt)
            {
                log.WriteLog("UnsupportedMessageType: " + umt.Message);
                parseMessage(message, sessionID);
            }
            catch (Exception ex)
            {
                log.WriteLog(ex.ToString());
            }
        }
示例#23
0
 public void ToApp(QuickFix.Message message, QuickFix.SessionID sessionId)
 {
     if (doNotSendException != null)
     {
         throw doNotSendException;
     }
 }
        public IList<FixMesageValidationErrorDescriptor> GetValidationErrors()
        {
            try
            {
                QuickFix.Message msg = new QuickFix.Message();

                msg.FromString(_message, false, null, null);

                string beginString = msg.Header.GetField(QuickFix.Fields.Tags.BeginString);
                string msgType = msgType = msg.Header.GetField(QuickFix.Fields.Tags.MsgType);
                QuickFix.DataDictionary.DataDictionary dict = _dicSource.GetDictionaryForBeginString(beginString);

                dict.Validate(msg, beginString, msgType);
                return null;
            }
            catch (Exception ex)
            {
                //TODO: create a validation method on fix dictionary that retuns a list of errors instead of just throwing on the first one
                FixMesageValidationErrorDescriptor descr = new FixMesageValidationErrorDescriptor();

                descr.Message = ex.Message;

                return new List<FixMesageValidationErrorDescriptor>(new FixMesageValidationErrorDescriptor[] { descr });

            }
        }
示例#25
0
        public void TestLastMsgSeqNumProcessed()
        {
            // Disabled by default
            Assert.That(!session.EnableLastMsgSeqNumProcessed);

            session.EnableLastMsgSeqNumProcessed = true;

            // Logon
            Logon();
            QuickFix.Message msg    = responder.msgLookup[QuickFix.Fields.MsgType.LOGON].Last();
            int lastSeqNumProcessed = msg.Header.GetInt(QuickFix.Fields.Tags.LastMsgSeqNumProcessed);

            Assert.That(lastSeqNumProcessed == 1);

            // NOS
            QuickFix.FIX42.NewOrderSingle order = new QuickFix.FIX42.NewOrderSingle(
                new QuickFix.Fields.ClOrdID("1"),
                new QuickFix.Fields.HandlInst(QuickFix.Fields.HandlInst.MANUAL_ORDER),
                new QuickFix.Fields.Symbol("IBM"),
                new QuickFix.Fields.Side(QuickFix.Fields.Side.BUY),
                new QuickFix.Fields.TransactTime(),
                new QuickFix.Fields.OrdType(QuickFix.Fields.OrdType.LIMIT));

            order.Header.SetField(new QuickFix.Fields.TargetCompID(sessionID.SenderCompID));
            order.Header.SetField(new QuickFix.Fields.SenderCompID(sessionID.TargetCompID));
            order.Header.SetField(new QuickFix.Fields.MsgSeqNum(seqNum++));
            session.Send(order);

            msg = responder.msgLookup[QuickFix.Fields.MsgType.NEW_ORDER_D].Last();
            lastSeqNumProcessed = msg.Header.GetInt(QuickFix.Fields.Tags.LastMsgSeqNumProcessed);
            Assert.That(lastSeqNumProcessed == 1);
        }
示例#26
0
 public void FromAdmin(QuickFix.Message message, QuickFix.SessionID sessionID)
 {
     if (fromAdminException != null)
     {
         throw fromAdminException;
     }
 }
示例#27
0
        public void AssertMicrosecondsInTag(string msgType, int tag, bool shouldHaveMicrosecond)
        {
            QuickFix.Message msg         = responder.msgLookup[msgType].Last();
            string           sendingTime = msg.Header.GetString(tag);
            Match            m           = microsecondRegex.Match(sendingTime);

            Assert.That(m.Success == shouldHaveMicrosecond);
        }
示例#28
0
        private void SendTheMessage(QuickFix.Message msg)
        {
            msg.Header.SetField(new QuickFix.Fields.TargetCompID(sessionID.SenderCompID));
            msg.Header.SetField(new QuickFix.Fields.SenderCompID(sessionID.TargetCompID));
            msg.Header.SetField(new QuickFix.Fields.MsgSeqNum(seqNum++));

            session.Next(msg.ToString());
        }
示例#29
0
 public void ToApp(QuickFix.Message message, QuickFix.SessionID sessionId)
 {
     _strategy.ProcessToApp(message, QuickFix.Session.LookupSession(sessionId));
     Trace.WriteLine("## ToApp: " + message.ToString());
     if (MessageEvent != null)
     {
         MessageEvent(message, false);
     }
 }
示例#30
0
 public void FromApp(QuickFix.Message message, QuickFix.SessionID sessionID)
 {
     Trace.WriteLine("## FromApp: " + message.ToString());
     if (MessageEvent != null)
     {
         MessageEvent(message, true);
     }
     Crack(message, sessionID);
 }
示例#31
0
 private void SendLogon(QuickFix.Message msg)
 {
     msg.Header.SetField(new QuickFix.Fields.TargetCompID(sessionID.SenderCompID));
     msg.Header.SetField(new QuickFix.Fields.SenderCompID(sessionID.TargetCompID));
     msg.Header.SetField(new QuickFix.Fields.MsgSeqNum(seqNum++));
     msg.Header.SetField(new QuickFix.Fields.SendingTime(System.DateTime.UtcNow));
     msg.SetField(new QuickFix.Fields.HeartBtInt(1));
     session.Next(msg.ToString());
 }
示例#32
0
 public override string ProcMarketOrder(ref bool comp, string symbol, string price, int qty)
 {
     QuickFix.Message sno = generateOrderMessage(symbol, price, qty, false);
     if (sno == null)
     {
         return(string.Empty);
     }
     return(SendMessageToSession(sno) ? sno.getField((int)EFixTags.ClOrdID) : string.Empty);
 }
示例#33
0
        /// <summary>
        /// Edit the order for the ID specified - throws an exception if the order isnt working
        /// </summary>
        /// <param name="myID"></param>
        /// <param name="newQty">new qty if specified</param>
        /// <param name="newPrice">new price if specified</param>
        public void ReplaceOrder(string myID, double? newQty, double? newPrice, double? newStopPx)
        {
            KaiTrade.Interfaces.Order myOrder = null;
            try
            {
                // Get Order
                KaiTrade.Interfaces.OrderManager myOM = AppFactory.Instance().GetOrderManager();
                myOrder = myOM.GetOrder(myID);
                if (myOrder == null)
                {
                    string myError = "Order not found cannot edit:" + myID;
                    Exception myE = new Exception(myError);
                    throw myE;
                }
                if (m_ORLog.IsInfoEnabled)
                {
                    m_ORLog.Info("ReplaceOrder:"+ myOrder.ToString());
                }
                // are these changes?
                if (!newValueDifferentFromOld(myOrder, newQty, newPrice, newStopPx))
                {
                    string myError = "The new fields in the Replace request are the same as the existing fields" + myID;
                    Exception myE = new Exception(myError);
                    throw myE;
                }
                // Is this a triggered order
                if (myOrder.TriggerOrderID.Length > 0)
                {
                    if (newQty.HasValue)
                    {
                        myOrder.OrderQty = new QuickFix.OrderQty((double)newQty);
                    }

                    if (newPrice.HasValue)
                    {
                        myOrder.Price = new QuickFix.Price((double)newPrice);
                    }
                    if (newStopPx.HasValue)
                    {
                        myOrder.StopPx = new QuickFix.StopPx((double)newStopPx);
                    }
                    return;
                }
                // store the clordID's
                //NOT USED? QuickFix.OrigClOrdID myOrigClOrdID;
                QuickFix.ClOrdID myClOrdID;

                // check if we are pending cancel or pending mod
                if (order.LastOrderCommand == KaiTrade.Interfaces.LastOrderCommand.replace)
                {
                    // we are currently doing a replace - cannot do another
                    string myError = "Order is already processing a replace cannot modify at this time:" + myID;
                    Exception myE = new Exception(myError);
                    throw myE;
                }

                if (order.LastOrderCommand == KaiTrade.Interfaces.LastOrderCommand.cancel)
                {
                    // we are currently doing a cancel - cannot do a mod
                    string myError = "Order is already processing a cancel cannot modify" + myID;
                    Exception myE = new Exception(myError);
                    throw myE;
                }

                // check that the order is working
                if (!myOrder.IsWorking())
                {
                    if ((myOrder.OrdType.getValue() == QuickFix.OrdType.STOP) || (myOrder.OrdType.getValue() == QuickFix.OrdType.STOP_LIMIT))
                    {
                        // no action
                    }
                    else
                    {
                        string myError = "Order is not in a working state cannot replace:" + myID;
                        Exception myE = new Exception(myError);
                        throw myE;
                    }
                }
                // Check the limits for the order
                string myTextErr;
                double qty;
                if (newQty.HasValue)
                {
                    qty = newQty.Value;
                }
                else
                {
                    qty = myOrder.OrderQty.getValue();
                }
                double px;
                if (newPrice.HasValue)
                {
                    px = newPrice.Value;
                }
                else
                {
                    px = myOrder.Price.getValue();
                }
                if (LimitChecker.Instance().BreaksLimits(out myTextErr, myOrder, qty, px))
                {
                    myOrder.OrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.REJECTED);
                    myOrder.Text = "You have exceeded the order qty limit - please re-enter";
                    Exception myE = new Exception("You have exceeded the order qty limit - please re-enter");
                    throw myE;
                }

                // Create a FIX cancel replace messsage

                QuickFix.Message myFixMsg = new QuickFix.Message();
                QuickFix.MsgType msgType = new QuickFix.MsgType("G");
                myFixMsg.getHeader().setField(msgType);
                QuickFix.BeginString myBeginString = new QuickFix.BeginString("FIX.4.4");
                myFixMsg.getHeader().setField(myBeginString);

                // OrderID
                if (myOrder.OrderID == null)
                {
                    myOrder.Text = "No order ID found cannot modify order";
                    Exception myE = new Exception("No order ID found cannot modify order");
                    throw myE;
                }

                // set the original to the existing clordid
                myOrder.OrigClOrdID = new QuickFix.OrigClOrdID(myOrder.ClOrdID.getValue());
                myFixMsg.setField(myOrder.OrigClOrdID);

                myFixMsg.setField(myOrder.OrderID);

                ////Side
                myFixMsg.setField(myOrder.Side);

                // set up the product details in the message
                myOrder.Product.Set(myFixMsg);

                //// Transact Time
                myOrder.TransactTime = new QuickFix.TransactTime(DateTime.Now.ToUniversalTime());
                myFixMsg.setField(myOrder.TransactTime);

                myFixMsg.setField(myOrder.OrdType);

                // Create the message wrapper used to send the order cancel to the driver
                KaiTrade.Interfaces.Message myMsg = new KaiTCPComm.KaiMessageWrap();

                myMsg.Label = "G";

                string myDriverCode = "";
                // A trade venue must be specified on the order
                KaiTrade.Interfaces.Venue myVenue = null;
                if (myOrder.Product.TradeVenue.Length > 0)
                {
                    // get the driver code and session details from the venue manager
                    myVenue = AppFactory.Instance().GetVenueManager().GetVenue(myOrder.Product.TradeVenue);
                    if (myVenue != null)
                    {
                        myDriverCode = myVenue.DriverCode;
                        if (myVenue.TargetVenue.Length > 0)
                        {
                            myMsg.VenueCode = myVenue.TargetVenue;
                        }
                        if (myVenue.BeginString.Length > 0)
                        {
                            // this is the FIX version the server wants, we convert between
                            // versions in the FIX client
                            myMsg.Format = myVenue.BeginString;
                        }

                        if (myVenue.SID.Length > 0)
                        {
                            QuickFix.SenderCompID mySID = new QuickFix.SenderCompID(myVenue.SID);
                            myFixMsg.getHeader().setField(mySID);
                            myMsg.ClientID = myVenue.SID;
                        }
                        if (myVenue.TID.Length > 0)
                        {
                            QuickFix.TargetCompID myTID = new QuickFix.TargetCompID(myVenue.TID);
                            myFixMsg.getHeader().setField(myTID);
                            myMsg.TargetID = myVenue.TID;
                        }
                    }
                    else
                    {
                        string myErr = "Invalid Venue Code:" + myOrder.Product.TradeVenue;
                        m_Log.Error(myErr);
                        Exception myE = new Exception(myErr);
                        throw myE;
                    }
                }
                else
                {
                    string myErr = "No Venue Code specified on product:";
                    m_Log.Error(myErr);
                    Exception myE = new Exception(myErr);
                    throw myE;
                }

                // process any venue field bags - do this prior to the order bags
                // to allow the order setting to override the venues
                List<KaiTrade.Interfaces.Field> myFieldBag;
                KTAFacade.Instance().SetBag(out myFieldBag, myVenue.ReplaceBag, ",");

                foreach (KaiTrade.Interfaces.Field myField in myFieldBag)
                {
                    try
                    {
                        myFixMsg.setString(int.Parse(myField.ID), myField.Value);
                    }
                    catch (Exception myE)
                    {
                        m_Log.Error("replace Extra tags from venue error:", myE);
                    }
                }

                // process any additional tags for the order
                foreach (KaiTrade.Interfaces.Field myField in myOrder.ReplaceBag)
                {
                    try
                    {
                        myFixMsg.setString(int.Parse(myField.ID), myField.Value);
                    }
                    catch (Exception myE)
                    {
                        m_Log.Error("replace Extra tags error:", myE);
                    }
                }
                if (myOrder.Account != null)
                {
                    if (myOrder.Account.getValue().Length > 0)
                    {
                        myFixMsg.setField(myOrder.Account);
                    }
                }

                try
                {
                    //Send the message
                    KaiTrade.Interfaces.Driver myDrv = AppFactory.Instance().GetDriverManager().GetDriver(myDriverCode);
                    if (myDrv != null)
                    {
                        // save the existing clordid and set the new clordid
                        myClOrdID = myOrder.ClOrdID;
                        myOrder.ClOrdID = new QuickFix.ClOrdID(KaiUtil.Identities.Instance.genReqID());
                        myFixMsg.setField(myOrder.ClOrdID);
                        // Associate the CLOrdID with this order
                        AppFactory.Instance().GetOrderManager().AssociateClOrdID(myOrder.ClOrdID.getValue(), myOrder);

                        if (newQty.HasValue)
                        {
                            myOrder.OrderQty = new QuickFix.OrderQty((double)newQty);
                            myFixMsg.setField(myOrder.OrderQty);
                        }

                        if (newPrice.HasValue)
                        {
                            myOrder.Price = new QuickFix.Price((double)newPrice);
                            myFixMsg.setField(myOrder.Price);
                        }
                        if (newStopPx.HasValue)
                        {
                            myOrder.StopPx = new QuickFix.StopPx((double)newStopPx);
                            myFixMsg.setField(myOrder.StopPx);
                        }

                        // Set the FIX string as message data
                        myMsg.Data = myFixMsg.ToString();

                        // inform order manager clients that the order has changed
                        myOM.SetChanged(myOrder.Identity);
                        // send the message for processing
                        //myDrv.Send(myMsg);
                        // send the message for processing
                        order.LastOrderCommand = KaiTrade.Interfaces.LastOrderCommand.replace;
                        //SendDelegate mySend = new SendDelegate(myDrv.Send);
                        //IAsyncResult ar = mySend.BeginInvoke(myMsg, SRCallback, "123456789");
                        myDrv.Send(myMsg);
                    }
                    else
                    {
                        string myError = "Driver not found for code:" + myDriverCode;
                        m_Log.Error(myError);
                        Exception myE = new Exception(myError);
                        throw myE;
                    }
                }
                catch (Exception myE)
                {
                    m_Log.Error("EditOrder:Sendnessage part" + myOrder.Identity, myE);
                    myOrder.OrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.REJECTED);
                    throw (myE);
                }
            }
            catch (Exception myE)
            {
                m_Log.Error("ReplaceOrder:", myE);
                if (myOrder != null)
                {
                    myOrder.OrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.REJECTED);
                    myOrder.Text = myE.Message;
                }
                throw (myE);
            }
        }
示例#34
0
        /// <summary>
        /// Handle an incomming execution report
        /// </summary>
        /// <param name="myMsg"></param>
        public void HandleExecReport(KaiTrade.Interfaces.Message myMsg)
        {
            try
            {
                if (m_Log.IsInfoEnabled)
                {
                    m_Log.Info("OrderService:HandleExecReport:" + myMsg.Data);
                }
                if (m_ORLog.IsInfoEnabled)
                {
                    m_ORLog.Info("OrderService:HandleExecReport:" + myMsg.Data);
                }
                // Get order manager
                KaiTrade.Interfaces.OrderManager myOM = KTAFacade.Instance().Factory.GetOrderManager();

                //Create a quickfix message object
                QuickFix.Message myFixMsg = new QuickFix.Message(myMsg.Data);

                QuickFix.ExecID myExecID = new QuickFix.ExecID();
                myFixMsg.getField(myExecID);

                // check if we have already processed this report
                if (!myOM.RecordExecutionReport(myExecID.getValue(), myFixMsg))
                {
                    // we have processed this already
                    m_Log.Warn("HandleExecReport: Duplicate Exec Report:" + myMsg.Data);
                    return;
                }

                // these fields must be present
                QuickFix.OrderID myOrderID = new QuickFix.OrderID();
                myFixMsg.getField(myOrderID);

                QuickFix.ExecType myExecType = new QuickFix.ExecType();
                myFixMsg.getField(myExecType);

                QuickFix.OrdStatus myOrdStatus = new QuickFix.OrdStatus();
                myFixMsg.getField(myOrdStatus);

                // we need the clordid to update an existing order - if
                // it is not present or unknow we create a synthetic order
                QuickFix.ClOrdID myClOrdID = new QuickFix.ClOrdID();
                KaiTrade.Interfaces.Order myOrder = null;
                if (myFixMsg.isSetField(myClOrdID))
                {
                    myFixMsg.getField(myClOrdID);
                    myOrder = myOM.GetOrderWithClOrdIDID(myClOrdID.getValue());
                }
                if (myOrder == null)
                {
                    myOrder = CreateSyntheticOrder(myFixMsg);
                }

                // add the ExecRep to the Order
                KaiTrade.Interfaces.Fill myFill = new K2DataObjects.FillData();
                myFill.OrderID = myOrder.Identity;
                myFill.SetUpFromFixExecReport(myFixMsg.ToString());

                myOrder.FillsList.Add(myFill);

                // update mandatory fields
                myOrder.OrderID = myOrderID;
                myOrder.OrdStatus = myOrdStatus;
                QuickFix.Text myText = new QuickFix.Text();
                if (myFixMsg.isSetField(myText))
                {
                    myFixMsg.getField(myText);
                    myOrder.Text = myText.getValue();
                }

                QuickFix.Account myAccount = new QuickFix.Account();
                if (myFixMsg.isSetField(myAccount))
                {
                    myFixMsg.getField(myAccount);

                    myOrder.Account = myAccount;
                }

                // process the execution depanding on type of ExecReport
                switch (myExecType.getValue())
                {
                    case QuickFix.ExecType.NEW:
                        processGeneralExecRep(ref myOrder, myFixMsg);
                        /*
                        if (order.LastOrderCommand == KaiTrade.Interfaces.LastOrderCommand.neworder)
                        {
                            order.LastOrderCommand = KaiTrade.Interfaces.LastOrderCommand.none;
                        }
                        else
                        {
                            m_Log.Error("HandleExecReport:OrderStatus new not expected");
                        }
                         * */
                        break;
                    case QuickFix.ExecType.FILL:
                        if (order.LastOrderCommand == KaiTrade.Interfaces.LastOrderCommand.neworder)
                        {
                            order.LastOrderCommand = KaiTrade.Interfaces.LastOrderCommand.none;
                        }

                        processFill(ref myOrder, myFixMsg);
                        break;
                    case QuickFix.ExecType.PARTIAL_FILL:
                        if (order.LastOrderCommand == KaiTrade.Interfaces.LastOrderCommand.neworder)
                        {
                            order.LastOrderCommand = KaiTrade.Interfaces.LastOrderCommand.none;
                        }
                        processFill(ref myOrder, myFixMsg);
                        break;
                    case QuickFix.ExecType.ORDER_STATUS:
                        processGeneralExecRep(ref myOrder, myFixMsg);
                        break;
                    default:
                        processGeneralExecRep(ref myOrder, myFixMsg);
                        break;
                }

                myOM.SetChanged(myOrder.Identity);

                // Check if the order is part of a strategy
                if (myOrder.ParentIdentity != null)
                {
                    // get the strategy concerned
                    KaiTrade.Interfaces.IStrategy myStrat = KTAFacade.Instance().Factory.GetStrategyManager().GetStrategy(myOrder.ParentIdentity);
                    if (myStrat != null)
                    {
                        myStrat.HandleExecReport(myFixMsg, myOrder);
                    }
                    else
                    {
                        m_Log.Error("Strategy not found for:" + myOrder.ParentIdentity);
                    }
                }

                if (myOrder.OCAGroupName.Length > 0)
                {
                    KTAFacade.Instance().Factory.GetOCOManager().OnOrderTraded(myOrder);
                }
                if (m_ORLog.IsInfoEnabled)
                {
                    m_ORLog.Info("OrderService:HandleExecRep:Exit:" + myOrder.ToString());
                }
            }
            catch (Exception myE)
            {
                m_Log.Error("HandleExecReport", myE);
            }
        }
示例#35
0
        public void RenderOrderAsFix(out QuickFix.Message myNOS, out KaiTrade.Interfaces.Message myMsg, out string myDriverCode, KaiTrade.Interfaces.Order myOrder)
        {
            try
            {
                lock (this)
                {
                    // do not actually submit triggered orders

                    // register the order as a publisher
                    KaiTrade.Interfaces.Publisher myPub = null;
                    myPub = AppFactory.Instance().GetPublisherManager().GetPublisher(myOrder.Identity);
                    if (myPub == null)
                    {
                        myPub = myOrder as KaiTrade.Interfaces.Publisher;
                        AppFactory.Instance().GetPublisherManager().Add(myPub);
                    }

                    // Check the limits for the order
                    string myTextErr;
                    if (LimitChecker.Instance().BreaksLimits(out myTextErr, myOrder))
                    {
                        myOrder.OrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.REJECTED);
                        myOrder.Text = "order failed order qty limit test";
                        Exception myE = new Exception("process order failed order qty limit test");
                        throw myE;
                    }

                    // Create the FIX order message
                    myNOS = new QuickFix.Message();

                    // pending new at this stage
                    myOrder.OrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.PENDING_NEW);

                    myOrder.TransactTime = new QuickFix.TransactTime(DateTime.Now.ToUniversalTime());
                    myNOS.setField(myOrder.TransactTime);

                    //myOrder.ClOrdID = new QuickFix.ClOrdID(KaiUtil.Identities.Instance.genReqID());

                    // Associate the CLOrdID with this order
                    AppFactory.Instance().GetOrderManager().AssociateClOrdID(myOrder.ClOrdID.getValue(), myOrder);

                    // Set fix version
                    QuickFix.BeginString myBeginString = new QuickFix.BeginString("FIX.4.4");
                    myNOS.getHeader().setField(myBeginString);

                    // Set order message type
                    QuickFix.MsgType msgType = new QuickFix.MsgType();
                    msgType.setValue("D");
                    myNOS.getHeader().setField(msgType);

                    myNOS.setField(myOrder.ClOrdID);

                    // set up the product details in the message
                    myOrder.Product.Set(myNOS);

                    // Qty
                    myNOS.setField(myOrder.OrderQty);

                    // MaxFloor
                    if (myOrder.MaxFloor != null)
                    {
                        myNOS.setField(myOrder.MaxFloor);
                    }

                    // set the side
                    myNOS.setField(myOrder.Side);

                    // set the order type
                    myNOS.setField(myOrder.OrdType);

                    // Time in force
                    if (myOrder.TimeInForce != null)
                    {
                        myNOS.setField(myOrder.TimeInForce);
                    }
                    else
                    {
                        myOrder.TimeInForce = new QuickFix.TimeInForce(QuickFix.TimeInForce.DAY);
                        myNOS.setField(myOrder.TimeInForce);
                    }

                    // Validation - check they entered a date/time if needed
                    switch (myOrder.TimeInForce.getValue())
                    {
                        case QuickFix.TimeInForce.GOOD_TILL_DATE:
                            break;

                        default:
                            break;
                    }

                    // do not add the price to the fix message on Market orders
                    if (myOrder.OrdType.getValue() != QuickFix.OrdType.MARKET)
                    {
                        if (myOrder.Price.getValue() > 0)
                        {
                            myNOS.setField(myOrder.Price);
                        }
                        else
                        {
                            throw new Exception("Must specify price > 0 on Limit and other non Market orders");
                        }
                    }

                    if (myOrder.StopPx != null)
                    {
                        myNOS.setField(myOrder.StopPx);
                    }

                    // default the handlInst to automated
                    if (myOrder.HandlInst != null)
                    {
                        myNOS.setField(myOrder.HandlInst);
                    }
                    else
                    {
                        myOrder.HandlInst = new QuickFix.HandlInst(QuickFix.HandlInst.AUTOEXECPUB);
                        myNOS.setField(myOrder.HandlInst);
                    }

                    // Create the message wrapper used to send the order to the driver
                    myMsg = new KaiTCPComm.KaiMessageWrap();

                    myMsg.Label = "D";

                    myDriverCode = "";
                    // A trade venue must be specified on the order
                    KaiTrade.Interfaces.Venue myVenue = null;
                    if (myOrder.Product.TradeVenue.Length > 0)
                    {
                        // get the driver code and session details from the venue manager
                        myVenue = AppFactory.Instance().GetVenueManager().GetVenue(myOrder.Product.TradeVenue);
                        if (myVenue != null)
                        {
                            myDriverCode = myVenue.DriverCode;
                            if (myVenue.TargetVenue.Length > 0)
                            {
                                myMsg.VenueCode = myVenue.TargetVenue;
                            }
                            if (myVenue.BeginString.Length > 0)
                            {
                                // this is the FIX version the server wants, we convert between
                                // versions in the FIX client
                                myMsg.Format = myVenue.BeginString;
                            }

                            if (myVenue.SID.Length > 0)
                            {
                                QuickFix.SenderCompID mySID = new QuickFix.SenderCompID(myVenue.SID);
                                myNOS.getHeader().setField(mySID);
                                myMsg.ClientID = myVenue.SID;
                            }
                            if (myVenue.TID.Length > 0)
                            {
                                QuickFix.TargetCompID myTID = new QuickFix.TargetCompID(myVenue.TID);
                                myNOS.getHeader().setField(myTID);
                                myMsg.TargetID = myVenue.TID;
                            }
                        }
                        else
                        {
                            string myErr = "Invalid Venue Code:" + myOrder.Product.TradeVenue;
                            m_Log.Error(myErr);
                            Exception myE = new Exception(myErr);
                            throw myE;
                        }
                    }
                    else
                    {
                        string myErr = "No Venue Code specified on product:";
                        m_Log.Error(myErr);
                        Exception myE = new Exception(myErr);
                        throw myE;
                    }

                    // process any venue field bags - do this prior to the order bags
                    // to allow the order setting to override the venues
                    List<KaiTrade.Interfaces.Field> myFieldBag;
                    KTAFacade.Instance().SetBag(out myFieldBag, myVenue.NOSBag, ",");
                    foreach (KaiTrade.Interfaces.Field myField in myFieldBag)
                    {
                        try
                        {
                            myNOS.setString(int.Parse(myField.ID), myField.Value);
                        }
                        catch (Exception myE)
                        {
                            m_Log.Error("NOS Extra tags from venue error:", myE);
                        }
                    }

                    // process any additional tags for the order
                    foreach (KaiTrade.Interfaces.Field myField in myOrder.NOSBag)
                    {
                        try
                        {
                            myNOS.setString(int.Parse(myField.ID), myField.Value);
                        }
                        catch (Exception myE)
                        {
                            m_Log.Error("NOS Extra tags error:", myE);
                        }
                    }

                    // additional setting placed here will override the
                    // fields in the bags

                    if (myOrder.Account != null)
                    {
                        if (myOrder.Account.getValue().Length > 0)
                        {
                            myNOS.setField(myOrder.Account);
                        }
                    }

                    QuickFix.TargetStrategyParameters targetStrategyParameters = new QuickFix.TargetStrategyParameters(myOrder.StrategyName);
                    myNOS.setField(targetStrategyParameters);

                    // Process any strategy parameters
                    if (myOrder.K2Parameters.Count > 0)
                    {
                        QuickFix.NoStrategyParameters noStratParms = new QuickFix.NoStrategyParameters(myOrder.K2Parameters.Count);
                        myNOS.setField(noStratParms);
                        QuickFix50Sp2.NewOrderSingle.NoStrategyParameters group = new QuickFix50Sp2.NewOrderSingle.NoStrategyParameters();
                        QuickFix.StrategyParameterName strategyParameterName;
                        QuickFix.StrategyParameterType strategyParameterType;
                        QuickFix.StrategyParameterValue strategyParameterValue;

                        foreach (KaiTrade.Interfaces.K2Parameter param in myOrder.K2Parameters)
                        {
                            strategyParameterName = new QuickFix.StrategyParameterName(param.ParameterName);
                            group.setField(strategyParameterName);
                            strategyParameterType = new QuickFix.StrategyParameterType((int)param.ParameterType);
                            group.setField(strategyParameterType);
                            strategyParameterValue = new QuickFix.StrategyParameterValue(param.ParameterValue);
                            group.setField(strategyParameterValue);
                            myNOS.addGroup(group);
                        }
                    }

                    // Set the FIX string as message data
                    myMsg.Data = myNOS.ToString();

                    // inform order manager clients that the order has changed
                    AppFactory.Instance().GetOrderManager().SetChanged(myOrder.Identity);
                }
            }
            catch (Exception myE)
            {
                m_Log.Error("RenderOrderAsFix:", myE);
                myOrder.OrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.REJECTED);
                myOrder.Text = myE.Message;
                // inform order manager clients that the order has changed
                AppFactory.Instance().GetOrderManager().SetChanged(myOrder.Identity);
                throw (myE);
            }
        }
示例#36
0
        /// <summary>
        /// submit an order to IB using a incomming FIX new order single
        /// </summary>
        /// <param name="myMsg"></param>
        private void submitOrder(KaiTrade.Interfaces.IMessage myMsg)
        {
            QuickFix.Message myQFOrder = null;
            try
            {
                // Extract the raw FIX Message from the inbound message
                string strOrder = myMsg.Data;

                // Use QuickFix to handle the message
                myQFOrder = new QuickFix.Message(strOrder);

                // Use product manager to validate the product specified on
                // the order exists for this adapter

                // Get the product associated with the FIX message

                //QuickFix.Symbol symbol = new QuickFix.Symbol();
                //myQFOrder.getField(symbol);

                QuickFix.Side mySide = new QuickFix.Side();
                QuickFix.OrdType myOrdType = new QuickFix.OrdType();
                QuickFix.OrderQty myOrderQty = new QuickFix.OrderQty();
                QuickFix.Price myPrice = new QuickFix.Price();
                QuickFix.StopPx myStopPx = new QuickFix.StopPx();
                QuickFix.Account myAccount = new QuickFix.Account();

                QuickFix.ClOrdID myClOrdID = new QuickFix.ClOrdID();
                QuickFix.TimeInForce myTimeInForce = new QuickFix.TimeInForce();

                // the account code is mandatory
                if (myQFOrder.isSetField(myAccount))
                {
                    myQFOrder.getField(myAccount);
                }
                else
                {
                    this.SendAdvisoryMessage("IB TWS: you need to provide a valid account");
                    throw new Exception("IB TWS: you need to provide a valid account");
                }

                myQFOrder.getField(myClOrdID);

                // Get the Order type
                myQFOrder.getField(myOrdType);

                // Get the QTY
                myQFOrder.getField(myOrderQty);

                // get the Side of the order
                myQFOrder.getField(mySide);

                // Set order duration
                myQFOrder.getField(myTimeInForce);

                // Prices
                if (myQFOrder.isSetField(myPrice))
                {
                    myQFOrder.getField(myPrice);
                }

                if (myQFOrder.isSetField(myStopPx))
                {
                    myQFOrder.getField(myStopPx);
                }

                // get the contract
                TWSLib.IContract myContract = getIBContract(myQFOrder);
                if (myContract == null)
                {
                    this.SendAdvisoryMessage("IB TWS: cannot find a valid contract");
                    throw new Exception("IB TWS: cannot find a valid contract");
                }

                // create an IB Order
                TWSLib.IOrder myIBOrder = m_Host.TWS.createOrder();

                myIBOrder.whatIf = 0;
                myIBOrder.account = myAccount.getValue();

                if(myOrdType.getValue() == QuickFix.OrdType.LIMIT)
                {
                    myIBOrder.orderType = "LMT";
                    myIBOrder.lmtPrice = myPrice.getValue();
                }
                else if(myOrdType.getValue() == QuickFix.OrdType.MARKET)
                {
                    myIBOrder.orderType = "MKT";
                }
                else if (myOrdType.getValue() == QuickFix.OrdType.STOP)
                {
                    myIBOrder.orderType = "STP";
                    myIBOrder.auxPrice = myStopPx.getValue();
                    if (myPrice.getValue() == -1)
                    {
                        myIBOrder.lmtPrice = myStopPx.getValue();
                    }
                    else
                    {
                        myIBOrder.lmtPrice = myPrice.getValue();
                    }
                }
                else if (myOrdType.getValue() == QuickFix.OrdType.STOP_LIMIT)
                {
                    myIBOrder.orderType = "STP";
                    myIBOrder.auxPrice = myStopPx.getValue();
                    if (myPrice.getValue() == -1)
                    {
                        myIBOrder.lmtPrice = myStopPx.getValue();
                    }
                    else
                    {
                        myIBOrder.lmtPrice = myPrice.getValue();
                    }
                }
                else
                {
                    this.SendAdvisoryMessage("IB TWS: order type not supported");
                    throw new Exception("IB TWS: order type not supported");
                }

                myIBOrder.totalQuantity = (int) myOrderQty.getValue();

                // Side
                string myAction = KaiUtil.QFUtils.DecodeSide(mySide).ToUpper();
                myIBOrder.action = myAction;

                // Time in force
                string myTIF = KaiUtil.QFUtils.DecodeTimeInForce(myTimeInForce).ToUpper();
                myIBOrder.timeInForce = myTIF;

                if (myOrdType.getValue() == QuickFix.OrdType.LIMIT)
                {
                    myIBOrder.lmtPrice = myPrice.getValue();
                }

                DriverBase.OrderContext myCntx = RecordOrderContext(myClOrdID.getValue(), myQFOrder, null, m_NextID.ToString());
                SetContextCommand(myCntx, DriverBase.ORCommand.Undefined, DriverBase.ORCommand.Submit);

                myCntx.OrderQty = myIBOrder.totalQuantity;
                myCntx.CumQty = 0;

                m_Host.TWS.placeOrderEx(m_NextID++, myContract, myIBOrder);

            }
            catch (Exception myE)
            {

                _log.Error("submitOrder", myE);
                // To provide the end user with more information
                // send an advisory message, again this is optional
                // and depends on the adpater
                this.SendAdvisoryMessage("IB TWS:submitOrder: problem submitting order:" + myE.ToString());

                QuickFix.OrdStatus myOrdStatus;
                QuickFix.ExecType myExecType = new QuickFix.ExecType(QuickFix.ExecType.REJECTED);

                myOrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.REJECTED);
                QuickFix.OrderQty orderQty = new QuickFix.OrderQty();
                if (myQFOrder != null)
                {
                    myQFOrder.getField(orderQty);
                    QuickFix.OrdRejReason myRejReason = new QuickFix.OrdRejReason(QuickFix.OrdRejReason.OTHER);
                    sendExecReport(myQFOrder, new QuickFix.OrderID("UNKNOWN"), myOrdStatus, myExecType, 0.0, (int)orderQty.getValue(), 0, 0, 0, myE.Message, myRejReason);
                }

            }
        }
示例#37
0
        /// <summary>
        /// Cancel the order specified
        /// </summary>
        /// <param name="myID">ID of order to cancel</param>
        public void CancelOrder(string myID)
        {
            try
            {
                // Get Order
                KaiTrade.Interfaces.OrderManager myOM = AppFactory.Instance().GetOrderManager();
                KaiTrade.Interfaces.Order myOrder = myOM.GetOrder(myID);

                if (myOrder == null)
                {
                    string myError = "Order not found cannot cancel:" + myID;
                    Exception myE = new Exception(myError);
                }

                if (m_ORLog.IsInfoEnabled)
                {
                    m_ORLog.Info("CancelOrder:" + myOrder.ToString());
                }

                if (order.LastOrderCommand == KaiTrade.Interfaces.LastOrderCommand.cancel)
                {
                    string myError = "Order has already had a cancel processed - cannot recancel:" + myID;
                    Exception myE = new Exception(myError);
                }

                // Is this a triggered order
                if (myOrder.TriggerOrderID.Length > 0)
                {
                    KaiTrade.Interfaces.TriggeredOrder triggeredOrder = KTAFacade.Instance().Factory.GetTriggeredOrderManager().Get(myOrder.TriggerOrderID);
                    triggeredOrder.Cancel();
                    return;
                }
                // store the clordID's
                //NOT USED? QuickFix.OrigClOrdID myOrigClOrdID;
                QuickFix.ClOrdID myClOrdID;

                if ((myOrder.OrdStatus.getValue() == QuickFix.OrdStatus.FILLED) || (myOrder.OrdStatus.getValue() == QuickFix.OrdStatus.CANCELED))
                {
                    // cannot cancel the order - so return
                    return;
                }

                // Create a FIX cancel messsage

                QuickFix.Message myFixMsg = new QuickFix.Message();
                QuickFix.MsgType msgType = new QuickFix.MsgType("F");
                myFixMsg.getHeader().setField(msgType);
                QuickFix.BeginString myBeginString = new QuickFix.BeginString("FIX.4.4");
                myFixMsg.getHeader().setField(myBeginString);

                // set the original to the existing clordid
                myOrder.OrigClOrdID = new QuickFix.OrigClOrdID(myOrder.ClOrdID.getValue());
                myFixMsg.setField(myOrder.OrigClOrdID);

                // save the existing clordid and set the new clordid
                myClOrdID = myOrder.ClOrdID;
                myOrder.ClOrdID = new QuickFix.ClOrdID(KaiUtil.Identities.Instance.genReqID());
                myFixMsg.setField(myOrder.ClOrdID);
                // Associate the CLOrdID with this order
                AppFactory.Instance().GetOrderManager().AssociateClOrdID(myOrder.ClOrdID.getValue(), myOrder);

                // OrderID
                if (myOrder.OrderID != null)
                {
                    myFixMsg.setField(myOrder.OrderID);
                }

                ////Side
                myFixMsg.setField(myOrder.Side);

                // set up the product details in the message
                myOrder.Product.Set(myFixMsg);

                //// Transact Time
                myOrder.TransactTime = new QuickFix.TransactTime(DateTime.Now.ToUniversalTime());
                myFixMsg.setField(myOrder.TransactTime);

                // Create the message wrapper used to send the order cancel to the driver
                KaiTrade.Interfaces.Message myMsg = new KaiTCPComm.KaiMessageWrap();

                myMsg.Label = "F";

                string myDriverCode = "";
                // A trade venue must be specified on the order
                KaiTrade.Interfaces.Venue myVenue = null;
                if (myOrder.Product.TradeVenue.Length > 0)
                {
                    // get the driver code and session details from the venue manager
                    myVenue = AppFactory.Instance().GetVenueManager().GetVenue(myOrder.Product.TradeVenue);
                    if (myVenue != null)
                    {
                        myDriverCode = myVenue.DriverCode;
                        if (myVenue.TargetVenue.Length > 0)
                        {
                            myMsg.VenueCode = myVenue.TargetVenue;
                        }
                        if (myVenue.BeginString.Length > 0)
                        {
                            // this is the FIX version the server wants, we convert between
                            // versions in the FIX client
                            myMsg.Format = myVenue.BeginString;
                        }

                        if (myVenue.SID.Length > 0)
                        {
                            QuickFix.SenderCompID mySID = new QuickFix.SenderCompID(myVenue.SID);
                            myFixMsg.getHeader().setField(mySID);
                            myMsg.ClientID = myVenue.SID;
                        }
                        if (myVenue.TID.Length > 0)
                        {
                            QuickFix.TargetCompID myTID = new QuickFix.TargetCompID(myVenue.TID);
                            myFixMsg.getHeader().setField(myTID);
                            myMsg.TargetID = myVenue.TID;
                        }
                    }
                    else
                    {
                        string myErr = "Invalid Venue Code:" + myOrder.Product.TradeVenue;
                        m_Log.Error(myErr);
                        Exception myE = new Exception(myErr);
                        throw myE;
                    }
                }
                else
                {
                    string myErr = "No Venue Code specified on product:";
                    m_Log.Error(myErr);
                    Exception myE = new Exception(myErr);
                    throw myE;
                }

                // process any venue field bags - do this prior to the order bags
                // to allow the order setting to override the venues
                List<KaiTrade.Interfaces.Field> myFieldBag;
                KTAFacade.Instance().SetBag(out myFieldBag, myVenue.CancelBag, ",");

                foreach (KaiTrade.Interfaces.Field myField in myFieldBag)
                {
                    try
                    {
                        myFixMsg.setString(int.Parse(myField.ID), myField.Value);
                    }
                    catch (Exception myE)
                    {
                        m_Log.Error("cancel Extra tags from venue error:", myE);
                    }
                }

                // process any additional tags for the order
                foreach (KaiTrade.Interfaces.Field myField in myOrder.CancelBag)
                {
                    try
                    {
                        myFixMsg.setString(int.Parse(myField.ID), myField.Value);
                    }
                    catch (Exception myE)
                    {
                        m_Log.Error("cancel Extra tags error:", myE);
                    }
                }
                if (myOrder.Account != null)
                {
                    if (myOrder.Account.getValue().Length > 0)
                    {
                        myFixMsg.setField(myOrder.Account);
                    }
                }
                // Set the FIX string as message data
                myMsg.Data = myFixMsg.ToString();

                // inform order manager clients that the order has changed
                myOM.SetChanged(myOrder.Identity);

                try
                {
                    //Send the message
                    KaiTrade.Interfaces.Driver myDrv = AppFactory.Instance().GetDriverManager().GetDriver(myDriverCode);
                    if (myDrv != null)
                    {
                        // send the message for processing
                        order.LastOrderCommand = KaiTrade.Interfaces.LastOrderCommand.cancel;

                        //SendDelegate mySend = new SendDelegate(myDrv.Send);
                        //IAsyncResult ar = mySend.BeginInvoke(myMsg, SRCallback, "123456789");
                        // send the message for processing
                        myDrv.Send(myMsg);
                    }
                    else
                    {
                        string myError = "Driver not found for code:" + myDriverCode;
                        m_Log.Error(myError);
                        Exception myE = new Exception(myError);
                        throw myE;
                    }
                }
                catch (Exception myE)
                {
                    m_Log.Error("CanceltOrder:" + myOrder.Identity, myE);
                    myOrder.OrdStatus = new QuickFix.OrdStatus(QuickFix.OrdStatus.REJECTED);
                    order.LastOrderCommand = KaiTrade.Interfaces.LastOrderCommand.none;
                    throw (myE);
                }
            }
            catch (Exception myE)
            {
                m_Log.Error("CancelOrder:", myE);
                throw (myE);
            }
        }