public OptionsManager(IBClient ibClient, DataGridView callGrid, DataGridView putGrid, DataGridView optionPositionsGrid)
 {
     this.ibClient = ibClient;
     this.callGrid = callGrid;
     this.putGrid = putGrid;
     this.positionsGrid = optionPositionsGrid;
 }
Exemple #2
0
 public AdvisorManager(IBClient ibClient, DataGridView aliasesGrid, DataGridView groupsGrid, DataGridView profilesGrid)
 {
     IbClient = ibClient;
     AliasesGrid = aliasesGrid;
     GroupsGrid = groupsGrid;
     ProfilesGrid = profilesGrid;
 }
Exemple #3
0
 public OrderManager(IBClient ibClient, DataGridView liveOrdersGrid, DataGridView tradeLogGrid)
 {
     this.ibClient = ibClient;
     this.orderDialog = new OrderDialog(this);
     this.liveOrdersGrid = liveOrdersGrid;
     this.tradeLogGrid = tradeLogGrid;
 }
 public HistoricalDataManager(IBClient ibClient, Chart chart, DataGridView gridView) : base(ibClient, chart) 
 {
     Chart historicalChart = (Chart)uiControl;
     historicalChart.Series[0]["PriceUpColor"] = "Green";
     historicalChart.Series[0]["PriceDownColor"] = "Red";
     this.gridView = gridView;
 }
        //Constructor
        public IBBrokerManager(RiskFilter r)
        {
            riskFilter = r;

            tickerIdsToProduct = new Dictionary<int, FlexTrade.Product>();
            openOrders = new Dictionary<int, Krs.Ats.IBNet.Order>();
            orderInputQueue = new List<Krs.Ats.IBNet.Order>();
            openOrderContracts = new Dictionary<int, Krs.Ats.IBNet.Contract>();
            ordersOrgFormat = new Dictionary<int, FlexTrade.Order>();

            //The interface with Interactive Brokers is a singleton. We do this to control the message
            //flow. Having multiple client connections may be better for performance and should be 
            //explored in the future.
            if (ibClient == null)
            {
                //Create the IB Client which is the main interface for interactining the broker system
                log.Info("Creating new IB Client object");
                ibClient = new IBClient();
                
                //We need to be listening for all of the events coming back from IB. This class will
                //catch all of the messages and exceptions for this broker so that other classes
                //don't need to be concerned with broker specific issues.
                ibClient.ThrowExceptions = true;
                ibClient.TickPrice += new EventHandler<TickPriceEventArgs>(priceChangeTick);
                ibClient.TickSize += new EventHandler<TickSizeEventArgs>(sizeChangeTick);
                ibClient.Error += new EventHandler<ErrorEventArgs>(errorReceived);
                ibClient.NextValidId += new EventHandler<NextValidIdEventArgs>(nextValidId);
                ibClient.ExecDetails += new EventHandler<ExecDetailsEventArgs>(fillReceived);
                ibClient.OpenOrder += new EventHandler<OpenOrderEventArgs>(openOrder);
            }
        }
 public OptionsManager(IBClient ibClient, DataGridView callGrid, DataGridView putGrid, DataGridView optionPositionsGrid, ListView optionParamsListView)
 {
     this.ibClient             = ibClient;
     this.callGrid             = callGrid;
     this.putGrid              = putGrid;
     this.positionsGrid        = optionPositionsGrid;
     this.optionParamsListView = optionParamsListView;
 }
        public HistoricalDataManager(IBClient ibClient, Chart chart, DataGridView gridView) : base(ibClient, chart)
        {
            Chart historicalChart = (Chart)uiControl;

            historicalChart.Series[0]["PriceUpColor"]   = "Green";
            historicalChart.Series[0]["PriceDownColor"] = "Red";
            this.gridView = gridView;
        }
 public NewsManager(IBClient ibClient, DataGridView tickNewsDataGrid, DataGridView newsProvidersGrid, TextBox textBoxArticleText, DataGridView historicalNewsGrid)
 {
     IbClient           = ibClient;
     TickNewsGrid       = tickNewsDataGrid;
     NewsProvidersGrid  = newsProvidersGrid;
     TextBoxArticleText = textBoxArticleText;
     HistoricalNewsGrid = historicalNewsGrid;
 }
        public ContractManager(IBClient ibClient, TextBox fundamentalsOutput, DataGridView contractDetailsGrid)
        {
            IbClient = ibClient;
            Fundamentals = fundamentalsOutput;
            ContractDetailsGrid = contractDetailsGrid;
            comboContractResults = new ComboContractResults();

        }
        public AddInstrumentInteractiveBrokersWindow()
        {
            Random r = new Random();

            _client = new IBClient();

            try
            {
                //random connection id for this one...
                _client.Connect(Properties.Settings.Default.ibClientHost, Properties.Settings.Default.ibClientPort, r.Next(1000, 200000));
            }
            catch (Exception e)
            {
                MessageBox.Show("Could not connect to TWS: " + e.Message, "Error");
                Close();
                return;
            }

            AddedInstruments = new List <Instrument>();

            _client.NextValidId        += _client_NextValidId;
            _client.ContractDetails    += _client_ContractDetails;
            _client.Error              += _client_Error;
            _client.ConnectionClosed   += _client_ConnectionClosed;
            _client.ContractDetailsEnd += _client_ContractDetailsEnd;

            Exchanges = new ObservableCollection <KeyValuePair <int, string> > {
                new KeyValuePair <int, string>(0, "All")
            };
            _exchanges = new Dictionary <string, Exchange>();

            using (var context = new MyDBContext())
            {
                _thisDS = context.Datasources.First(x => x.Name == "Interactive Brokers");

                foreach (Exchange e in context.Exchanges)
                {
                    Exchanges.Add(new KeyValuePair <int, string>(e.ID, e.Name));
                    _exchanges.Add(e.Name, e);
                }
            }

            InitializeComponent();
            DataContext = this;

            Instruments     = new ObservableCollection <Instrument>();
            InstrumentTypes = new ObservableCollection <InstrumentType>();

            //list the available types from our enum
            var values = MyUtils.GetEnumValues <InstrumentType>();

            foreach (var val in values)
            {
                InstrumentTypes.Add(val);
            }

            ShowDialog();
        }
Exemple #11
0
        public static void RunGetNewsProviders(ConnectionDetails connectionDetails)
        {
            var ibClient = new IBClient();

            ibClient.NotificationReceived        += new EventHandler <Notification>(Common.NotificationReceived);
            ibClient.NewsProvidersUpdateReceived += new EventHandler <NewsProvider[]>(NewsProvidersUpdateReceived);
            ibClient = ConnectionHelper.StartIbClient(ibClient, connectionDetails);
            ibClient.GetNewsProviders();
        }
Exemple #12
0
 public OrderManager(IBClient ibClient, DataGridView liveOrdersGrid, DataGridView tradeLogGrid, IBTradeApp appForm)
 {
     this.ibClient = ibClient;
     //this.orderDialog = new OrderDialog(this);
     this.liveOrdersGrid = liveOrdersGrid;
     this.tradeLogGrid   = tradeLogGrid;
     this.appForm        = appForm;
     this.appStgManager  = appForm.appStrategyManager;
 }
        internal HistoricalDataManager(IBController Controller, IBClient ibClient)
            : base(Controller, ibClient)
        {
            _ibClient.HistoricalData    += this.AppendPendingRequestData;
            _ibClient.HistoricalDataEnd += this.HandleEndMessage;

            _ibClient.HeadTimestamp += this.AppendPendingRequestData;
            _ibClient.HeadTimestamp += this.HandleEndMessage;
        }
