示例#1
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());
            }
        }
示例#2
0
        private void btnSub_Click(object sender, EventArgs e)
        {
            //if (MessageBox.Show(this, "Subscribe to FIX orders service ?", "FIX Service", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
            {
                using (OrdersProxy proxy = new OrdersProxy())
                {
                    //string path = string.Format(@"{0}\private$\client", Environment.MachineName);
                    //string path = @"10.30.60.11\private$\client";
                    //string ip = SystemConfigurations.GetMachineIP();

                    btnSub.Enabled = false;

                    if (!isSubscribed)
                    {
                        string path = string.Format(@"Formatname:DIRECT=TCP:{0}", SystemConfigurations.GetAppSetting("ResponseQueue"));
                        proxy.SubscribeSession(path);
                    }
                    else
                    {
                        proxy.UnsubscribeSession(clientKey);
                    }
                    //66A92E99-721E-47C2-B866-FA853E0AE17F
                    //proxy.ResubscribeMe(new Guid("57D42C89-2EF5-4AEA-9C67-8CE0F0A8088C"), @".\private$\client");
                }
            }
        }
        private string ValidateOrder(string username, NewSingleOrder order)
        {
            if (OrdersManager.CallbackHasReqOrdID(order.RequesterOrderID))
            {
                return("Requested Order ID already existed for this session.");
            }
            if (order.DateTime.Date != DateTime.Today.Date)
            {
                return("Invalid DateTime");
            }
            if (DateTime.Now.Subtract(order.DateTime).Milliseconds > m_allowableOrderDelayInMilliSeconds)
            {
                return("Delayed Order");
            }
            Dictionary <string, object> optionalParam = order.OptionalParam;

            if (optionalParam != null)
            {
                bool aon = false;
                if (optionalParam.ContainsKey("AON") && (optionalParam["AON"] == null || !bool.TryParse(optionalParam["AON"].ToString(), out aon)))
                {
                    return("Invalid AON");
                }
                if (aon)
                {
                    if (!optionalParam.ContainsKey("MinQty"))
                    {
                        return("Missing Min. Qty");
                    }
                    int minq = 0;
                    if (optionalParam["MinQty"] == null || !int.TryParse(optionalParam["MinQty"].ToString(), out minq))
                    {
                        return("Invalid Min. Qty");
                    }
                    if (minq <= 0)
                    {
                        return("Invalid Min. Qty");
                    }
                    if (minq > order.Quantity)
                    {
                        return("Min. quantity should be equal or less than order's quantity");
                    }
                }

                if (optionalParam.ContainsKey(ALLOC_REQ_FIELDS.ALLOC_TYPE) && order.OrderSide == "Buy")
                {
                    bool isAllowBuyAllocation = Convert.ToBoolean(SystemConfigurations.GetAppSetting("AllowBuyAllocation"));
                    if (isAllowBuyAllocation == false)
                    {
                        return("Mcsd Allocation for buy orders is not allowed");
                    }
                }
            }

            return("valid");
        }
        private void btnSub_Click(object sender, EventArgs e)
        {
            //if (MessageBox.Show(this, "Subscribe to FIX orders service ?", "FIX Service", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
            {
                using (OrdersProxy proxy = new OrdersProxy())
                {
                    btnSub.Enabled = false;

                    ICallbackHandler m_callbackHandler;
                    InstanceContext  m_InstanceContext;
                    DuplexChannelFactory <IFixAdmin>         m_factory;
                    ICallbackHandler.IncomingMessageDelegate m_IncomingMessageDelegate = new ICallbackHandler.IncomingMessageDelegate(OnIncomingMsg);
                    m_callbackHandler = new ICallbackHandler(m_IncomingMessageDelegate);
                    m_InstanceContext = new InstanceContext(m_callbackHandler);
                    m_factory         = new DuplexChannelFactory <IFixAdmin>(m_InstanceContext, "netTcpBinding_IFixAdmin");
                    _client           = m_factory.CreateChannel();
                    ((ICommunicationObject)_client).Closed  += TcpClient_Closed;
                    ((ICommunicationObject)_client).Faulted += tcpClient_Faulted;
                    //for (int i = 0; i < 3; i++)
                    //{
                    try
                    {
                        FixAdminMsg returnMsg = _client.Subscribe(
                            new subReq()
                        {
                            Username            = "******",
                            Password            = "******",
                            QueueName           = SystemConfigurations.GetAppSetting("ResponseQueueName"),
                            QueueIP             = SystemConfigurations.GetAppSetting("ResponseQueueIP"),
                            FlushUpdatesOffline = true,
                        });

                        //FixAdminMsg returnMsg = _client.Resubscribe(
                        //   new ResupReq()
                        //   {
                        //       SessionKey = new Guid("6D0AC300-CC63-4F34-81B6-B4E6DB358DC6"),
                        //       NewQueue = true,
                        //       QueueName = SystemConfigurations.GetAppSetting("ResponseQueueName"),
                        //       QueueIP = SystemConfigurations.GetAppSetting("ResponseQueueIP"),
                        //       Username = "******",
                        //       Password = "******",
                        //       FlushUpdatesOffline = true,
                        //   });

                        isConnectedToAdmin = true;
                        SetReport(returnMsg.Code + " " + returnMsg.Note ?? "");
                        //   Task.Factory.StartNew(() => { while (isConnectedToAdmin) { _client.Ping(); Thread.Sleep(3000); } }, tokenSource.Token);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    //}
                }
            }
        }
示例#5
0
 static void sh_Closed(object sender, EventArgs e)
 {
     try
     {
         Counters.IncrementCounter(CountersConstants.ExceptionMessages);
         string[] cc = SystemConfigurations.GetAppSetting("SupportMailCC").Split(',');
         NotificationSender.Send(true, true, false, SystemConfigurations.GetAppSetting("SupportMailFrom"), SystemConfigurations.GetAppSetting("SupportMailTo"), cc, "Fix Orders Service Closed", "Fix Orders Service Closed",
                                 string.Format("Fix Orders Service has been closed on machine {0} at {1}", SystemConfigurations.GetMachineIP(), DateTime.Now.ToString()), null);
     }
     catch (Exception ex)
     {
         SystemLogger.WriteOnConsoleAsync(true, "Sending Mail Error: " + ex.Message, ConsoleColor.Red, ConsoleColor.Black, true);
     }
 }
示例#6
0
        private static void CheckAndSetPermissionsToQueues()
        {
            SystemLogger.WriteOnConsoleAsync(true, string.Format("Checking Service Queue Existance: "), ConsoleColor.Yellow, ConsoleColor.Black, false);
            string RecievedMessagesQueueName = SystemConfigurations.GetAppSetting("RecievedMessagesQueueName");
            bool   IsTransactionalQueue      = bool.Parse(SystemConfigurations.GetAppSetting("IsTransactionalQueue"));

            if (!MessageQueue.Exists(RecievedMessagesQueueName))
            {
                MessageQueue queue = MessageQueue.Create(RecievedMessagesQueueName, IsTransactionalQueue);
                SystemLogger.WriteOnConsoleAsync(true, string.Format("Done, Queue {0} has been created successfully !", queue.Path), ConsoleColor.Green, ConsoleColor.Black, false);
            }
            else
            {
                SystemLogger.WriteOnConsoleAsync(true, string.Format("Done ,Queue Already Existed!"), ConsoleColor.Green, ConsoleColor.Black, false);
            }


            SystemLogger.WriteOnConsoleAsync(true, string.Format("Setting Permission to queue: "), ConsoleColor.Yellow, ConsoleColor.Black, false);
            MessageQueue m = new MessageQueue(RecievedMessagesQueueName);

            m.SetPermissions(SystemConfigurations.GetAppSetting("FixQueueAuthenticatedUser"), MessageQueueAccessRights.FullControl, AccessControlEntryType.Allow);
            SystemLogger.WriteOnConsoleAsync(true, string.Format("Done"), ConsoleColor.Green, ConsoleColor.Black, false);
        }
 static void OpenFixConn()
 {
     try
     {
         string              fixClientConf = Environment.CurrentDirectory + @"\" + SystemConfigurations.GetAppSetting("FixClientConfPath");
         SessionSettings     settings      = new SessionSettings(fixClientConf);
         OnConnectionChanged d             = new OnConnectionChanged(FixConnChanged);
         _app = new ClientApp(d);
         //_app.OnStatusChanged+=
         FileStoreFactory storeFactory   = new FileStoreFactory(settings);
         FileLogFactory   logFactory     = new FileLogFactory(settings);
         MessageFactory   messageFactory = new DefaultMessageFactory();
         _initiator = new SocketInitiator(_app, storeFactory, settings, logFactory, messageFactory);
         _initiator.start();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
示例#8
0
 public void Initialize(string msgTypeTagValueToHandle)
 {
     m_MsgTypeTagValueToHandle = msgTypeTagValueToHandle;
     m_msgTypeTag = int.Parse(SystemConfigurations.GetAppSetting("MsgTypeTag"));
 }
示例#9
0
        protected void OnStartInternally(object arguments)
        {
            string[] args = (string[])arguments;

            try
            {
                /*if (!IsAdministrator())
                 * {
                 *  // Restart program and run as admin
                 *  var exeName = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                 *  ProcessStartInfo startInfo = new ProcessStartInfo(exeName);
                 *  startInfo.Verb = "runas";
                 *  System.Diagnostics.Process.Start(startInfo);
                 *  Environment.Exit(0);
                 *  return;
                 * }*/



                // check multiple processes
                //commented by khazbak to avoid requirement to start in admin mode

                /*
                 * if (bool.Parse(SystemConfigurations.GetAppSetting("CheckMultipleInstances")))
                 * {
                 *  string currProcName = Process.GetCurrentProcess().ProcessName;
                 *  int currProcID = Process.GetCurrentProcess().Id;
                 *  Process[] processes = Process.GetProcessesByName(currProcName);
                 *  if (processes.Length > 1)
                 *  {
                 *      foreach (Process p in processes)
                 *      {
                 *          if (p.Id != currProcID)
                 *          {
                 *              int id = p.Id;
                 *              p.Kill();
                 *              SystemLogger.WriteOnConsoleAsync(true, "Process has been killed ID: " + id, ConsoleColor.Gray, ConsoleColor.White, false);
                 *          }
                 *      }
                 *  }
                 * }*/

                Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);

                SystemLogger.LogEventAsync("Starting FIX Service...");

                try
                {
                    if (bool.Parse(SystemConfigurations.GetAppSetting("ReinitializeCounters")))
                    {
                        Counters.ReInitialize();
                    }
                    else
                    {
                        Counters.Initialize();
                    }
                }
                catch (Exception ex)
                {
                    SystemLogger.WriteOnConsoleAsync(true, "Error initializing counters, Error: " + ex.ToString(), ConsoleColor.Red, ConsoleColor.Black, true);
                }


                DatabaseMethods db = new DatabaseMethods();
                if (!db.IsTodaySequenceReset()) // reset the counters only if the service starts for first time today
                {
                    Counters.ResetCounters();
                }
                // Check queue existance
                if (bool.Parse(SystemConfigurations.GetAppSetting("CheckQueueExistance")))
                {
                    CheckAndSetPermissionsToQueues();
                }
                FixExchangesInfo.Initialize();
                Currencies.Initialize();
                StocksDefinitions.Initialize();
                Lookups.Initialize();
                string seqFilePath = SystemConfigurations.GetAppSetting("SequenceFilePath");
                if (!db.IsTodaySequenceReset())
                {
                    SystemLogger.LogEventAsync("Resetting FIX sequence..");
                    db.UpdateTodaySequenceReset();
                    SystemLogger.LogEventAsync("Sequence reset successfully");
                    //try
                    //{
                    //    System.IO.File.Delete(seqFilePath);
                    //}
                    //catch (Exception ex)
                    //{
                    //    Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                    //    SystemLogger.WriteOnConsoleAsync(true, "Deleting Sequence File Error: " + ex.Message, ConsoleColor.Red, ConsoleColor.Black, true);
                    //}
                }


                Router responsesRouter = new Router(typeof(ResponsesProcessor), int.Parse(SystemConfigurations.GetAppSetting("ResponsesRouterProcessorsNum")));

                m_FixSessionStatusChangedDelegate = new FixSessionStatusChangedDelegate(OnFixStatusChange);


                bool AllowMcsdAllocation = Convert.ToBoolean(SystemConfigurations.GetAppSetting("AllowMcsdAllocation")); // maghrabi

                if (AllowMcsdAllocation)                                                                                 //MCSD
                {
                    Router mcsdResponsesRouter = new Router(typeof(ResponsesProcessorMcsd), int.Parse(SystemConfigurations.GetAppSetting("McsdResponsesRouterProcessorsNum")));
                    McsdGatwayManager.Initialize(mcsdResponsesRouter); // maghrabi
                    McsdGatwayManager.LoginToMCSD();                   // maghrabi
                }

                string fixClientSettings = Environment.CurrentDirectory + @"\" + SystemConfigurations.GetAppSetting("FixClientSettingsFile");
                string fixServerSettings = Environment.CurrentDirectory + @"\" + SystemConfigurations.GetAppSetting("FixServerSettingsFile");
                MarketFixClient.Initialize(fixClientSettings, responsesRouter, m_FixSessionStatusChangedDelegate);
                SvcFixServer.InitializeServer(fixServerSettings);
                OrdersManager.Initialize();
                Sessions.Initialize();
                //RepSessions.Initialize();
                InitializeService();

                if (_resetSequenceNumber)
                {
                    //  MarketFixClient.ResetSequence();
                }

                MarketFixClient.Logon();



                SystemLogger.WriteOnConsoleAsync(true, "Awaiting for Fix server response ...", ConsoleColor.Yellow, ConsoleColor.Black, false);
                System.Windows.Forms.Application.Run(new frmMonitor()); //maghrabi
                //while (true) { Console.ReadKey(); }
                //StopService();
            }
            catch (Exception ex)
            {
                Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                SystemLogger.WriteOnConsoleAsync(true, "Main Error: " + ex.ToString(), ConsoleColor.Red, ConsoleColor.Black, true);

                try
                {
                    string[] cc = SystemConfigurations.GetAppSetting("SupportMailCC").Split(',');
                    NotificationSender.Send(true, true, false, SystemConfigurations.GetAppSetting("SupportMailFrom"), SystemConfigurations.GetAppSetting("SupportMailTo"), cc, "Fix Service Down", "Fix Service Down",
                                            string.Format("Service startup error state on machine {0} at {1}, Error : {2}", SystemConfigurations.GetMachineIP(), DateTime.Now.ToString(), ex.ToString()), null);
                }
                catch (Exception inex)
                {
                    Counters.IncrementCounter(CountersConstants.ExceptionMessages);
                    SystemLogger.WriteOnConsoleAsync(true, "Sending Mail Error: " + inex.Message, ConsoleColor.Red, ConsoleColor.Black, false);
                }

                //Console.ReadKey();
            }
        }
        public void StartRecievingMsgs()
        {
            // MessageQueue m_msgSenderQueue = new MessageQueue(string.Format(@"{0}\private$\{1}", SystemConfigurations.GetAppSetting("ResponseQueueIP"), SystemConfigurations.GetAppSetting("ResponseQueueName")));
            MessageQueue m_msgSenderQueue = new MessageQueue(string.Format(@"Formatname:DIRECT=TCP:{0}\private$\{1}", SystemConfigurations.GetAppSetting("ResponseQueueIP"), SystemConfigurations.GetAppSetting("ResponseQueueName")));
            //List<Type> types = System.Reflection.Assembly.Load("Beltone.Services.Fix.Contract").GetTypes().Where(x=>x.IsClass).ToList();
            //types.Add(typeof(Dictionary<string, object>));
            //XmlMessageFormatter formatter = new XmlMessageFormatter(types.ToArray());

            XmlMessageFormatter formatter = new XmlMessageFormatter
                                                (new Type[] { typeof(Fix_OrderReplaceRefusedByService), typeof(FixAdminMsg), typeof(FixAdmin_TestRequest),
                                                              typeof(Fix_OrderAcceptedResponse), typeof(Fix_OrderRejectionResponse), typeof(Fix_ExecutionReport),
                                                              typeof(LogOutResponse), typeof(LogOutResponse), typeof(Fix_BusinessMessageReject), typeof(Fix_OrderReplaceCancelReject),
                                                              typeof(Fix_OrderReplacedResponse),
                                                              typeof(Fix_PendingReplaceResponse), typeof(Fix_OrderRefusedByService), typeof(Fix_PendingNewResponse), typeof(Fix_PendingCancelResponse),
                                                              typeof(Fix_OrderCanceledResponse) });

            //if (!m_msgSenderQueue.CanRead)
            //{
            //    // warning
            //}
            while (true)
            {
                try
                {
                    //MessageQueueTransaction mqt = new MessageQueueTransaction();
                    //mqt.Begin();
                    System.Messaging.Message msg = (System.Messaging.Message)m_msgSenderQueue.Receive();
                    if (msg == null)
                    {
                        continue;
                    }

                    object recievedMsg = formatter.Read(msg);

                    this.BeginInvoke(new Action(() => SetReport(string.Format("Recieved {0}", recievedMsg.GetType().ToString()), Color.DarkGray)));

                    if (recievedMsg.GetType() == typeof(FixAdmin_TestRequest))
                    {
                        try
                        {
                            IToAdminMsg msgTo = new FixAdmin_TestResponse()
                            {
                                TestKey = ((FixAdmin_TestRequest)recievedMsg).TestKey
                            };
                            _client.HandleMsg(msgTo);
                            //_client.HandleRequest(new FixAdmin_TestResponse() { TestKey = "" });
                        }
                        catch (Exception ex)
                        {
                            this.BeginInvoke(new Action(() => MessageBox.Show(ex.Message)));
                        }
                        this.BeginInvoke(new Action(() => SetReport("sent FixAdmin_TestResponse", Color.DarkGray)));
                    }
                    if (recievedMsg.GetType() == typeof(Fix_OrderAcceptedResponse))
                    {
                        Fix_OrderAcceptedResponse resp = (Fix_OrderAcceptedResponse)recievedMsg;
                        this.BeginInvoke(new Action(() => SetReport(string.Format("order : {0} accepted", resp.ReqOrdID), Color.Green)));
                    }
                    else if (recievedMsg.GetType() == typeof(Fix_ExecutionReport))
                    {
                        Fix_ExecutionReport resp = (Fix_ExecutionReport)recievedMsg;
                        this.BeginInvoke(new Action(() => SetReport(string.Format("order : {0} TotalExecuted: {1}, TradeExecuted: {2}, Remaining {3}, Status : {4}", resp.RequesterOrderID, resp.TotalExecutedQuantity, resp.TradeExecutedQuantity, resp.RemainingQuantity, resp.OrderStatus), Color.Blue)));
                    }
                    else if (recievedMsg.GetType() == typeof(Fix_OrderSuspensionResponse))
                    {
                        Fix_OrderSuspensionResponse resp = (Fix_OrderSuspensionResponse)recievedMsg;
                        this.BeginInvoke(new Action(() => SetReport(string.Format("order : {0} suspended : {1}", resp.RequesterOrderID, resp.Message), Color.Red)));
                    }
                    else if (recievedMsg.GetType() == typeof(Fix_OrderRejectionResponse))
                    {
                        Fix_OrderRejectionResponse resp = (Fix_OrderRejectionResponse)recievedMsg;
                        this.BeginInvoke(new Action(() => SetReport(string.Format("order : {0} rejected : {1}", resp.RequesterOrderID, resp.RejectionReason), Color.Red)));
                    }
                    else if (recievedMsg.GetType() == typeof(Fix_OrderReplacedResponse))
                    {
                        Fix_OrderReplacedResponse replace = (Fix_OrderReplacedResponse)recievedMsg;
                        this.BeginInvoke(new Action(() => SetReport(string.Format("order : {0} replaced : Quantity {1} price {2}", replace.ReqOrdID, replace.Qty, replace.Prc), Color.DarkGreen)));
                    }

                    else if (recievedMsg.GetType() == typeof(Fix_OrderRefusedByService))
                    {
                        Fix_OrderRefusedByService refuseMsg = (Fix_OrderRefusedByService)recievedMsg;
                        this.BeginInvoke(new Action(() => SetReport(string.Format("order : {0} refused by service : msessage : {1} ", refuseMsg.RequesterOrderID, refuseMsg.RefuseMessage), Color.DarkOrange)));
                    }

                    else if (recievedMsg.GetType() == typeof(Fix_OrderCanceledResponse))
                    {
                        Fix_OrderCanceledResponse msgCanceled = (Fix_OrderCanceledResponse)recievedMsg;
                        this.BeginInvoke(new Action(() => SetReport(string.Format("order : {0} canceld successfully ! ", msgCanceled.RequesterOrderID), Color.DarkOrange)));
                    }


                    else if (recievedMsg.GetType() == typeof(Fix_PendingNewResponse) || recievedMsg.GetType() == typeof(Fix_PendingReplaceResponse) || recievedMsg.GetType() == typeof(Fix_PendingCancelResponse))
                    {
                        this.BeginInvoke(new Action(() => SetReport(string.Format("order pending"), Color.DarkOrange)));
                    }
                }
                catch (Exception ex)
                {
                    this.BeginInvoke(new Action(() => SetReport(string.Format("Error : {0}", ex.Message), Color.Red)));
                    Thread.Sleep(2000);
                }
            }
        }
        public FixOrdSvc()
        {
            int _requestsRouterProcessorsNum = int.Parse(SystemConfigurations.GetAppSetting("RequestsRouterProcessorsNum"));

            _router = new Router(typeof(RequestsProcessor), _requestsRouterProcessorsNum);
        }