private void Initialize()
        {
            client = new IBClient();
            client.ThrowExceptions = true;

            client.TickPrice         += client_TickPrice;
            client.TickSize          += client_TickSize;
            client.Error             += client_Error;
            client.NextValidId       += client_NextValidId;
            client.UpdateMarketDepth += client_UpdateMktDepth;
            client.RealTimeBar       += client_RealTimeBar;
            client.OrderStatus       += client_OrderStatus;
            client.OpenOrder         += client_OpenOrder;
            client.OpenOrderEnd      += client_OpenOrderEnd;
            client.ExecDetails       += new EventHandler <ExecDetailsEventArgs>(client_ExecDetails);
            client.UpdatePortfolio   += client_UpdatePortfolio;
            client.ReportException   += client_ReportException;
            client.Connect("127.0.0.1", 7496, 0);
            client.RequestAccountUpdates(true, null);
            Thread.Sleep(1000);
        }
        public static void Start(string[] args)
        {
            //set Mode to "entry" (for market entry) or "exit" (for market exit)
            //if args[1] = 1    :   Mode = "entry"
            //if args[1] = -1   :   Mode = "exit"
            GetProcessMode(args[1]);

            Logger.WriteStartToLog(DateTime.Now, "starting Program", Program.UserId);
            Logger.WriteToProgramLog(DateTime.Now,
                                   String.Format("Start Process for userId: {0} for market {1}.", Program.UserId, Mode));

            DataContext dbmanager = new DataContext();

            //get user's settings
            user = dbmanager.GetUserSettings(Program.UserId);
            if (user.UserId == null)
            {
                Logger.WriteToProgramLog(DateTime.Now, String.Format("wrong userId, cant find user settings for userId = {0}",Program.UserId));
                return;
            }

            //if mode = 'entry' calculate new rsi orders and get last(new) RSI orders list
            //if mode = 'exit' sell all the orders in the portfolio
            if (Mode.Equals("entry"))
            {
                dbmanager.CalculateTodaysOeders(user.UserId, user.NumberOfOrders, user.Capital, args[1]);
                orders = dbmanager.GetRsiOrders(user);
            }

            client = new IBClient {ThrowExceptions = true};
            client.NextValidId += (ClientNextValidId);
            client.OrderStatus += (ClientOrderStatus);
            client.ExecDetails += (ClientExecDetails);
            client.Error += (ClientError);
            client.UpdatePortfolio += (ClientUpdatePortfolio);
            client.UpdateAccountValue += (ClientUpdateAccountValue);
            client.CurrentTime += (ClientCurrentTime);

            //connect to TWS
            ConnectToTws();
            if (!client.Connected)
                ConnectToTws();

            if (!client.Connected)
            {
                Logger.WriteToLog(DateTime.Now, "ClientManager.Start: cannot connect to TWS, terminate the program", Program.UserId);
                Logger.WriteToProgramLog(DateTime.Now, string.Format("{0}: Could not connect to TWS", Program.UserId));
                if (runTwsProcesId!=0)
                    CloseTws();
                return;
            }

            client.RequestAccountUpdates(true, "");
            client.RequestCurrentTime();

            DateTime startingTime = DateTime.Now;

            // Close when all orders have been submited or 1.5 minutes have passed (counter = count orders that their status has changed)
            //while (DateTime.Now.Subtract(startingTime).Minutes < 1.5 && counter < orders.Count)
            while (!fdone)
            {
                if (fCurentTime)
                    //if (fNextValisId && done == false)
                    if (fNextValisId)
                        PlaceOrders();

                Thread.Sleep(1000); //1 secound (Wait a second for writing to the log all the remained order status)

                if (DateTime.Now.Subtract(startingTime).Minutes >= 3.5)
                {
                    Logger.WriteToLog(DateTime.Now, "Program Time Down", Program.UserId);
                    Logger.WriteToProgramLog(DateTime.Now, string.Format("{0}: Time Down", Program.UserId));
                    fdone = true;
                }
            }

            //close tws
            int closeAttempt = 0;
            if (runTwsProcesId != 0)
            {
                while (!CloseTws() && closeAttempt < 3)
                closeAttempt++;
            }

            Logger.WriteToLog(DateTime.Now, "Done", Program.UserId);
            Logger.WriteToProgramLog(DateTime.Now, string.Format("{0}: Done",Program.UserId));
        }