Esempio n. 1
0
 private static void OnIncomingMsg(IMcdrFromAdmin[] msgs)
 {
     try
     {
         foreach (var msg in msgs)
         {
             if (msg is McdrSessionUp)
             {
                 try
                 {
                     _clientSessionKey = ((McdrSessionUp)msg).SessionKey;
                     _IsMcsdSessionUp  = true;
                 }
                 catch (Exception ex)
                 {
                     Console.WriteLine(ex.ToString());
                 }
             }
         }
     }
     catch (Exception exp)
     {
         SystemLogger.LogErrorAsync("Failed to handle received MCSD from Admin Message . Error : " + exp.ToString());
     }
 }
        public void Handle(AllocRes msg)
        {
            if (msg != null)
            {
                switch (msg.ResType)
                {
                case ALLOC_RES_TYPES.ALLOC_ACCEPTED_RES:
                case ALLOC_RES_TYPES.ALLOC_UPDATED_RES:
                    HandleUpdatedAllocation(msg);
                    break;

                case ALLOC_RES_TYPES.ALLOC_REFUSED_RES:
                case ALLOC_RES_TYPES.ALLOC_UPDATE_REFUSED_RES:
                    HandleRejectAllocation(msg);

                    break;

                default:
                    // log here.
                    SystemLogger.LogErrorAsync(string.Format("Unhandled message type received from MCSD : ", msg.ResType));

                    break;
                }
            }
        }
Esempio n. 3
0
        //timer to check connectivity with MCSD should be added to establish connection with MCSD if it went down during the session.
        #endregion

        #region Constructor


        #endregion

        #region private members
        private static void InitializeDeclerations()
        {
            try
            {
                m_MCSDresponseQueueIP   = SystemConfigurations.GetAppSetting("MCSDresponseQueueIP");
                m_MCSDresponseQueueName = SystemConfigurations.GetAppSetting("MCSDresponseQueueName");

                m_MCSDUserName  = SystemConfigurations.GetAppSetting("MCSD_UserName");
                m_MCSD_Password = SystemConfigurations.GetAppSetting("MCSD_Password");

                m_OverrideMCSDQueue       = Boolean.Parse(SystemConfigurations.GetAppSetting("OverrideMCSDQueue"));
                m_FlushMCSDUpdatesOffline = Boolean.Parse(SystemConfigurations.GetAppSetting("FlushMCSDUpdatesOffline"));

                _McsdServicePingIntervals = int.Parse(SystemConfigurations.GetAppSetting("McsdServicePingIntervals"));

                m_IncomingMessageDelegate = new IMCDSCallbackHandler.IncomingMessageDelegate(OnIncomingMsg);

                m_callbackHandler = new IMCDSCallbackHandler(m_IncomingMessageDelegate);
                m_InstanceContext = new InstanceContext(m_callbackHandler);
                m_factory         = new DuplexChannelFactory <IMcdrAdmin>(m_InstanceContext, "netTcpBinding_IMcdrAdmin");



                subRequest = new MCDR.Contract.Entities.ToAdmin.subReq();
            }
            catch (Exception exp)
            {
                SystemLogger.LogErrorAsync("MCSDManager Constructor Error: " + exp.ToString());
            }
        }
Esempio n. 4
0
 private static void Unsubscribe()
 {
     try
     {
         m_clientMcsd.Unsubscribe();
     }
     catch (Exception exp)
     {
         SystemLogger.LogErrorAsync("Unsubscribtion from MCSD Service Failed. Error : " + exp.ToString());
         SystemLogger.WriteOnConsoleAsync(true, "Unsubscribtion from MCSD Service Failed. Error : " + exp.ToString(), ConsoleColor.Red, ConsoleColor.Black, true);
     }
 }
Esempio n. 5
0
 private static void PingMCSDService()
 {
     try
     {
         while (_IsPingToMcsdStarted)
         {
             m_clientMcsd.Ping();
             System.Threading.Thread.Sleep(_McsdServicePingIntervals);
         }
     }
     catch (Exception exp)
     {
         SystemLogger.LogErrorAsync("Pinging MCSD Service Failed. Error : " + exp.ToString());
     }
 }