Exemple #14
0
 public AccountManager(IBClient ibClient, ComboBox accountSelector, DataGridView accountSummaryGrid, DataGridView accountValueGrid,
                       DataGridView accountPortfolioGrid, DataGridView positionsGrid)
 {
     IbClient             = ibClient;
     AccountSelector      = accountSelector;
     AccountSummaryGrid   = accountSummaryGrid;
     AccountValueGrid     = accountValueGrid;
     AccountPortfolioGrid = accountPortfolioGrid;
     PositionsGrid        = positionsGrid;
 }
Exemple #15
0
 public AccountManager(IBClient ibClient, ComboBox accountSelector, DataGridView accountSummaryGrid, DataGridView accountValueGrid,
     DataGridView accountPortfolioGrid, DataGridView positionsGrid)
 {
     IbClient = ibClient;
     AccountSelector = accountSelector;
     AccountSummaryGrid = accountSummaryGrid;
     AccountValueGrid = accountValueGrid;
     AccountPortfolioGrid = accountPortfolioGrid;
     PositionsGrid = positionsGrid;
 }
Exemple #16
0
 /// <summary>
 /// An example of EUR/USD would be symbol=EUR and currency=USD
 /// </summary>
 /// <param name="ibClient"></param>
 /// <param name="symbol"></param>
 /// <param name="currency"></param>
 public static void RequestForexContract(IBClient ibClient, string symbol, string currency)
 {
     ibClient.GetContractDetails(new Contract
     {
         Symbol   = symbol,
         SecType  = SecurityType.CASH.ToString(),
         Exchange = "IDEALPRO",
         Currency = currency
     });
 }
Exemple #17
0
 public static void RequestComodityContract(IBClient ibClient, string symbol, string currency)
 {
     ibClient.GetContractDetails(new Contract
     {
         Symbol   = symbol,
         SecType  = SecurityType.CMDTY.ToString(),
         Exchange = "SMART",
         Currency = currency
     });
 }
Exemple #18
0
        static void Main(string[] args)
        {
            /*
             * OrderManager om = new OrderManager();
             * MainViewModel.Instance.test();
             */
            //IBController controller = new IBController(MainViewModel.Instance);
            //controller.test();
            //Console.ReadLine();
            IBClient client = new IBClient();

            client.Connect("localhost", 4002, 1);
            Task.Run(() => client.PlaceOrder(1000, new Contract("MHIN9", "HKFE", SecurityType.Future, "HKD"), new Order()));
            Task.Run(() => client.CancelOrder(1000));
            var c = JsonConvert.DeserializeObject <Dictionary <string, string> >("");
            Dictionary <string, Dictionary <string, GTA> > t = new Dictionary <string, Dictionary <string, GTA> >();

            t.Add("buy", new Dictionary <string, GTA>()
            {
                { "GTA", new GTA()
                  {
                      DT = DateTime.Now
                  } }
            });
            string s1 = JsonConvert.SerializeObject(t);
            string s  = "{'buy':{'GTA':{'DT':'15:39'}}}";
            var    dateTimeConverter = new IsoDateTimeConverter {
                DateTimeFormat = "HH:mm"
            };
            Dictionary <string, Dictionary <string, GTA> > t1 = JsonConvert.DeserializeObject <Dictionary <string, Dictionary <string, GTA> > >(s, dateTimeConverter);
            //Console.ReadLine();

            /*
             * Test test = new Test();
             * test.Names.Add("chan");
             * List<string> t = test.Names;
             * Test test1 = null;
             * PropertyInfo pi;
             * test1 = (Test)Reflection.GetPropertyParent(t, "Test.Names", out pi);*/
            Regex r1 = new Regex(@"(?<dateFormat>y*[-\/]*M*[-\/]*[Dd]*)(?<dateFormat>M*[-\/]*[Dd]*[-\/]*y*)(?<dateFormat>[Dd]*[-\/]*M*[-\/]*y*)(?<timeFormat>[Hh]*[:]*m*[:]*s*[ ]*t*)");
            Regex r2 = new Regex(@"([Hh]*[:]*m*[:]*s*[ ]*t*)");
            //var p1 = new PcreRegex(@"(y*[-\/]*M*[-\/]*[Dd]*)(M*[-\/]*[Dd]*[-\/]*y*)([Dd]*[-\/]*M*[-\/]*y*)([Hh]*[:]*m*[:]*s*[ ]*t*)");
            string          input = "MMDDyyyy HH:mm:ss";
            MatchCollection match = r1.Matches(input);
            Match           m2    = r2.Match(input);

            //var m3 = p1.Match(input);

            if (m2.Success)
            {
                //string v = match.Groups[1].Value;
                //Console.WriteLine("Between One and Three: {0}", v);
            }
        }
        public AddInstrumentInteractiveBrokersWindow()
        {
            Random r = new Random();
            _client = new IBClient();

            try
            {
                //random connection id for this one...
                _client.Connect(Properties.Settings.Default.ibClientHost, Properties.Settings.Default.ibClientPort, r.Next(1000, 200000));
            }
            catch (Exception e)
            {
                MessageBox.Show("Could not connect to TWS: " + e.Message, "Error");
                Close();
                return;
            }

            AddedInstruments = new List<Instrument>();

            _client.NextValidId += _client_NextValidId;
            _client.ContractDetails += _client_ContractDetails;
            _client.Error += _client_Error;
            _client.ConnectionClosed += _client_ConnectionClosed;
            _client.ContractDetailsEnd += _client_ContractDetailsEnd;

            Exchanges = new ObservableCollection<KeyValuePair<int, string>> { new KeyValuePair<int, string>(0, "All") };
            _exchanges = new Dictionary<string, Exchange>();

            using (var context = new MyDBContext())
            {
                _thisDS = context.Datasources.First(x => x.Name == "Interactive Brokers");

                foreach (Exchange e in context.Exchanges)
                {
                    Exchanges.Add(new KeyValuePair<int, string>(e.ID, e.Name));
                    _exchanges.Add(e.Name, e);
                }
            }

            InitializeComponent();
            DataContext = this;

            Instruments = new ObservableCollection<Instrument>();
            InstrumentTypes = new ObservableCollection<InstrumentType>();

            //list the available types from our enum
            var values = MyUtils.GetEnumValues<InstrumentType>();
            foreach (var val in values)
            {
                InstrumentTypes.Add(val);
            }

            ShowDialog();
        }
 public ContractManager(IBClient ibClient, TextBox fundamentalsOutput, DataGridView contractDetailsGrid, DataGridView bondContractDetailsGrid, ComboBox comboBoxMarketRuleId,
                        DataGridView dataGridViewMarketRule, Label labelMarketRuleIdRes)
 {
     IbClient                = ibClient;
     Fundamentals            = fundamentalsOutput;
     ContractDetailsGrid     = contractDetailsGrid;
     BondContractDetailsGrid = bondContractDetailsGrid;
     comboContractResults    = new ComboContractResults();
     ComboBoxMarketRuleId    = comboBoxMarketRuleId;
     DataGridViewMarketRule  = dataGridViewMarketRule;
     LabelMarketRuleIdRes    = labelMarketRuleIdRes;
 }
        /// <summary>
        /// Argument Constructor
        /// </summary>
        public InteractiveBrokersMarketDataProvider(IBClient ibClient, ConnectionParameters parameters)
        {
            _ibClient   = ibClient;
            _parameters = parameters;

            _ask = new Tick {
                MarketDataProvider = _marketDataProviderName
            };
            _bid = new Tick {
                MarketDataProvider = _marketDataProviderName
            };
        }
