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 #2
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();
        }
        /// <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 #5
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 #6
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 #8
0
        public AddInstrumentIbViewModel(IDialogCoordinator 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")
            .Subscribe(e => _logger.Warn("IB Instrument Adder connection closed."));

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

            Observable
            .FromEventPattern <ErrorEventArgs>(_client, "Error")
            .Subscribe(e =>
            {
                if (e.EventArgs.ErrorMsg != "No security definition has been found for the request")
                {
                    _logger.Error($"{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.Include(x => x.Sessions))
                {
                    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 #9
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);
            }
        }
        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 on port 7496..." + "(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);

            /////////// 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(s, item, 10);
                //client.RequestContractDetails(s, item);
                //client.RequestFundamentalData(s, item, "Estimates");
                //client.RequestFundamentalData(s, item, "Financial Statements");
                //client.RequestFundamentalData(s, item, "Summary");
                //client.RequestNewsBulletins(false);

                listToEcho += ", " + name;
            }
            logger.Debug("Symbols: {0}", listToEcho);
            //(NowString() + ": Symbols: " + listToEcho).Log();
        }
Exemple #11
0
        /// <summary>
        /// Arguments are GOOG/IB, rundate, basketfile, datapath
        /// </summary>
        static void Main(string[] args)
        {
            #region parameters
            string  _client = "IB";         // IB or GOOG
            IClient _iclient;
            string  _enddate    = DateTime.Today.ToString("yyyyMMdd");
            string  _basketfile = @"c:\QuantTrading\Config\basket.xml";
            string  _datapath   = @"c:\QuantTrading\HistData\";
            Basket  _basket;

            if (args.Length > 0)
            {
                _client = args[0];
            }
            if (args.Length > 1)
            {
                _enddate = args[1];
            }
            if (args.Length > 2)
            {
                _basketfile = args[2];
            }
            if (args.Length > 3)
            {
                _datapath = args[3];
            }
            _datapath = _datapath + _client + @"\";

            _basket = Basket.DeserializeFromXML(_basketfile);
            #endregion

            _sec2bars = new Dictionary <string, List <string> >(_basket.Count);
            Dictionary <string, string> _outfiles  = new Dictionary <string, string>(_basket.Count);
            Dictionary <string, long>   _totalBars = new Dictionary <string, long>(_basket.Count);
            _processedBars = new Dictionary <string, long>(_basket.Count);

            DateTime _startTime = DateTime.SpecifyKind(DateTime.ParseExact(_enddate, "yyyyMMdd", null), DateTimeKind.Local);
            DateTime _endTime   = _startTime + new TimeSpan(1, 0, 0, 0);      // one day later
            double   sec        = _endTime.Subtract(_startTime).TotalSeconds; // should be 24 hours or 86,400 secs

            foreach (string s in _basket.Securities)
            {
                // set up bar counts
                _totalBars.Add(s, (long)sec);                       // one bar is one sec; if one minute, divide it by 60
                _processedBars.Add(s, 0);                           // initialize processed to 0

                // set up out filenames
                string filename = _datapath + s + "_" + _startTime.Date.ToString("yyyyMMdd") + ".csv";
                _outfiles.Add(s, filename);
                List <string> lines = new List <string>(90000);           // set something greater than 86,4000
                lines.Add("DateTime,Open,High,Low,Close,Volume");
                _sec2bars.Add(s, lines);
            }

            if (_client == "IB")
            {
                _iclient = new IBClient();          // currently it uses default ip:port
                _iclient.SendDebugEventDelegate   += _iclient_SendDebugEventDelegate;
                _iclient.GotHistoricalBarDelegate += _iclient_GotHistoricalBarDelegate;
                _iclient.Connect();

                long     totalRequests = (long)sec / 1800;       // one request is 30 min, totalRequests = 48
                TimeSpan thirtyMin     = new TimeSpan(0, 30, 0);

                foreach (string sym in _basket.Securities)
                {
                    DateTime s = _startTime;
                    DateTime t = _startTime + thirtyMin;

                    Console.WriteLine("Requesting historical bars for :" + sym);
                    for (int i = 0; i < totalRequests; i++)
                    {
                        Console.WriteLine("Request #: " + (i + 1).ToString() + "/" + totalRequests);
                        // 1 = 1 second
                        BarRequest br = new BarRequest(sym, 1, Util.ToIntDate(s.Date), Util.ToIntTime(s.Hour, s.Minute, s.Second),
                                                       Util.ToIntDate(t.Date), Util.ToIntTime(t.Hour, t.Minute, t.Second), _client);
                        _iclient.RequestHistoricalData(br, true);

                        // Do not make more than 60 historical data requests in any ten-minute period.
                        // If I have 10 names, each can only make 6 requests in ten minute;
                        // I use 5 minute for a pause; Then 24 hours takes 120 min or 1.5hour
                        // Thread.Sleep(new TimeSpan(0, 5, 0));
                        // wait 10 secs
                        Thread.Sleep(10000);
                        s += thirtyMin;
                        t += thirtyMin;
                    }
                }
            }
            else if (_client == "GOOG")
            {
                _iclient = new GoogleClient(1);
                _iclient.SendDebugEventDelegate   += _iclient_SendDebugEventDelegate;
                _iclient.GotHistoricalBarDelegate += _iclient_GotHistoricalBarDelegate;

                foreach (string sym in _basket.Securities)
                {
                    Console.WriteLine("Requesting historical bars for :" + sym);
                    BarRequest br = new BarRequest(sym, 60, Util.ToIntDate(DateTime.Today), Util.ToIntTime(DateTime.Today),
                                                   Util.ToIntDate(DateTime.Today), Util.ToIntTime(DateTime.Today), _client);
                    _iclient.RequestHistoricalData(br);
                }
            }

            // write to files
            Console.WriteLine("Wait three minutes for bars being processed.....");
            Thread.Sleep(new TimeSpan(0, 3, 0));            // wait three minutes for all hist bar to be processed.

            foreach (string s in _basket.Securities)
            {
                List <string> noDups = _sec2bars[s].Distinct().ToList();
                //_sec2bars[s].Insert(0, _processedBars[s].ToString());
                File.WriteAllLines(_outfiles[s], noDups);
            }
        }
Exemple #12
0
        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");
            ZF      = 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");

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

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

            Order BuyContract = new Order();

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

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

            client.RequestAllOpenOrders();

            while (true)
            {
                Thread.Sleep(100);
            }
        }