Esempio n. 6
0
        private static void HandleReceivedMSCDMessages()
        {
            MessageQueue        m_msgSenderQueue = new MessageQueue(string.Format(@"Formatname:DIRECT=TCP:{0}\private$\{1}", m_MCSDresponseQueueIP, m_MCSDresponseQueueName));
            XmlMessageFormatter formatter        = new XmlMessageFormatter(new Type[] { typeof(McdrTestReq), typeof(AllocRes) });

            while (true)
            {
                try
                {
                    System.Messaging.Message msg = (System.Messaging.Message)m_msgSenderQueue.Receive();
                    if (msg == null)
                    {
                        continue;
                    }

                    object recievedMsg = formatter.Read(msg);

                    if (recievedMsg.GetType() == typeof(McdrTestReq))
                    {
                        try
                        {
                            IMcdrToAdmin msgTo = new McdrTestRes()
                            {
                                TestKey = ((McdrTestReq)recievedMsg).TestKey
                            };
                            m_clientMcsd.HandleMsg(msgTo);
                        }
                        catch (Exception ex)
                        {
                            Console.Write(ex.ToString());
                        }
                    }
                    else if (recievedMsg.GetType() == typeof(AllocRes))
                    {
                        AllocRes respMsg = (AllocRes)recievedMsg;
                        m_mcsdRouter.PushMessage(respMsg);
                    }
                }
                catch (Exception exp)
                {
                    SystemLogger.LogErrorAsync("Error while handling MCSD Message. Error : " + exp.ToString());
                    continue;
                }
            }
        }