Exemple #22
0
        public static void Get(IBClient ibClient, string symbol)
        {
            Contract contract = new Contract();

            contract.Symbol   = "AAPL";
            contract.SecType  = "STK";
            contract.Currency = "USD";
            //In the API side, NASDAQ is always defined as ISLAND in the exchange field
            contract.Exchange = "SMART";                                                                                                                  // SMART

            ibClient.ClientSocket.reqMktData((Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds, contract, "", true, false, null);; // Request market data for a contract https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient.html#a7a19258a3a2087c07c1c57b93f659b63
        }
Exemple #23
0
 public AccountDetailManager(IBClient ibClient, DataGridView accountValueGrid, DataGridView accountPortfolioGrid, IBTradeApp appForm)
 {
     IbClient                  = ibClient;
     AccountValueGrid          = accountValueGrid;
     this.accountPortfolioGrid = accountPortfolioGrid;
     this.appForm              = appForm;
     String[] tags = ACCOUNT_VALUE_TAGS.Split(',');
     valid_account_values = new Dictionary <string, string>();
     foreach (String tag in tags)
     {
         valid_account_values.Add(tag, tag);
     }
     appStrategyManager = appForm.appStrategyManager;
 }
        public static void RunBasicDownload(ConnectionDetails connectionDetails)
        {
            var ibClient = new IBClient();

            ibClient.NotificationReceived            += new EventHandler <Notification>(Common.NotificationReceived);
            ibClient.HistoricalDataUpdateEndReceived += new EventHandler <Tuple <int, List <Bar> > >(HistoricalDataUpdateEndReceived);
            ibClient = ConnectionHelper.StartIbClient(ibClient, connectionDetails);

            var duration = new Duration {
                Unit = 1, DurationType = DurationType.D
            };

            ibClient.GetHistoricalData(1005, _contract, DateTime.Now, duration, BarSize.FiveMinutes, WhatToShow.MIDPOINT, Rth.No, false);
        }
Exemple #25
0
        public ContractSearch(IBClient ibClient)         // Class constructor. Takes only ibClient instance into the constructor
        {
            IbClient = ibClient;

            contract = new Contract();             // New instance of the contract class

            //contract.Symbol = "AAPL";
            contract.SecType  = "STK";
            contract.Exchange = "SMART";
            contract.Currency = "USD";
            //contract.LastTradeDateOrContractMonth = this.conDetLastTradeDateOrContractMonth.Text;
            //contract.Strike = 10;
            //contract.Multiplier = this.conDetMultiplier.Text;
        }
Exemple #26
0
        public ContractSearchDialog(Contract c, IBClient ibClient)
        {
            InitializeComponent();

            this.ibClient = ibClient;
            Contract      = c;

            if (c != null)
            {
                tbSymbol.Text   = c.Symbol;
                tbExchange.Text = c.Exchange;
                tbCurrency.Text = c.Currency;
                cbSecType.Text  = c.SecType;
            }
        }
        public HistoricalDataManager(IBClient ibClient, Chart chart, DataGridView gridView, IBTradeApp appForm)
            : base(ibClient, chart)
        {
            /*
             * Chart historicalChart = (Chart)uiControl;
             * historicalChart.Series[0]["PriceUpColor"] = "Green";
             * historicalChart.Series[0]["PriceDownColor"] = "Red";
             */
            this.gridView = gridView;
            this.appForm  = appForm;
            AppStrategyManager stgManager = appForm.appStrategyManager;

            this.appMDManager    = stgManager.getAppMDManager();
            this.RTBSynchronizer = appMDManager.getAppRTBSynchronizer();
        }
 void DisposeIBClient()
 {
     if (client != null)
     {
         logger.Debug("Disconnecting IBClient");
         client.Disconnect();
         Thread.Sleep(250);
         logger.Debug("Stopping IBClient Worker Thread");
         client.Stop();
         Thread.Sleep(250);
         logger.Debug("Disposing IB Client");
         client.Dispose();
         Thread.Sleep(250);
         client = null;
         Thread.Sleep(250);
     }
 }
Exemple #29
0
 public IBTradeApp()
 {
     initProperties();
     appStrategyManager = new AppStrategyManager(this);
     InitializeComponent();
     ibClient = new IBClient(this);
     readOrderFromFiles();
     orderManager = new OrderManager(ibClient, grid_open_order, grid_order_summary, this);
     appStrategyManager.setOrderManager(orderManager);
     appStrategyManager.ibClient = ibClient;
     accountManager        = new AccountDetailManager(ibClient, grid_account_details, grid_pos_summary, this);
     marketDataManager     = new MarketDataManager(ibClient, grid_market_price, appStrategyManager);
     realTimeBarManager    = new RealTimeBarsManager(ibClient, null, grid_rt_bar, appStrategyManager.getAppMDManager(), this);
     historicalDataManager = new HistoricalDataManager(ibClient, null, grid_hist_bar, this);
     tabMain.SelectedTab   = tabOrderStatus;
     initTickerInfo();
 }
Exemple #30
0
        public HistoryLoader(IBClientCore ibClient
                             , Contract contract
                             , int periodsBack
                             , DateTime endDate
                             , TimeSpan duration
                             , TimeUnit timeUnit
                             , BarSize barSize
                             , DataMapDelegate <T> map
                             , Action <IList <T> > done
                             , Action <IList <T> > dataEnd
                             , Action <Exception> error)
        {
            _ibClient = ibClient;
            _contract = contract;
            if (_contract.Exchange.IsNullOrEmpty())
            {
                _contract = ibClient.ReqContractDetailsCached(contract).ToEnumerable().ToArray().Select(cd => cd.Summary.ContractFactory())
                            .Count(1, new { HistoryLoader = new { _contract } })
                            .Single();
            }
            _periodsBack = periodsBack;
            _reqId       = (++_currentTicker) + HISTORICAL_ID_BASE;
            _list        = new List <T>();
            _list2       = new List <T>();
            if (endDate.Kind == DateTimeKind.Unspecified)
            {
                throw new Exception(new { endDate = new { endDate.Kind } } +"");
            }
            _dateStart = endDate.Subtract(duration);
            _endDate   = endDate.ToLocalTime();
            _timeUnit  = timeUnit;
            _barSize   = barSize;
            var durationByPeriod = barSize.Span().Multiply(periodsBack);

            _duration = duration.Max(durationByPeriod);
            _done     = done;
            _dataEnd  = dataEnd;
            _error    = error;
            _delay    = TimeSpan.Zero;
            _map      = map;
            Done      = false;
            Init();
            var me = this;

            RequestHistoryDataChunk();
        }
Exemple #31
0
        public IBApp.IBAppClasses.PlaceOrder placeOrder;         // PlaceOrder class variable

        // Linking system events and handlers
        public Form1()
        {
            InitializeComponent();             // Form components init

            // Instances
            ibClient        = new IBClient(signal);
            contractManager = new ContractManager(ibClient, fundamentalsOutput, contractDetailsGrid);
            contractSearch  = new IBAppClasses.ContractSearch(ibClient);

            // Events
            ibClient.Error            += ibClient_Error;
            ibClient.NextValidId      += ibClient_NextValidId;                                                                          // For log messages
            ibClient.ContractDetails  += (reqId, contractDetails) => HandleMessage(new ContractDetailsMessage(reqId, contractDetails)); //  Request contract details https://interactivebrokers.github.io/tws-api/contract_details.html#gsc.tab=0
            ibClient.ConnectionClosed += ibClient_ConnectionClosed;                                                                     // Update UI when disconnect button is clicked

            // Order
            placeOrder = new IBAppClasses.PlaceOrder(ibClient);             // New instance
        }
        /// <summary>
        /// Disconnects/Stops a client
        /// </summary>
        public bool Stop()
        {
            try
            {
                if (_ibClient != null)
                {
                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Sending disconnect call for IB.", _type.FullName, "Stop");
                    }
                    // Toggle Field Value
                    _logoutRequest = true;

                    foreach (var ids in _idsMap.Values)
                    {
                        // Send Unsubscription Map
                        _ibClient.CancelMarketData(ids);
                    }

                    _ibClient = null;

                    // Raised Logout Event
                    if (LogoutArrived != null)
                    {
                        LogoutArrived(_marketDataProviderName);
                    }
                }
                else
                {
                    if (Logger.IsInfoEnabled)
                    {
                        Logger.Info("Connection no longer exists.", _type.FullName, "Stop");
                    }
                }

                // Indicating calls were successfully sent
                return(true);
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "Stop");
                return(false);
            }
        }
        /// <summary>
        /// Connects/Starts a client
        /// </summary>
        public bool Start()
        {
            try
            {
                if (Logger.IsInfoEnabled)
                {
                    Logger.Info("Sending connection call for IB.", _type.FullName, "Start");
                }
                if (_ibClient == null)
                {
                    _ibClient = new IBClient();
                }

                // Toggle Field Value
                _logoutRequest = false;

                // Hook Gateway Events
                RegisterGatewayEvents();

                _ibClient.Connect(_parameters.Host, _parameters.Port, _parameters.ClientId);

                Task.Factory.StartNew(
                    () =>
                {
                    while (!IsConnected())
                    {
                    }

                    // Raise Logon Event
                    if (LogonArrived != null)
                    {
                        LogonArrived(_marketDataProviderName);
                    }
                });

                // Indicating calls were successfully sent
                return(true);
            }
            catch (Exception exception)
            {
                Logger.Error(exception, _type.FullName, "Start");
                return(false);
            }
        }
