public void connectSync() { EReaderMonitorSignal signal_ = new EReaderMonitorSignal(); Wotan.client client_ = new Wotan.client(signal_, new dispatchDelegate((twsMessage m) => {}), new logDelegate((string m, logType l, verbosity v, int id) => { }), false); if (!client_.socket.IsConnected()) { client_.socket.eConnect("127.0.0.1", 4001, 0); EReader reader = new EReader(client_.socket, signal_); reader.Start(); new Thread(() => { while (client_.socket.IsConnected()) { signal_.waitForSignal(); reader.processMsgs(); } }) { Name = "reading thread", IsBackground = true }.Start(); Thread.Sleep(1000); client_.socket.eDisconnect(); } }
public void connectAsync() { bool result = false; EReaderMonitorSignal signal_ = new EReaderMonitorSignal(); Wotan.client client_ = null; EReader reader_ = null; client_ = new Wotan.client( signal_, new dispatchDelegate((twsMessage m) => { result = true; }), new logDelegate((string m, logType l, verbosity v, int id) => { }), true); reader_ = new EReader(client_.socket, signal_); reader_.Start(); client_.connectAck(); Thread.Sleep(1000); new Thread(() => { while (client_.socket.IsConnected()) { signal_.waitForSignal(); reader_.processMsgs(); } }) { Name = "reading thread", IsBackground = true }.Start(); Thread.Sleep(10000); }
/// <summary> /// Connect /// </summary> /// <param name="host"></param> /// <param name="portIb"></param> /// <param name="clientIdIb"></param> public void Connect(string host, int portIb, int clientIdIb) { if (!IsConnectedIb) { try { ClientSocket.eConnect(host, portIb, clientIdIb); var signal = new EReaderMonitorSignal(); var reader = new EReader(ClientSocket, signal); reader.Start(); new Thread(() => { while (ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } catch (Exception) { throw; } } else { IsConnectedIb = false; ClientSocket.eDisconnect(); } }
public bool Connect(string ip, int port, int clientID) { Log.Info("Connecting IB"); try { IBClient.ClientSocket.eConnect(ip, port, clientID); var reader = new EReader(IBClient.ClientSocket, signal); reader.Start(); new Thread(() => { while (IBClient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } catch (Exception ex) { Log.Error("Error on connect IB, message: " + ex.Message); Log.Error("Error on connect IB, StackTrace: " + ex.StackTrace); throw ex; } return(true); }
private void button13_Click(object sender, EventArgs e) // Api connect button click { if (!isConnected) // False on startup { try { ibClient.ClientId = 2; // Client id. Multiple clients can be connected to the same gateway with the same login/password ibClient.ClientSocket.eConnect("127.0.0.1", Settings.ibGateWayPort, ibClient.ClientId); //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(ibClient.ClientSocket, signal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (ibClient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); // https://interactivebrokers.github.io/tws-api/connection.html#gsc.tab=0 } catch (Exception exception) { ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Check your connection credentials. Exception: " + exception, "white"); } try { ibClient.ClientSocket.reqCurrentTime(); } catch (Exception exception) { ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "req time. Exception: " + exception, "white"); } } else { isConnected = false; ibClient.ClientSocket.eDisconnect(); status_CT.Text = "Disconnected"; button13.Text = "Connect"; ListViewLog.AddRecord(this, "brokerListBox", "Form1.cs", "Disconnecting..", "white"); } }
private void Connect_Click(object sender, RoutedEventArgs e) { if (!IsConnected) { try { //int port = Int32.Parse(Port.Text); string host = string.IsNullOrEmpty(Ip.Text) ? "127.0.0.1" : Ip.Text; IBClient.ClientSocket.eConnect(host, 7496, 0); var reader = new EReader(IBClient.ClientSocket, signal); reader.Start(); new Thread(() => { while (IBClient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); if (IBClient.ClientSocket.IsConnected()) { Connect.Content = "DisConnect"; status.Content = "Connected"; } } catch (Exception ex) { MessageBox.Show("请检查ip和port是否正确!"); } } else { IBClient.ClientSocket.eDisconnect(); Connect.Content = "Connected"; status.Content = "DisConnect"; } IsConnected = !IsConnected; }
private void connectButton_Click(object sender, EventArgs e) // Connect button { if (!IsConnected) { int port; string host = null; // this.host_CT.Text; if (host == null || host.Equals("")) { host = "127.0.0.1"; } try { port = 4002; // Int32.Parse(this.port_CT.Text); ibClient.ClientId = 2; // Int32.Parse(this.clientid_CT.Text); ibClient.ClientSocket.eConnect(host, port, ibClient.ClientId); var reader = new EReader(ibClient.ClientSocket, signal); reader.Start(); new Thread(() => { // Create object while (ibClient.ClientSocket.IsConnected()) // Params. Lambda expression { signal.waitForSignal(); reader.processMsgs(); } }) // Create { IsBackground = true }.Start(); // Start method call } catch (Exception) { HandleMessage(new ErrorMessage(-1, -1, "jopa Please check your connection attributes.")); } } else { IsConnected = false; ibClient.ClientSocket.eDisconnect(); // Fiers ibClient.ConnectionClose event } }
// Control events handlers. Button clicks etc. private void button1_Click(object sender, EventArgs e) // Connect button click { if (!IsConnected) // False on startup { HandleMessage(new ErrorMessage(0, 0, "Connect button clicked")); int port; string host = this.host_CT.Text; if (host == null || host.Equals("")) { host = "127.0.0.1"; } try { port = Int32.Parse(this.port_CT.Text); ibClient.ClientId = Int32.Parse(this.clientid_CT.Text); ibClient.ClientSocket.eConnect(host, port, ibClient.ClientId); // Connection var reader = new EReader(ibClient.ClientSocket, signal); // Put the websocket stream to the reader variable reader.Start(); new Thread(() => { while (ibClient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); // https://interactivebrokers.github.io/tws-api/connection.html#gsc.tab=0 } catch (Exception) { HandleMessage(new ErrorMessage(-1, -1, "Please check your connection attributes.")); } } else { IsConnected = false; ibClient.ClientSocket.eDisconnect(); HandleMessage(new ErrorMessage(0, 0, "Connect button clicked while connection establichet - disconnect")); } }
// Control events handlers. Button clicks etc. private void connect_Button(object sender, EventArgs e) // Connect button click { if (!IsConnected) // False on startup { ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "Connect button clicked", "white"); int port; string host = "127.0.0.1"; if (host == null || host.Equals("")) { host = "127.0.0.1"; } try { port = TfrSettingsJson.ibGateWayPort; // 7496 - TWS. 4002 - IB Gateway ibClient.ClientId = 1; ibClient.ClientSocket.eConnect(host, port, ibClient.ClientId); // Connection var reader = new EReader(ibClient.ClientSocket, signal); // Put the websocket stream to the reader variable reader.Start(); new Thread(() => { while (ibClient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); // https://interactivebrokers.github.io/tws-api/connection.html#gsc.tab=0 } catch (Exception) { ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "Please check your connection attributes", "white"); } } else { IsConnected = false; ibClient.ClientSocket.eDisconnect(); ListViewLogging.log_add(this, "parserListBox", "Form1.cs", "Connect button clicked while connection establichet - disconnect", "white"); } }
public override void connectAck() { //tws is connected but we should wait for nextValidId too Logger.Info("Received connect acknowledge from Interactive Brokers TWS Api"); this.IsTwsConnected = true; //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(Client, EReaderSignal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (Client.IsConnected()) { EReaderSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); }
public bool Connect() { lock (_connectLockObj) { if (!IsConnected) { int port; string host = _host; if (host == null || host.Equals("")) { host = "127.0.0.1"; } try { port = _port; _ibClient.ClientId = _clientId; _ibClient.ClientSocket.eConnect(host, port, _ibClient.ClientId); var reader = new EReader(_ibClient.ClientSocket, _signal); reader.Start(); EventWaitHandle wait = new ManualResetEvent(false); new Thread(() => { while (_ibClient.ClientSocket.IsConnected()) { _signal.waitForSignal(); reader.processMsgs(); wait.Set(); } }) { IsBackground = true }.Start(); wait.WaitOne(TIME_OUT_VALUE); } catch (Exception) { HandleErrorMessage(new ErrorMessage(-1, -1, "Please check your connection attributes.")); } } } return(IsConnected); }
public bool Connect() { try { string host = Framework.Settings.Get("IB_HOST", "localhost"); int port = Framework.Settings.Get("IB_PORT", 4001); #if DEBUG int clientId = Framework.Settings.Get("IB_CLIENTID", 1); #else int clientId = Framework.Settings.Get("IB_CLIENTID", 11); #endif this.Log("Connecting to IB gateway on {0}:{1}... (client_id={2})", host, port, clientId); _ibClient.ClientId = clientId; _ibClient.ClientSocket.eConnect(host, port, _ibClient.ClientId); var reader = new EReader(_ibClient.ClientSocket, _signal); reader.Start(); //process incoming tcp data new Thread(() => { while (_ibClient.ClientSocket.IsConnected()) { _signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); //startup and connect ran fine return(true); } catch (Exception ex) { throw ex; //HandleErrorMessage(new ErrorMessage(-1, -1, "Please check your connection attributes.")); return(false); } }
private void connectButton_Click(object sender, EventArgs e) { if (!IsConnected) { int port; string host = this.host_CT.Text; if (host == null || host.Equals("")) { host = "127.0.0.1"; } try { port = Int32.Parse(this.port_CT.Text); ibClient.ClientId = Int32.Parse(this.clientid_CT.Text); ibClient.ClientSocket.eConnect(host, port, ibClient.ClientId); var reader = new EReader(ibClient.ClientSocket, signal); reader.Start(); new Thread(() => { while (ibClient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } catch (Exception) { HandleMessage(new ErrorMessage(-1, -1, "Please check your connection attributes.")); } } else { IsConnected = false; ibClient.ClientSocket.eDisconnect(); } }
public void connect(string host, int port, int ClientID) { ibClient.ClientId = ClientID; ibClient.ClientSocket.eConnect(host, port, ClientID); var reader = new EReader(ibClient.ClientSocket, signal); reader.Start(); new Thread(() => { while (ibClient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); }
// connect private void connect(IPAddress host, int port) { if (!client_.socket.IsConnected()) { client_.socket.eConnect(host.ToString(), port, 1); reader_ = new EReader(client_.socket, signal_); reader_.Start(); new Thread(() => { while (client_.socket.IsConnected()) { signal_.waitForSignal(); reader_.processMsgs(); } }) { Name = "reading thread", IsBackground = true }.Start(); } }
public void Start() { //! [connect] _clientSocket.eConnect("127.0.0.1", 7497, 0); //! [connect] //! [ereader] //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue var reader = new EReader(_clientSocket, _readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (_clientSocket.IsConnected()) { _readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); //! [ereader] /*************************************************************************************************************************************************/ /* One (although primitive) way of knowing if we can proceed is by monitoring the order's nextValidId reception which comes down automatically after connecting. */ /*************************************************************************************************************************************************/ while (_nextOrderId <= 0) { } _tickerId = 1001; //! [futcontract] Contract contract = new Contract(); contract.Symbol = "MES"; contract.SecType = "FUT"; contract.Exchange = "GLOBEX"; contract.Currency = "USD"; contract.LastTradeDateOrContractMonth = "20200320"; _clientSocket.reqMktData(_tickerId, contract, "233", false, false, null); }
private void btnConnect_Click(object sender, EventArgs e) { if (!Connected) { try { int port = 7497; if (cbTradingEnvironment.SelectedItem.ToString() == "LIVE") { port = 7496; } Client.ClientId = 1; Client.ClientSocket.eConnect("127.0.0.1", port, Client.ClientId); var reader = new EReader(Client.ClientSocket, MessageMonitor); reader.Start(); new Thread(() => { while (Client.ClientSocket.IsConnected()) { MessageMonitor.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } catch (Exception) { HandleMessage(new ErrorMessage(-1, -1, "Please check your connection attributes.")); } } else { Shutdown(); } }
static void Main(string[] args) { int reqId = 0; Settings settings; try { settings = JsonConvert.DeserializeObject <Settings>(File.ReadAllText(@"settings.json")); } catch (Exception) { settings = new Settings(); File.WriteAllText(@"settings.json", JsonConvert.SerializeObject(settings, Formatting.Indented)); Console.WriteLine("Defaults have been saved to 'settings.json'"); Console.ReadKey(); return; } var cnx = new MySqlConnectionStringBuilder(); cnx.UserID = settings.username; cnx.Password = settings.password; cnx.Server = settings.server; cnx.Port = settings.port; MySqlTransaction tr = null; var mysql = new MySqlConnection(cnx.ToString()); mysql.Open(); // Create MySQL database and tables Create(mysql); Console.Write("Symbol: "); string symbol = Console.ReadLine(); Console.Write("Duration (days): "); int days = Convert.ToInt32(Console.ReadLine()); Console.Write("Retrieve ticks [y/n]: "); bool retrieveTicks = (Console.ReadLine() == "y"); Console.WriteLine(); DateTime end = DateTime.Now; DateTime start = end.AddDays(-days); var signal = new EReaderMonitorSignal(); var client = new IBClient(signal); client.ClientSocket.eConnect(settings.TWS, settings.TWSPort, settings.ClientID); var c = new Contract(); c.Currency = "USD"; if (symbol.StartsWith("@")) { c.Symbol = symbol.Replace("@", ""); c.SecType = "CONTFUT"; c.Exchange = FuturesExchange(symbol); } else { c.Symbol = symbol; c.Exchange = "SMART"; c.SecType = "STK"; c.PrimaryExch = "ISLAND"; // fixes ambiguity } var contracts = new List <ContractDetails>(); client.ContractDetails += (ContractDetailsMessage msg) => { contracts.Add(msg.ContractDetails); }; client.ContractDetailsEnd += (ContractDetailsEndMessage) => { if (contracts.Count == 0) { Console.WriteLine("No contracts found for {0}", symbol); } else { ContractDetails closest = null; foreach (var cd in contracts) { // No date (not futures) if (string.IsNullOrEmpty(cd.Contract.LastTradeDateOrContractMonth)) { closest = cd; break; } var dt1 = DateTime.ParseExact(cd.Contract.LastTradeDateOrContractMonth, "yyyyMMdd", CultureInfo.InvariantCulture); // Skip the contract if there's only 5 days left if ((dt1 - DateTime.Now).Days <= 5) { continue; } // Find the closest contract if (closest == null || dt1 < DateTime.ParseExact(closest.Contract.LastTradeDateOrContractMonth, "yyyyMMdd", CultureInfo.InvariantCulture)) { closest = cd; } } if (closest == null) { Console.WriteLine("Contract not found for {0}", symbol); } else { // Store the symbol Insert(mysql, symbol); // Transaction for bulk inserting tr = mysql.BeginTransaction(); c = closest.Contract; // Request candles client.ClientSocket.reqHistoricalData(reqId++, closest.Contract, end.ToString("yyyyMMdd HH:mm:ss"), string.Format("{0} D", days), "1 min", "TRADES", 0, 1, false, null); } } }; // Request contract data client.ClientSocket.reqContractDetails(reqId++, c); client.HistoricalData += (HistoricalDataMessage msg) => { Insert(mysql, tr, symbol, 60, msg); }; client.HistoricalDataEnd += (HistoricalDataEndMessage msg) => { // Commit data tr.Commit(); Console.WriteLine("Finished retrieving candles"); if (retrieveTicks) { // New transaction for ticks tr = mysql.BeginTransaction(); // Request ticks client.ClientSocket.reqHistoricalTicks(reqId++, c, null, end.ToString("yyyyMMdd HH:mm:ss"), 1000, "TRADES", 0, true, null); } }; client.historicalTickLast += (int req, HistoricalTickLast[] ticks, bool done) => { Insert(mysql, tr, symbol, ticks); if (done) { end = UnixTimeStampToDateTime(ticks[0].Time); if (end <= start) { // Commit data tr.Commit(); Console.WriteLine("Finished retrieving ticks"); } else { client.ClientSocket.reqHistoricalTicks(reqId++, c, null, end.ToString("yyyyMMdd HH:mm:ss"), 1000, "TRADES", 0, true, null); } } }; client.Error += (int id, int errorCode, string str, Exception ex) => { if (id != -1) { Console.WriteLine("{0} {1} {2} {3}", DateTime.Now, id, errorCode, str); } }; var reader = new EReader(client.ClientSocket, signal); reader.Start(); while (true) { signal.waitForSignal(); reader.processMsgs(); } }