Esempio n. 7
0
        static void MCSDManager_Closed(object sender, EventArgs e)
        {
            try
            {
                _IsMcsdSessionUp = false;
                SystemLogger.LogErrorAsync("MCSD Session Closed");
            }
            catch (Exception exp)
            {
                SystemLogger.LogErrorAsync(exp.ToString());
            }

            finally
            {
                // try to connect again.
                //Subscribe();
                taskReSubscribe = new Thread(new ThreadStart(Subscribe));
                taskReSubscribe.IsBackground = true;
                taskReSubscribe.Start();
            }
        }
        public void Handle(QuickFix.Message msg)
        {
            long orderID = -1;

            // check message type tag, if execution report then push execution report update
            QuickFix.MsgType msgType       = new QuickFix.MsgType();
            string           msgTypeString = msg.getHeader().getField(m_msgTypeTag);

            if (msgTypeString == m_MsgTypeTagValueToHandle)
            {
                Counters.IncrementCounter(CountersConstants.OrderCancelRejectRspMsgs);

                //SystemLogger.WriteOnConsole(true, string.Format("new message recieved, Type: {0}, Message: '{1}'", msgTypeString, msg.ToXML()), ConsoleColor.Cyan, ConsoleColor.Black, false);
                SingleOrder order = null;
                // get order id
                if (msg.isSetField(11))
                {
                    orderID = long.Parse(msg.getField(11).Split(new char[] { '-' })[0]);
                    try
                    {
                        order = OrdersManager.GetOrder(orderID);
                    }
                    catch (Exception ex) // order not found
                    {
                        // get borse order  id
                        string bourseOrderID = msg.getField(37);
                        order = OrdersManager.GetOrder(bourseOrderID);
                        if (order == null)
                        {
                            SystemLogger.WriteOnConsoleAsync(true, string.Format("order BourseOrderID {0} not found !", bourseOrderID), ConsoleColor.Red, ConsoleColor.Black, true);
                            return;
                        }
                    }
                } // then search by borse order  id
                else if (msg.isSetField(37))
                {
                    string bourseOrderID = msg.getField(37);
                    order = OrdersManager.GetOrder(bourseOrderID);
                    if (order == null)
                    {
                        SystemLogger.WriteOnConsoleAsync(true, string.Format("order BourseOrderID {0} not found !", bourseOrderID), ConsoleColor.Red, ConsoleColor.Black, true);
                        return;
                    }
                }


                lock (order)
                {
                    string reason = string.Empty;
                    if (msg.isSetField(102))
                    {
                        try
                        {
                            reason = Lookups.GetOrderCancelRejectReasonsLookup(msg.getField(102)).MessageEn + " ,";
                        }
                        catch (Exception ex)
                        {
                            Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                            SystemLogger.WriteOnConsoleAsync(true, string.Format("Error getting order cancel reject reason: {0}", ex.Message), ConsoleColor.Red, ConsoleColor.Black, false);
                        }
                    }
                    if (msg.isSetField(58))
                    {
                        reason += msg.getField(58) + " ";
                    }
                    Nullable <DateTime> transactionDateTime = null;
                    if (msg.isSetField(60))
                    {
                        transactionDateTime = msg.getUtcTimeStamp(60);
                    }
                    LookupItem statusLookup = Lookups.GetOrderStatusLookup(msg.getField(39));
                    string     status       = statusLookup.CodeValue;

                    Guid requesterOrderID = (Guid)order[SingleOrderProperties.RequesterOrderID];
                    // find subscribed callbacks
                    //order[SingleOrderProperties.OrderStatus] = status;

                    bool   isPendingCancel  = false;
                    bool   isPendingReplace = false;
                    string orderNote        = string.Empty;
                    if (order[SingleOrderProperties.OrderStatus].ToString() == ORD_STATUS.PendingCancel)
                    {
                        isPendingCancel = true;
                        orderNote       = "Order cancel has been refused by bourse: " + reason;
                    }
                    else if (order[SingleOrderProperties.OrderStatus].ToString() == ORD_STATUS.PendingReplace)
                    {
                        // handle diff allocation cancellation

                        isPendingReplace = true;
                        orderNote        = "Order replace has been refused by bourse: " + reason;


                        #region Handle Mcsd Reset Allocation


                        try
                        {
                            if (order[SingleOrderProperties.IsMcsdAllocRequired] != null)
                            {
                                if (Convert.ToBoolean(order[SingleOrderProperties.IsMcsdAllocRequired]) == true)
                                {
                                    order[SingleOrderProperties.ActionOnAllocResponse] = ActionOnAllocResponse.DoNothing;
                                    int mcsdQty = Convert.ToInt32(order[SingleOrderProperties.McsdrAllocQty]);

                                    //  orderid = Convert.ToInt64(order[SingleOrderProperties.OrderID]);
                                    OrdersManager.HandleRejectedOrderAllocation(orderID, mcsdQty);
                                }
                            }
                        }
                        catch (Exception exp)
                        {
                            Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                            SystemLogger.LogErrorAsync(string.Format("Error, Reset MCSD allocation of Order {0}, Error : {1}", orderID, exp.ToString()));
                        }
                        #endregion
                    }
                    else
                    {
                        orderNote = "Order cancel/replace has been refused by bourse: " + reason;
                    }


                    // create IResponseMessage
                    string username = OrdersManager.GetOrdSessionIfAvailable((long)order[SingleOrderProperties.OrderID]);
                    if (username != null)
                    {
                        try
                        {
                            if (isPendingCancel)
                            {
                                Sessions.Push(username, new IResponseMessage[] { new Fix_OrderCancelRejected()
                                                                                 {
                                                                                     Message = reason, RequesterOrderID = requesterOrderID, OrderStatus = order[SingleOrderProperties.OriginalOrderStatus].ToString()
                                                                                 } });
                            }
                            else if (isPendingReplace)
                            {
                                Sessions.Push(username, new IResponseMessage[] { new Fix_OrderReplaceRejected()
                                                                                 {
                                                                                     Message = reason, RequesterOrderID = requesterOrderID, OrderStatus = order[SingleOrderProperties.OriginalOrderStatus].ToString()
                                                                                 } });
                            }
                            else
                            {
                                Sessions.Push(username, new IResponseMessage[] { new Fix_OrderReplaceCancelReject()
                                                                                 {
                                                                                     Message = reason, RequesterOrderID = requesterOrderID, OrderStatus = order[SingleOrderProperties.OriginalOrderStatus].ToString()
                                                                                 } });
                            }
                        }
                        catch (Exception ex)
                        {
                            Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                            SystemLogger.WriteOnConsoleAsync(true, string.Format("error sending order cancel reject to clients: {0}", ex.Message), ConsoleColor.Red, ConsoleColor.Black, true);
                        }
                    }
                    // update databse
                    try
                    {
                        DatabaseMethods db = new DatabaseMethods();

                        order[SingleOrderProperties.OrderStatus]      = order[SingleOrderProperties.OriginalOrderStatus];
                        order[SingleOrderProperties.IsPending]        = false;
                        order[SingleOrderProperties.Note]             =
                            order[SingleOrderProperties.Note2]        = "Action Status: " + status;
                        order[SingleOrderProperties.ModifiedDateTime] = transactionDateTime == null ? DateTime.Now : transactionDateTime;


                        Dictionary <string, object> orders_Columns = new Dictionary <string, object>();


                        orders_Columns.Add(SingleOrderProperties.OrderStatus, order[SingleOrderProperties.OriginalOrderStatus]);
                        orders_Columns.Add(SingleOrderProperties.Note, order[SingleOrderProperties.Note]);
                        orders_Columns.Add(SingleOrderProperties.Note2, order[SingleOrderProperties.Note2]);
                        orders_Columns.Add(SingleOrderProperties.ActionOnAllocResponse, ActionOnAllocResponse.DoNothing);
                        orders_Columns.Add(SingleOrderProperties.ModifiedDateTime, transactionDateTime == null ? DateTime.Now : transactionDateTime);
                        orders_Columns.Add(SingleOrderProperties.IsPending, false);


                        Dictionary <string, object> orders_Filters = new Dictionary <string, object>();
                        orders_Filters.Add(SingleOrderProperties.OrderID, order[SingleOrderProperties.OrderID]);

                        Dictionary <string, object> ordersDetails_Columns = new Dictionary <string, object>();
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.OrderID, order[SingleOrderProperties.OrderID]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.ClOrderID, order[SingleOrderProperties.ClOrderID]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.OrigClOrdID, order[SingleOrderProperties.OrigClOrdID]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.ExecutionMsgType, msgTypeString);

                        ordersDetails_Columns.Add(SingleOrdDetailsProps.AvgPrice, order[SingleOrderProperties.AvgPrice]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.CurrentPrice, order[SingleOrderProperties.CurrentPrice]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.ExecPrice, order[SingleOrderProperties.LastExecPrice]);

                        ordersDetails_Columns.Add(SingleOrdDetailsProps.CurrentQuantity, order[SingleOrderProperties.CurrentQuantity]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.ExecutedQuantity, order[SingleOrderProperties.ExecutedQuantity]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.LastExecQuantity, order[SingleOrderProperties.LastExecQuantity]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.RemainingQuantity, order[SingleOrderProperties.RemainingQuantity]);

                        ordersDetails_Columns.Add(SingleOrdDetailsProps.ExecType, order[SingleOrderProperties.ExecType]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.OrderStatus, order[SingleOrderProperties.OrderStatus]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.Note, order[SingleOrderProperties.Note]);

                        ordersDetails_Columns.Add(SingleOrdDetailsProps.OrderType, order[SingleOrderProperties.OrderType]);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.TimeInForce, order[SingleOrderProperties.TimeInForce]);

                        ordersDetails_Columns.Add(SingleOrdDetailsProps.IsResponse, true);


                        if (order[SingleOrderProperties.OrderStatus].ToString() == ORD_STATUS.PendingCancel)
                        {
                            ordersDetails_Columns.Add(SingleOrdDetailsProps.IsCancelResponse, true);
                        }
                        else if (order[SingleOrderProperties.OrderStatus].ToString() == ORD_STATUS.PendingReplace)
                        {
                            ordersDetails_Columns.Add(SingleOrdDetailsProps.IsModifyResponse, true);
                        }
                        else
                        {
                            ordersDetails_Columns.Add(SingleOrdDetailsProps.IsModifyResponse, true);
                            ordersDetails_Columns.Add(SingleOrdDetailsProps.IsCancelResponse, true);
                        }


                        ordersDetails_Columns.Add(SingleOrdDetailsProps.DateTime, DateTime.Now);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.ExecutionDate, transactionDateTime == null ? DateTime.Now : transactionDateTime);
                        ordersDetails_Columns.Add(SingleOrdDetailsProps.ExecutionRecievedDateTime, DateTime.Now);


                        db.UpdateOrderDetails(orders_Columns, orders_Filters, ordersDetails_Columns);



                        db = null;
                    }
                    catch (Exception ex)
                    {
                        Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                        SystemLogger.WriteOnConsoleAsync(true, string.Format("error updating order cancel reject into the db error: {0}", ex.Message), ConsoleColor.Red, ConsoleColor.Black, true);
                    }
                }
            }
        }
        public bool Handle(IRequestMessage msg)
        {
            try
            {
                Type msgType = msg.GetType();
                if (typeof(IRequestMessage).IsAssignableFrom(msgType))
                {
                    if (typeof(NewSingleOrder) == msgType)
                    {
                        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
                        sw.Start();
                        Counters.IncrementCounter(CountersConstants.ClientsNewOrderReqs);

                        NewSingleOrder order = (NewSingleOrder)msg;

                        #region validate client key
                        if (order.ClientKey == Guid.Empty || order.ClientKey == null)
                        {
                            SystemLogger.LogEventAsync(string.Format("ClientKey [{0}] not valid! ", order.ClientKey.ToString()));
                            return(true);
                        }
                        string username = Sessions.GetUsername(order.ClientKey);
                        if (!Sessions.IsSubscribedToSendMsg(username))
                        {
                            SystemLogger.LogEventAsync(string.Format("ClientKey [{0}] not subscribed", order.ClientKey));
                            return(true);
                        }
                        #endregion validate client key

                        #region validate stock group
                        Stock stock = StocksDefinitions.GetStockByCode(order.SecurityID);
                        if (stock == null)
                        {
                            Sessions.Push(Sessions.GetUsername(order.ClientKey), new IResponseMessage[] { new Fix_OrderRefusedByService()
                                                                                                          {
                                                                                                              ClientKey = order.ClientKey, RefuseMessage = "Stock Not Found!", RequesterOrderID = order.RequesterOrderID
                                                                                                          } });
                        }
                        #endregion validate stock group

                        #region validate currency
                        CurrencyItem currency = Currencies.GetCurrencyByCode(stock.CurrencyCode);
                        #endregion validate currency

                        #region validate order details
                        string validation = ValidateOrder(username, order);
                        #endregion validate order details

                        #region not valid order

                        if (validation != "valid")
                        {
                            try
                            {
                                SystemLogger.LogEventAsync(string.Format("OrderRefusedByService RequesterOrderID: {0}, Reason: {1}", order.RequesterOrderID, validation));
                                Sessions.Push(Sessions.GetUsername(order.ClientKey), new IResponseMessage[] { new Fix_OrderRefusedByService()
                                                                                                              {
                                                                                                                  ClientKey = order.ClientKey, RefuseMessage = validation, RequesterOrderID = order.RequesterOrderID
                                                                                                              } });
                            }
                            catch (Exception ex)
                            {
                                Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                                SystemLogger.LogEventAsync(string.Format("Error sending refused order to the client, ClientKey {0}, Error: {1}", order.ClientKey, ex.Message));
                            }
                            return(true);
                        }
                        #endregion not valid order

                        OrdersManager.HandleNewSingleOrder(username, order.ClientKey, order.RequesterOrderID, order.ClientID, order.CustodyID, order.SecurityID, order.OrderSide, Math.Round(order.Price, m_orderPriceDigitsRounding), order.Quantity, order.OrderType, DateTime.Now, order.TimeInForce, currency, order.ExchangeID, order.DateTime, stock.GroupID, stock.MarketID, order.HandleInst, order.ExpirationDateTime, order.OptionalParam);
                        sw.Stop();
                        SystemLogger.LogEventAsync(string.Format("new order handled in {0} ms ", sw.ElapsedMilliseconds));
                        sw = null;
                        return(true);
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                SystemLogger.LogErrorAsync("NewSingleOrderHandler Error: " + ex.Message);
                return(true);
            }
        }
        public static void Initialize()
        {
            _key_Session      = new Dictionary <Guid, SessionInfo>();
            _username_Session = new Dictionary <string, SessionInfo>();
            //m_iUpdateMessageDelegate = new IUpdateMessageDelegate(UpdateClientInternal);
            DateTime      dtNow     = DateTime.Now;
            FixDbEntities dbContext = new FixDbEntities();
            // remove old sessions
            IQueryable <Session> sessionsToDelete = dbContext.Sessions.Select(s => s);

            foreach (Session s in sessionsToDelete)
            {
                if (s.ConnectionDateTime.Date != DateTime.Now.Date)
                {
                    dbContext.SessionsHistories.Add(CreateHistory(s));
                    dbContext.Sessions.Remove(s);
                }
            }
            dbContext.SaveChanges();

            // remove unsubscribed sessions
            IQueryable <Session> unSubSessions = dbContext.Sessions.Where(s => !s.IsSubscribed);

            foreach (Session s in unSubSessions)
            {
                dbContext.SessionsHistories.Add(CreateHistory(s));
                dbContext.Sessions.Remove(s);
            }
            dbContext.SaveChanges();

            IQueryable <Session> sessions = dbContext.Sessions.Where(s => s.IsSubscribed == true).OrderByDescending(d => d.ConnectionDateTime);

            foreach (Session sub in sessions)
            {
                try
                {
                    // if not today subscriber or there are a double record for same session key
                    if (_key_Session.ContainsKey(sub.SessionKey) || sub.ConnectionDateTime.Date != DateTime.Now.Date)
                    {
                        dbContext.SessionsHistories.Add(CreateHistory(sub));
                        dbContext.Sessions.Remove(sub);
                        continue;
                    }

                    // make sure that you have only one record for each session

                    sub.IsOnline = false;
                    SessionInfo details = new SessionInfo()
                    {
                        SessionKey          = sub.SessionKey,
                        Callback            = null, // waiting for reactivation
                        FlushUpdatesOffline = sub.FlushUpdatesOffline,
                        IsOnline            = false,
                        QueueMachine        = sub.QueueIP,
                        QueueName           = sub.QueueName,
                        QueuePath           = sub.QueuePath,
                        Queue = new MessageQueue(sub.QueuePath)
                    };



                    Login login = dbContext.Logins.SingleOrDefault(l => l.UserName == sub.UserName);
                    if (login == null)
                    {
                        continue;
                    }
                    details.LoginInfo = new LoginInfo()
                    {
                        Username = login.UserName, CanPlaceOrder = login.CanPlaceOrder, CanReplicate = login.CanReplicate
                    };
                    _key_Session.Add(sub.SessionKey, details);
                    _username_Session.Add(login.UserName, details);
                }
                catch (Exception ex)
                {
                    SystemLogger.LogErrorAsync("Error while retriving subscribers from database: " + ex.ToString());
                }
            }
            dbContext.SaveChanges();

            _updater = new Thread(new ThreadStart(CheckEndOfSession));
            _updater.IsBackground = true;
            _updater.Start();
        }
Esempio n. 11
0
        public bool Handle(IRequestMessage msg)
        {
            try
            {
                Type msgType = msg.GetType();
                if (typeof(IRequestMessage).IsAssignableFrom(msgType))
                {
                    if (typeof(ModifyCancelOrder) == msgType)
                    {
                        Counters.IncrementCounter(CountersConstants.ClientsReplaceOrderReqs);


                        ModifyCancelOrder modifyOrder = (ModifyCancelOrder)msg;
                        SingleOrder       order       = OrdersManager.GetOrder(modifyOrder.RequesterOrderID);

                        #region order existanse validation
                        if (order == null)
                        {
                            Sessions.Push(Sessions.GetUsername(modifyOrder.ClientKey), new IResponseMessage[] { new Fix_OrderReplaceRefusedByService()
                                                                                                                {
                                                                                                                    ClientKey = modifyOrder.ClientKey, RefuseReason = "Order Not Found!", RequesterOrderID = modifyOrder.RequesterOrderID
                                                                                                                } });
                            SystemLogger.LogEventAsync(string.Format("Order Not Found RequesterID {0}  ", modifyOrder.RequesterOrderID));
                            return(true);
                        }
                        #endregion order existanse validation

                        lock (order)
                        {
                            #region check order activation
                            // check ispending before isactive becoz a pendingnew order might be not isactive but ispending
                            bool isPending, isMcsdPending = false;
                            isPending     = Convert.ToBoolean(order[SingleOrderProperties.IsPending]);
                            isMcsdPending = Convert.ToBoolean(order[SingleOrderProperties.IsPendingMcsd]);

                            if (isPending || isMcsdPending)
                            {
                                Sessions.Push(Sessions.GetUsername(modifyOrder.ClientKey), new IResponseMessage[] { new Fix_OrderReplaceRefusedByService()
                                                                                                                    {
                                                                                                                        ClientKey = modifyOrder.ClientKey, RefuseReason = !isMcsdPending ? "Order is in pending request" : "Awaiting for allocation response", RequesterOrderID = modifyOrder.RequesterOrderID
                                                                                                                    } });
                                return(true);
                            }

                            bool isActive = false;
                            isActive = Convert.ToBoolean(order[SingleOrderProperties.IsActive]);
                            if (!isActive)
                            {
                                Sessions.Push(Sessions.GetUsername(modifyOrder.ClientKey), new IResponseMessage[] { new Fix_OrderReplaceRefusedByService()
                                                                                                                    {
                                                                                                                        ClientKey = modifyOrder.ClientKey, RefuseReason = "Order not active any more", RequesterOrderID = modifyOrder.RequesterOrderID
                                                                                                                    } });
                                return(true);
                            }


                            #endregion check order activation

                            #region order validation
                            // ValidateOrder
                            string validation = ValidateOrder(modifyOrder, order);
                            if (validation != "valid")
                            {
                                Sessions.Push(Sessions.GetUsername(modifyOrder.ClientKey), new IResponseMessage[] { new Fix_OrderReplaceRefusedByService()
                                                                                                                    {
                                                                                                                        ClientKey = modifyOrder.ClientKey, RefuseReason = validation, RequesterOrderID = modifyOrder.RequesterOrderID
                                                                                                                    } });
                                return(true);
                            }
                            #endregion order validation

                            // handle ClOrderID and OrigClOrdID
                            OrdersManager.HandleModifyOrder(Sessions.GetUsername(modifyOrder.ClientKey), modifyOrder.ClientKey, modifyOrder.RequesterOrderID, (long)order[SingleOrderProperties.OrderID], modifyOrder.Quantity, Math.Round(modifyOrder.Price, m_orderPriceDigitsRounding), modifyOrder.OrderType, modifyOrder.TimeInForce, modifyOrder.OptionalParam);
                            return(true);
                        }
                    }
                }
                return(false);
            }
            catch (Exception ex)
            {
                Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                SystemLogger.LogErrorAsync("ModifyCancelOrderHandler Error: " + ex.Message);
                return(true);
            }
        }