Exemple #34
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     if (btnConnect.Text == "Connect")
     {
         client = new IBClient();
         client.ThrowExceptions = true;
         client.Connect(tbIPAddress.Text, Convert.ToInt32(tbPort.Text), 0);
         client.HistoricalData += client_HistoricalData;
         btnConnect.Text = "Disconnect";
         gbDownloadConfiguration.Enabled = true;
     }
     else
     {
         client.Disconnect();
         client.Dispose();
         client = null;
         btnConnect.Text = "Connect";
         gbDownloadConfiguration.Enabled = false;
     }
 }
Exemple #35
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     if (btnConnect.Text == "Connect")
     {
         client = new IBClient();
         client.ThrowExceptions = true;
         client.Connect(tbIPAddress.Text, Convert.ToInt32(tbPort.Text), 0);
         client.HistoricalData          += client_HistoricalData;
         btnConnect.Text                 = "Disconnect";
         gbDownloadConfiguration.Enabled = true;
     }
     else
     {
         client.Disconnect();
         client.Dispose();
         client          = null;
         btnConnect.Text = "Connect";
         gbDownloadConfiguration.Enabled = false;
     }
 }
        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);
        }
Exemple #37
0
        public static IBClient StartIbClient(IBClient ibClient, ConnectionDetails connectionDetails)
        {
            ibClient.ClientSocket.eConnect(connectionDetails.Host, connectionDetails.Port, connectionDetails.ClientId);
            var reader = new EReader(ibClient.ClientSocket, ibClient.Signal);

            reader.Start();
            new Thread(() =>
            {
                while (ibClient.ClientSocket.IsConnected())
                {
                    ibClient.Signal.waitForSignal();
                    reader.processMsgs();
                }
            })
            {
                IsBackground = true
            }.Start();

            //Force the thread to sleep in order to get all notifications from the gateway before going ahead
            Thread.Sleep(TimeSpan.FromSeconds(5));

            return(ibClient);
        }
Exemple #38
0
        private bool openConnection()
        {
            string text;
            ordersValid = false;
            positionsValid = false;

            tStart("openConnection()");
            // check TWS

            // open socket connection
            if (ibclient == null)
            {
                _twsConnected = false;
                logger.AddLog(LoggerLevel.Detail, "new IBClient");
                // use factory to enable unit tests
                // ibclient = new IBClient();
                ibclient = Factory.GetIbClient();
                // DEBUG
                ibclient.ThrowExceptions = true;
                ibclient.Error += ibclient_Error;
                ibclient.ConnectionClosed += ibclient_ConnectionClosed;
                ibclient.CurrentTime += new EventHandler<CurrentTimeEventArgs>(ibclient_CurrentTime);
                ibclient.UpdateAccountValue += new EventHandler<UpdateAccountValueEventArgs>(ibclient_UpdateAccountValue);
                ibclient.NextValidId += new EventHandler<NextValidIdEventArgs>(ibclient_NextValidId);
                ibclient.OpenOrder += new EventHandler<OpenOrderEventArgs>(ibclient_OpenOrder);
                ibclient.OrderStatus += new EventHandler<OrderStatusEventArgs>(ibclient_OrderStatus);
                ibclient.UpdatePortfolio += new EventHandler<UpdatePortfolioEventArgs>(ibclient_UpdatePortfolio);
                ibclient.ExecDetails += new EventHandler<ExecDetailsEventArgs>(ibclient_ExecDetails);
                ibclient.AccountDownloadEnd += new EventHandler<AccountDownloadEndEventArgs>(ibclient_AccountDownloadEnd);
                ibclient.ExecutionDataEnd += new EventHandler<ExecutionDataEndEventArgs>(ibclient_ExecutionDataEnd);
                ibclient.OpenOrderEnd += new EventHandler<EventArgs>(ibclient_OpenOrderEnd);
                ibclient.ManagedAccounts += new EventHandler<ManagedAccountsEventArgs>(ibclient_ManagedAccounts);
            }

            if (!ibclient.Connected)
            {
                logger.AddLog(LoggerLevel.Detail, "Connect");
                ibclient.Connect(Hostname, Port, clientId);

                if (!ibclient.Connected)
                {
                    _twsConnected = false;
                    return false;
                }
                ibclient.ThrowExceptions = false;
                _twsConnected = true;
                logger.AddLog(LoggerLevel.Detail, "Connected");

                //// sync PC clock to IB Server time
                //if (settings.SynchronizeMachineTimeToIBServerTime
                //    == MachineTime.SynchToIBServerTime)
                //{
                //    logger.AddLog(LoggerLevel.Detail, "Sync PC clock");
                //    string dtStr = ibclient.TwsConnectionTime;
                //    DateTime dt = DateTime.ParseExact(dtStr.Substring(0, 17),
                //        "yyyyMMdd HH:mm:ss", CultureInfo.InvariantCulture);
                //    SetMachineTimeToServerTime(dt);
                //}

                //// nicht für Gateway FIX
                //if (settings.DataHost == "") ibclient.SetServerLogLevel(settings.LogLevel);

                // cancel old market subscriptions
                //logger.AddLog(LoggerLevel.Detail, "Cancel old market data subscriptions");
                //for (int i = 10000; i < 10200; i++)
                //{
                    // DEBUG
                    // ibclient.CancelMktData(i);
                //}
                // successful started, reset reconnection counter
                watchdog.Start();
            }
            lock (private_lock)
            {
                isFAAccount = true;
            }
            ibclient.RequestManagedAccts();

            //// wait for account list or error
            int numAccounts = 0;
            for (int timeout = 20; timeout>0 ; timeout-- )
            {
                lock (private_lock)
                {
                    if (!isFAAccount) break;
                    numAccounts = activeAccounts.Count;
                    if (numAccounts > 0) break;
                }

                Thread.Sleep(500);
            }
            if(isFAAccount) info(numAccounts + " Accounts found");
            RequestAccountUpdates();
            lastPortfolioUpdate = DateTime.Now;
            ibclient.RequestOpenOrders();
            lastOpenOrderUpdate = DateTime.Now;

            ibclient.RequestIds(1);
            ibclient.RequestCurrentTime();

            _twsServerVersion = ibclient.ServerVersion.ToString();
            _twsConnectionTime = ibclient.TwsConnectionTime;
            text = "Connected, Server Version = " + _twsServerVersion
                          + ", Connection Time = " + _twsConnectionTime;
            logger.AddLog(LoggerLevel.Information, text);
            _isConnected = true;
            EmitConnected();
            tEnd("openConnection()");
            return true;
        }