Exemple #13
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);
            }
        }
        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 void SetUp()
 {
     _client = IBClientFactory.CreateNew();
     _client.Connect("127.0.0.1", 4002, 2);
 }
Exemple #16
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);
            }
        }
Exemple #17
0
        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;
            client.HistoricalData    += client_HistoricalData;

            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", "201609");
            //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", "201609");
            //ZT = new Contract("ZT", "ECBOT", SecurityType.Future, "USD", "200909");
            //ZF = new Contract("ZF", "ECBOT", SecurityType.Future, "USD", "200909");
            var dbk = new Contract();

            dbk.ContractId = 14121;
            dbk.Exchange   = "IBIS";
            //var dbk = new Contract("DBK", "IBIS", SecurityType.Stock, "EUR");
            client.RequestHistoricalData(1, ES, DateTime.Today.AddDays(1), "5 D", BarSize.OneDay, HistoricalDataType.Trades, 0);
            //var eurusd = new Contract();
            //eurusd.ContractId = 12087792;
            //eurusd.Exchange = "IDEALPRO";
            //var eurusd = new Contract("EUR", "IDEALPRO", SecurityType.Cash, "USD");
            //client.RequestRealTimeBars(1, eurusd, 5, RealTimeBarType.Midpoint, true);
            //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");

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

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

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

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

            //client.RequestAllOpenOrders();

            while (true)
            {
                Thread.Sleep(100);
            }
        }
        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 #19
0
        public Instrument(String m_Symbol, String m_Expiry, InstrumentType m_Type)
        {
            this.CreateHandle();
            this.Visible = false;

            if (m_Client == null)
            {
                m_Client = new IBClient();
                m_Client.ThrowExceptions = true;
                m_Client.TickPrice      += new EventHandler <TickPriceEventArgs>(S_OnPriceDataUpdate);
                m_Client.TickSize       += new EventHandler <TickSizeEventArgs>(S_OnSizeDataUpdate);
                m_Client.Error          += new EventHandler <ErrorEventArgs>(S_OnError);
                m_Client.NextValidId    += new EventHandler <NextValidIdEventArgs>(S_OnNextValidId);
                //m_Client.OrderStatus += new EventHandler< OrderStatusEventArgs >( OnOrderStatus);
                m_Client.ExecDetails += new EventHandler <ExecDetailsEventArgs>(S_OnFill);

                m_Client.HistoricalData += new EventHandler <HistoricalDataEventArgs>(OnHistoricalDataUpdate);

                m_Client.Connect("127.0.0.1", 7496, 0);

                contracts = new Dictionary <int, Instrument>();
            }

            m_ID = id;
            id++;

            Symbol = m_Symbol;

            switch (m_Type)
            {
            case InstrumentType.EQUITY:
                m_Contract = new Equity(m_Symbol);
                break;

            case InstrumentType.FOREX:
                //m_Contract = new Forex();
                break;

            case InstrumentType.FUTURE:
                m_Contract = new Future(m_Symbol, "GLOBEX", m_Expiry);
                break;

            //case InstrumentType.FUTURE:
            //    m_Contract = new Future( "CCK2", "NYBOT", "JUN12" );
            //    break;

            case InstrumentType.INDEX:
                m_Contract = new Index(m_Symbol, "CBOE");
                break;

            case InstrumentType.OPTION:
                m_Contract = new Option("IBM", "IBM   120518C00170000", 2012, 5, Krs.Ats.IBNet.RightType.Call, 170);
                break;
            }
            ;

            m_Client.RequestMarketData(m_ID, m_Contract, null, false, false);
            contracts.Add(m_ID, this);

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

            ///////////////////////////////////////////////////////////////////
            ////////////  These delegates perform cross-thread operation ///////
            ////////////////////////////////////////////////////////////////////
            OnPriceUpdateDelegate = new PriceUpdateEventHandler(Client_TickPrice);
            OnSizeUpdateDelegate  = new SizeUpdateEventHandler(Client_TickSize);
            OnFillUpdateDelegate  = new FillUpdateEventHandler(Client_Fill);
            ////////////////////////////////////////////////////////////////////
        }