Exemple #39
0
 public DataManager(IBClient client, Control dataGrid)
 {
     ibClient = client;
     uiControl = dataGrid;
 }
Exemple #40
0
 public DataManager(IBClient client, Control dataGrid)
 {
     ibClient  = client;
     uiControl = dataGrid;
 }
        public AddInstrumentIbViewModel(DialogCoordinator dialogService)
        {
            _dialogService = dialogService;
            CreateCommands();

            Random r = new Random();
            _client = new IBClient();

            //random connection id for this one...
            _client.Connect(Properties.Settings.Default.ibClientHost, Properties.Settings.Default.ibClientPort, r.Next(1000, 200000));

            AddedInstruments = new List<Instrument>();

            _client.ContractDetails += _client_ContractDetails;
            _client.ContractDetailsEnd += _client_ContractDetailsEnd;

            Observable
                .FromEventPattern<ConnectionClosedEventArgs>(_client, "ConnectionClosed")
                .ObserveOnDispatcher()
                .Subscribe(e => _logger.Log(NLog.LogLevel.Warn, "IB Instrument Adder connection closed."));

            Observable
                .FromEventPattern<NextValidIdEventArgs>(_client, "NextValidId")
                .Subscribe(e => _nextRequestID = e.EventArgs.OrderId);

            Observable
                .FromEventPattern<ErrorEventArgs>(_client, "Error")
                .ObserveOnDispatcher()
                .Subscribe(e =>
                {
                    if (e.EventArgs.ErrorMsg != "No security definition has been found for the request")
                    {
                        _logger.Log(NLog.LogLevel.Error,
                            string.Format("{0} - {1}", e.EventArgs.ErrorCode, e.EventArgs.ErrorMsg));
                    }

                    Status = e.EventArgs.ErrorMsg;
                    SearchUnderway = false;
                });

            Exchanges = new ObservableCollection<string> { "All" };
            _exchanges = new Dictionary<string, Exchange>();

            using (var context = new MyDBContext())
            {
                _thisDS = context.Datasources.First(x => x.Name == "Interactive Brokers");

                foreach (Exchange e in context.Exchanges)
                {
                    Exchanges.Add(e.Name);
                    _exchanges.Add(e.Name, e);
                }
            }

            Instruments = new ObservableCollection<Instrument>();
            InstrumentTypes = new ObservableCollection<InstrumentType>();

            //list the available types from our enum
            var values = MyUtils.GetEnumValues<InstrumentType>();
            foreach (var val in values)
            {
                InstrumentTypes.Add(val);
            }
        }
Exemple #42
0
        static void Main(string[] args)
        {
            client = new IBClient {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.ExecDetails += client_ExecDetails;
            client.CommissionReport += client_CommissionReport;

            Console.WriteLine("Connecting to IB.");
            client.Connect("127.0.0.1", 7496, 10);

            //TF = new Future("TF", "NYBOT", "USD", "200909");
            //YmEcbot = new Future("YM", "ECBOT", "USD", "200909");
            //ES = new Future("ES", "GLOBEX", "USD", "200909");
            //SPY = new Future("SPY", "GLOBEX", "USD", "200909");
            //ZN = new Future("ZN", "ECBOT", "USD", "200909");
            //ZB = new Future("ZB", "ECBOT", "USD", "200909");
            //ZT = new Future("ZT", "ECBOT", "USD", "200909");
            //ZF = new Future("ZF", "ECBOT", "USD", "200909");

            //TickNasdaq = new Index("TICK-NASD", "NASDAQ");
            //VolNasdaq = new Index("VOL-NASD", "NASDAQ");
            //AdNasdaq = new Index("AD-NASD", "NASDAQ");
            //TickNyse = new Index("TICK-NYSE", "NYSE");
            //VolNyse = new Index("VOL-NYSE", "NYSE");
            //AdNyse = new Index("AD-NYSE", "NYSE");

            //New Contract Creation Features
            //var Google = new Equity("GOOG");

            //Forex Test
            var EUR = new Forex("EUR", "USD");

            //Order BuyContract = KrsOrderFactory.CreateOrder(ActionSide.Buy, OrderType.Limit, 560, 0, 1, false, 0);
            //BuyContract.OutsideRth = false;
            //BuyContract.LimitPrice = 560;
            //BuyContract.OrderType = OrderType.Limit;
            //BuyContract.TotalQuantity = 1;
            //client.PlaceOrder(503, TF, BuyContract);

            client.RequestExecutions(NextOrderId++, new KrsExecutionFilter());
            client.RequestAllOpenOrders();

            client.RequestMarketData(NextOrderId++, EUR, null, false, false);
            client.RequestMarketDepth(NextOrderId++, EUR, 5);
            client.RequestRealTimeBars(NextOrderId++, EUR, 5, RealTimeBarType.Midpoint, false);
            //client.RequestMarketData(NextOrderId++, EUR, null, false, false);

            while(true)
            {
                Thread.Sleep(100);
            }
        }
 void DisposeIBClient()
 {
     if (client != null)
     {
         logger.Debug("Disconnecting IBClient");
         client.Disconnect();
         Thread.Sleep(250);
         logger.Debug("Stopping IBClient Worker Thread");
         client.Stop();
         Thread.Sleep(250);
         logger.Debug("Disposing IB Client");
         client.Dispose();
         Thread.Sleep(250);
         client = null;
         Thread.Sleep(250);
     }
 }
 public RealTimeBarsManager(IBClient ibClient, Chart rtBarsChart, DataGridView rtBarsGrid) : base(ibClient, rtBarsChart, rtBarsGrid)
 {
 }
Exemple #45
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        static void Main(string[] args)
        {
            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.ExecDetails += client_ExecDetails;

            Console.WriteLine("Connecting to IB.");
            client.Connect("127.0.0.1", 7496, 0);
            TF = new Contract("TF", "NYBOT", SecurityType.Future, "USD", "200909");
            YmEcbot = new Contract("YM", "ECBOT", SecurityType.Future, "USD", "200909");
            ES = new Contract("ES", "GLOBEX", SecurityType.Future, "USD", "200909");
            SPY = new Contract("SPY", "GLOBEX", SecurityType.Future, "USD", "200909");
            ZN = new Contract("ZN", "ECBOT", SecurityType.Future, "USD", "200909");
            ZB = new Contract("ZB", "ECBOT", SecurityType.Future, "USD", "200909");
            ZT = new Contract("ZT", "ECBOT", SecurityType.Future, "USD", "200909");
            AAPL = new Contract("ZF", "ECBOT", SecurityType.Future, "USD", "200909");

            //TickNasdaq = new Contract("TICK-NASD", "NASDAQ", SecurityType.Index, "USD");
            //VolNasdaq = new Contract("VOL-NASD", "NASDAQ", SecurityType.Index, "USD");
            //AdNasdaq = new Contract("AD-NASD", "NASDAQ", SecurityType.Index, "USD");


            //TickNyse = new Contract("TICK-NYSE", "NYSE", SecurityType.Index, "USD");
            //VolNyse = new Contract("VOL-NYSE", "NYSE", SecurityType.Index, "USD");
            //AdNyse = new Contract("AD-NYSE", "NYSE", SecurityType.Index, "USD");

            //New Contract Creation Features
            Equity Google = new Equity("GOOG");

            client.RequestMarketData(14, Google, null, false, false);
            client.RequestMarketDepth(15, Google, 5);
            client.RequestRealTimeBars(16, Google, 5, RealTimeBarType.Trades, false);

            Order BuyContract = new Order();
            BuyContract.Action = ActionSide.Sell;
            BuyContract.OutsideRth = false;
            BuyContract.LimitPrice = 560;
            BuyContract.OrderType = OrderType.Market;
            BuyContract.TotalQuantity = 1;
            BuyContract.AuxPrice = 560;       
            
            
            client.PlaceOrder(NextOrderId, Google, BuyContract);
            client.RequestIds(1);

            client.RequestExecutions(34, new ExecutionFilter());

            client.RequestAllOpenOrders();

            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Form1());

            while (true)
            {
                Thread.Sleep(100);
            }
        }
Exemple #46
0
 public HistoricalDataTestApp()
 {
     InitializeComponent();
     client = null;
     gbDownloadConfiguration.Enabled = false;
 }
Exemple #47
0
        void ibclient_ConnectionClosed(object sender, ConnectionClosedEventArgs e)
        {
            tStart("ibclient_ConnectionClosed()");
            //Console.WriteLine("Stingray: Connection to TWS closed");
            logger.AddLog(LoggerLevel.Error, "ConnectionClosed()");
            bool callDisconnect = false;
            lock (private_lock)
            {
                _twsConnected = false;
                if (ibclient != null && ibclient.Connected) callDisconnect = true;
                Accounts.Disconnect();
            }
            // if(callDisconnect)
            //try
            //{

            //        if(callDisconnect) ibclient.Disconnect();
            //}
            //catch (Exception /*ex*/)
            //{
            //    // MessageBox.Show("ibclient_ConnectionClosed: Disconnect: " + ex.Message);
            //    ibclient = null;
            //}
            ibclient = null;
            ordersValid = false;
            positionsValid = false;

            _isConnected = false;
            EmitDisconnected();
            tEnd("ibclient_ConnectionClosed()");
        }
        private void ConnectToIB()
        {
            DisposeIBClient();

            logger.Info("Rebuilding IBClient");

            if (client != null)
                client.Dispose();

            client = new IBClient();
            Thread.Sleep(1000);
            logger.Info("IBClient Rebuilt");


            //client.ThrowExceptions = true;
            int retryCt = 5;
            while (!client.Connected)
            {
                if ((retryCt--) <= 0)
                {
                    logger.Info("Tried to reconnect 5 times going to try re-creating the client...");
                    return;
                }
                
                if (terminateRequested) 
                    ShutdownRecorder();

                try
                {
                    //int clientID = (new Random()).Next(0, 2000);
                    logger.Info("Connecting to TWS Interactive brokers with host "+ settings.IBHostToConnectTo 
                        + " on port " + settings.IBPortToConnectTo + "..." +"(Try " + (4-retryCt) + " of 5)" );
                    client.Connect(settings.IBHostToConnectTo, settings.IBPortToConnectTo, 1);
                    logger.Info("Connection initiated, requesting data");
                    Thread.Sleep(2000);
                    client.RequestIds(1);
                    Thread.Sleep(2000);
                }
                catch (Exception ex)
                {
                    logger.Info("IB Connecting Exception: " + ex.Message);
                    if (terminateRequested) // changed: 2004-1-28
                        ShutdownRecorder();
                    Thread.Sleep(3000);
                }
            }
            logger.Info("TWS Client Connected is now true.");

            Thread.Sleep(2000);

            logger.Info("Connected to TWS server version {0} at {1}.", client.ServerVersion, client.TwsConnectionTime); 

            client.TickPrice += client_TickPrice;
            client.TickSize += client_TickSize;
            client.Error += client_Error;

            //client.UpdateMarketDepth += new EventHandler<UpdateMarketDepthEventArgs>(client_UpdateMarketDepth);
            //client.UpdateMarketDepthL2 += new EventHandler<UpdateMarketDepthL2EventArgs>(client_UpdateMarketDepthL2);
            //// client.TickString += new EventHandler<TickStringEventArgs>(client_TickString); // nothing of value that I see
            //client.TickGeneric += new EventHandler<TickGenericEventArgs>(client_TickGeneric);
            //client.TickEfp += new EventHandler<TickEfpEventArgs>(client_TickEfp);
            //client.FundamentalData += new EventHandler<FundamentalDetailsEventArgs>(client_FundamentalData);
            //client.ContractDetails += new EventHandler<ContractDetailsEventArgs>(client_ContractDetails);
            //client.RequestNewsBulletins(false);

            /////////// Register the list of symbols for TWS ///////////
            string listToEcho = "";
            for (int s = 0; s < symbols.Count(); s++)
            {
                string name = symbols[s].Symbol.Trim();

                Contract item = new Contract(name, symbols[s].Market, symbols[s].securityType, "USD");
                client.RequestMarketData(symbols[s].SymbolID, item, null, false, false);

                // Examples..
                //axTws1.reqMktData(curID++, symbols[s], "STK", "", 0, "", "", "SMART", "ISLAND", "USD", "", 0);
                //client.RequestMarketDepth(symbol.SymbolID, item, 10);
                //client.RequestContractDetails(symbol.SymbolID, item);
                //client.RequestFundamentalData(symbol.SymbolID, item, "Estimates");
                //client.RequestFundamentalData(symbol.SymbolID, item, "Financial Statements");
                //client.RequestFundamentalData(symbol.SymbolID, item, "Summary");

                listToEcho += ", " + name;
            }
            logger.Debug("Symbols: {0}", listToEcho); 
            //(NowString() + ": Symbols: " + listToEcho).Log();
        }
 public DeepBookManager(IBClient client, DataGridView dataGrid) : base(client, dataGrid)
 {
     
 }
        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));
        }
Exemple #51
0
 public ScannerManager(IBClient client, DataGridView dataGrid)
     : base(client, dataGrid)
 {
 }
Exemple #52
0
        private SearchJsonResponse searchJsonResponse;                    // Json search results object

        public Form1()
        {
            InitializeComponent();

            Log.InitializeDB();
            logThread = new Thread(new ThreadStart(LogThread));             // Make an instance of the thread and assign method name which will be executed in the thread


            // listView1 setup
            listView1.View          = View.Details;    // Shows the header
            listView1.FullRowSelect = true;            // !!!Lets to select the whole row in the table!!!

            // Fleck socket server
            FleckLog.Level = LogLevel.Debug;

            // Json search object class instance
            searchJsonResponse = new SearchJsonResponse();

            allSockets = new List <IWebSocketConnection>();
            var server = new WebSocketServer("ws://0.0.0.0:8181");

            server.SupportedSubProtocols = new[] { "superchat", "chat" };
            server.Start(socket =>
            {
                socket.OnOpen = () =>
                {;
                 Log.Insert(DateTime.Now, "Form1.cs", string.Format("Websocket connection open!"), "white");
                 allSockets.Add(socket); };
                socket.OnClose = () =>
                {
                    allSockets.Remove(socket);
                };
                socket.OnMessage = message =>
                {
                    // Send message back to websocket
                    Log.Insert(DateTime.Now, "Form1.cs", string.Format("socket.OnMessage. A message received from a client: {0}", message), "white");
                    //allSockets.ToList().ForEach(s => s.Send("Hello from websocket!"));

                    // Contract search. The same code as in searchContractDetails_Click button handler
                    ShowTab(contractInfoTab, contractDetailsPage);
                    Contract contract = GetConDetContract();                     // Read form fields
                    contract.Symbol   = message;
                    contractManager.RequestContractDetails(contract);
                };
            });


            // IB Client new instance
            ibClient = new IBClient(signal);

            // IB Variables declaraton
            // Other features can be added and connected
            orderManager    = new OrderManager(ibClient, liveOrdersGrid, tradeLogGrid);
            accountManager  = new AccountManager(ibClient, accountSelector, accSummaryGrid, accountValuesGrid, accountPortfolioGrid, positionsGrid);
            contractManager = new ContractManager(ibClient, fundamentalsOutput, contractDetailsGrid);             //ibClient, form tab, form tab. https://interactivebrokers.github.io/tws-api/contract_details.html#gsc.tab=0

            conDetRight.Items.AddRange(ContractRight.GetAll());
            conDetRight.SelectedIndex = 0;

            fundamentalsReportType.Items.AddRange(FundamentalsReport.GetAll());
            fundamentalsReportType.SelectedIndex = 0;

            this.groupMethod.DataSource    = AllocationGroupMethod.GetAsData();
            this.groupMethod.ValueMember   = "Value";
            this.groupMethod.DisplayMember = "Name";

            this.profileType.DataSource    = AllocationProfileType.GetAsData();
            this.profileType.ValueMember   = "Value";
            this.profileType.DisplayMember = "Name";

            hdRequest_EndTime.Text = DateTime.Now.ToString("yyyyMMdd HH:mm:ss");

            DateTime execFilterDefault = DateTime.Now.AddHours(-1);

            execFilterTime.Text = execFilterDefault.ToString("yyyyMMdd HH:mm:ss");

            // Events liniking
            // All events belong to EWrapper interface and called Public member functions
            ibClient.Error                  += ibClient_Error;
            ibClient.ConnectionClosed       += ibClient_ConnectionClosed;
            ibClient.CurrentTime            += time => addTextToBox("Current Time: " + time + "\n");
            ibClient.TickPrice              += ibClient_TickPrice;
            ibClient.TickSize               += ibClient_TickSize;
            ibClient.TickString             += (tickerId, tickType, value) => addTextToBox("Tick string. Ticker Id:" + tickerId + ", Type: " + TickType.getField(tickType) + ", Value: " + value + "\n");
            ibClient.TickGeneric            += (tickerId, field, value) => addTextToBox("Tick Generic. Ticker Id:" + tickerId + ", Field: " + TickType.getField(field) + ", Value: " + value + "\n");
            ibClient.TickEFP                += (tickerId, tickType, basisPoints, formattedBasisPoints, impliedFuture, holdDays, futureLastTradeDate, dividendImpact, dividendsToLastTradeDate) => addTextToBox("TickEFP. " + tickerId + ", Type: " + tickType + ", BasisPoints: " + basisPoints + ", FormattedBasisPoints: " + formattedBasisPoints + ", ImpliedFuture: " + impliedFuture + ", HoldDays: " + holdDays + ", FutureLastTradeDate: " + futureLastTradeDate + ", DividendImpact: " + dividendImpact + ", DividendsToLastTradeDate: " + dividendsToLastTradeDate + "\n");
            ibClient.TickSnapshotEnd        += tickerId => addTextToBox("TickSnapshotEnd: " + tickerId + "\n");
            ibClient.NextValidId            += ibClient_NextValidId;  // Receives next valid order id. Will be invoked automatically upon successfull API client connection. Used for sending connection status
            ibClient.DeltaNeutralValidation += (reqId, underComp) =>
                                               addTextToBox("DeltaNeutralValidation. " + reqId + ", ConId: " + underComp.ConId + ", Delta: " + underComp.Delta + ", Price: " + underComp.Price + "\n");

            // Accounts
            ibClient.ManagedAccounts += accountsList => HandleMessage(new ManagedAccountsMessage(accountsList));

            // Options
            ibClient.TickOptionCommunication += (tickerId, field, impliedVolatility, delta, optPrice, pvDividend, gamma, vega, theta, undPrice) =>
                                                HandleMessage(new TickOptionMessage(tickerId, field, impliedVolatility, delta, optPrice, pvDividend, gamma, vega, theta, undPrice));

            // Account info, portfolio
            ibClient.AccountSummary     += (reqId, account, tag, value, currency) => HandleMessage(new AccountSummaryMessage(reqId, account, tag, value, currency));
            ibClient.AccountSummaryEnd  += reqId => HandleMessage(new AccountSummaryEndMessage(reqId));
            ibClient.UpdateAccountValue += (key, value, currency, accountName) => HandleMessage(new AccountValueMessage(key, value, currency, accountName));
            ibClient.UpdatePortfolio    += (contract, position, marketPrice, marketValue, averageCost, unrealisedPNL, realisedPNL, accountName) =>
                                           HandleMessage(new UpdatePortfolioMessage(contract, position, marketPrice, marketValue, averageCost, unrealisedPNL, realisedPNL, accountName));
            ibClient.UpdateAccountTime  += timestamp => HandleMessage(new UpdateAccountTimeMessage(timestamp));
            ibClient.AccountDownloadEnd += account => HandleMessage(new AccountDownloadEndMessage(account));
            ibClient.OrderStatus        += (orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld) =>
                                           HandleMessage(new OrderStatusMessage(orderId, status, filled, remaining, avgFillPrice, permId, parentId, lastFillPrice, clientId, whyHeld));

            ibClient.OpenOrder    += (orderId, contract, order, orderState) => HandleMessage(new OpenOrderMessage(orderId, contract, order, orderState));
            ibClient.OpenOrderEnd += () => HandleMessage(new OpenOrderEndMessage());

            // Contracts, comission, fundamential data, historical data
            ibClient.ContractDetails    += (reqId, contractDetails) => HandleMessage(new ContractDetailsMessage(reqId, contractDetails));
            ibClient.ContractDetailsEnd += (reqId) => HandleMessage(new ContractDetailsEndMessage());
            ibClient.ExecDetails        += (reqId, contract, execution) => HandleMessage(new ExecutionMessage(reqId, contract, execution));
            ibClient.ExecDetailsEnd     += reqId => addTextToBox("ExecDetailsEnd. " + reqId + "\n");
            ibClient.CommissionReport   += commissionReport => HandleMessage(new CommissionMessage(commissionReport));
            ibClient.FundamentalData    += (reqId, data) => HandleMessage(new FundamentalsMessage(data));
            ibClient.HistoricalData     += (reqId, date, open, high, low, close, volume, count, WAP, hasGaps) =>
                                           HandleMessage(new HistoricalDataMessage(reqId, date, open, high, low, close, volume, count, WAP, hasGaps));
            ibClient.HistoricalDataEnd  += (reqId, startDate, endDate) => HandleMessage(new HistoricalDataEndMessage(reqId, startDate, endDate));
            ibClient.MarketDataType     += (reqId, marketDataType) => addTextToBox("MarketDataType. " + reqId + ", Type: " + marketDataType + "\n");
            ibClient.UpdateMktDepth     += (tickerId, position, operation, side, price, size) => HandleMessage(new DeepBookMessage(tickerId, position, operation, side, price, size, ""));
            ibClient.UpdateMktDepthL2   += (tickerId, position, marketMaker, operation, side, price, size) => HandleMessage(new DeepBookMessage(tickerId, position, operation, side, price, size, marketMaker));
            ibClient.UpdateNewsBulletin += (msgId, msgType, message, origExchange) =>
                                           addTextToBox("News Bulletins. " + msgId + " - Type: " + msgType + ", Message: " + message + ", Exchange of Origin: " + origExchange + "\n");

            // Positions
            ibClient.Position    += (account, contract, pos, avgCost) => HandleMessage(new PositionMessage(account, contract, pos, avgCost));
            ibClient.PositionEnd += () => addTextToBox("PositionEnd \n");

            // Bars, scanners
            ibClient.RealtimeBar       += (reqId, time, open, high, low, close, volume, WAP, count) => HandleMessage(new RealTimeBarMessage(reqId, time, open, high, low, close, volume, WAP, count));
            ibClient.ScannerParameters += xml => HandleMessage(new ScannerParametersMessage(xml));
            ibClient.ScannerData       += (reqId, rank, contractDetails, distance, benchmark, projection, legsStr) =>
                                          HandleMessage(new ScannerMessage(reqId, rank, contractDetails, distance, benchmark, projection, legsStr));
            ibClient.ScannerDataEnd          += reqId => addTextToBox("ScannerDataEnd. " + reqId + "\r\n");
            ibClient.ReceiveFA               += (faDataType, faXmlData) => HandleMessage(new AdvisorDataMessage(faDataType, faXmlData));
            ibClient.BondContractDetails     += (requestId, contractDetails) => addTextToBox("Receiving bond contract details.");
            ibClient.VerifyMessageAPI        += apiData => addTextToBox("verifyMessageAPI: " + apiData);
            ibClient.VerifyCompleted         += (isSuccessful, errorText) => addTextToBox("verifyCompleted. IsSuccessfule: " + isSuccessful + " - Error: " + errorText);
            ibClient.VerifyAndAuthMessageAPI += (apiData, xyzChallenge) => addTextToBox("verifyAndAuthMessageAPI: " + apiData + " " + xyzChallenge);
            ibClient.VerifyAndAuthCompleted  += (isSuccessful, errorText) => addTextToBox("verifyAndAuthCompleted. IsSuccessfule: " + isSuccessful + " - Error: " + errorText);
            ibClient.DisplayGroupList        += (reqId, groups) => addTextToBox("DisplayGroupList. Request: " + reqId + ", Groups" + groups);
            ibClient.DisplayGroupUpdated     += (reqId, contractInfo) => addTextToBox("displayGroupUpdated. Request: " + reqId + ", ContractInfo: " + contractInfo);

            // Multi positions
            ibClient.PositionMulti                        += (reqId, account, modelCode, contract, pos, avgCost) => HandleMessage(new PositionMultiMessage(reqId, account, modelCode, contract, pos, avgCost));
            ibClient.PositionMultiEnd                     += (reqId) => HandleMessage(new PositionMultiEndMessage(reqId));
            ibClient.AccountUpdateMulti                   += (reqId, account, modelCode, key, value, currency) => HandleMessage(new AccountUpdateMultiMessage(reqId, account, modelCode, key, value, currency));
            ibClient.AccountUpdateMultiEnd                += (reqId) => HandleMessage(new AccountUpdateMultiEndMessage(reqId));
            ibClient.SecurityDefinitionOptionParameter    += (reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes) => HandleMessage(new SecurityDefinitionOptionParameterMessage(reqId, exchange, underlyingConId, tradingClass, multiplier, expirations, strikes));
            ibClient.SecurityDefinitionOptionParameterEnd += (reqId) => HandleMessage(new SecurityDefinitionOptionParameterEndMessage(reqId));

            // Soft dollar tires
            ibClient.SoftDollarTiers += (reqId, tiers) => HandleMessage(new SoftDollarTiersMessage(reqId, tiers));
        }
 public MarketDataManager(IBClient client, DataGridView dataGrid) : base(client, dataGrid)
 {
 }
        public bool Disconnect()
        {
            if (client != null)
            {
                client.Error -= client_Error;
                client.TickPrice -= client_TickPrice;
                client.TickSize -= client_TickSize;
                client.UpdateAccountValue -= client_UpdateAccountValue;
                client.UpdatePortfolio -= client_UpdatePortfolio;
                client.OrderStatus -= client_OrderStatus;
                client.ExecDetails -= client_ExecDetails;
                client.NextValidId -= client_NextValidId;
                client.CurrentTime -= client_CurrentTime;

                client.Disconnect();
            }
            client = null;

            lock (_lockObject)
            {
                watchedSymbols.Clear();
                _watching = false;

                if (!_connected)
                {
                    lastError = "Not connected.";
                    hadError = true;
                    return false;
                }
                _connected = false;
                ClearError();
                return true;
            }
        }
        public bool Connect(ServiceConnectOptions connectOptions)
        {
            ClearError();

            if (_connected)
                return true;

            foreach (Symbol symbol in new List<Symbol>(watchedSymbols.Keys))
            {
                watchedSymbols[symbol] = null;
            }

            if (client == null)
            {
                client = new IBClient();
                client.ThrowExceptions = true;

                client.Error += client_Error;
                client.TickPrice += client_TickPrice;
                client.TickSize += client_TickSize;
                client.UpdateAccountValue += client_UpdateAccountValue;
                client.UpdatePortfolio += client_UpdatePortfolio;
                client.OrderStatus += client_OrderStatus;
                client.ExecDetails += client_ExecDetails;
                client.NextValidId += client_NextValidId;
                client.CurrentTime += client_CurrentTime;
            }

            int clientID = -1;
            bool brokerConnect = ((connectOptions & ServiceConnectOptions.Broker) == ServiceConnectOptions.Broker);

            if ((connectOptions & ServiceConnectOptions.Broker) == ServiceConnectOptions.Broker)
            {
                clientID = _clientIDBroker;
            }
            else if ((connectOptions & ServiceConnectOptions.LiveData) == ServiceConnectOptions.LiveData)
            {
                clientID = _clientIDLiveData;
            }
            else if ((connectOptions & ServiceConnectOptions.HistoricalData) == ServiceConnectOptions.HistoricalData)
            {
                clientID = _clientIDHist;
            }
            if (clientID < 0)
            {
                clientID = new Random().Next();
            }

            client.Connect(string.IsNullOrEmpty(ServerAddress) ? "127.0.0.1" : ServerAddress, (Port == 0) ? 7496 : Port, clientID);
            lock (_lockObject)
            {
                _connected = true;
            }
            if (brokerConnect)
            {
                lock (_lockObject)
                {
                    _connectWaitHandle = new ManualResetEvent(false);
                    _gettingReconnectData = true;
                    _hadError1102 = false;
                    foreach (string id in openOrders.Keys)
                    {
                        _potentiallyCancelledOrders[id] = null;
                    }
                }

                client.RequestAccountUpdates(true, accountCode);
                //client.ReqAllOpenOrders();
                client.RequestOpenOrders();

                ExecutionFilter filter = new ExecutionFilter();
                filter.ClientId = clientID;
                filter.Side = ActionSide.Buy;
                client.RequestExecutions(nextID++, filter);
                filter.Side = ActionSide.Sell;
                client.RequestExecutions(nextID++, filter);

                //	Request the current time so that when we get it, we know that (hopefully)
                //	we have gotten all the results from ReqOpenOrders and ReqExecutions
                client.RequestCurrentTime();

                if (!_connectWaitHandle.WaitOne(TimeSpan.FromSeconds(10.0), true))
                {
                    string msg = "Timed out waiting for TWS order and execution data to finish.";
                    Trace.WriteLine(msg);
                    Console.WriteLine(msg);
                }

                if (_potentiallyCancelledOrders.Count > 0)
                {
                    //	Wait a bit longer to check for errorCode 1102
                    Thread.Sleep(500);
                }

                lock (_lockObject)
                {

                    _gettingReconnectData = false;

                    if (!_hadError1102)
                    {
                        foreach (string orderID in _potentiallyCancelledOrders.Keys)
                        {
                            BrokerOrder order;

                            if (openOrders.TryGetValue(orderID, out order))
                            {
                                order.OrderState = BrokerOrderState.Cancelled;
                                OrderUpdatedDelegate tmp = OrderUpdated;
                                if (tmp != null)
                                {
                                    tmp(order, null, "Order cancelled while disconnected.");
                                }
                                openOrders.Remove(orderID);
                            }
                            else
                            {
                                int b = 0;
                            }
                        }
                    }
                    _potentiallyCancelledOrders.Clear();
                }
            }

            return true;
        }