private void connectToTWS() { logMessage("Connecting to TWS"); setConnectionState(ConnectionState.Connecting); // this ensures the state changes are visible: otherwise the synchronous connection mechanism // blocks them until it's finished ConnectionPanel.Refresh(); mApi.eConnect(ServerTextBox.Text, int.Parse(PortTextBox.Text), int.Parse(ClientIdTextBox.Text), false); // the following causes the IB API to start processing messages // received From TWS Task task = new Task((Action)(() => { EReader ereader = new EReader(mApi, mSignal); ereader.Start(); while (mApi.IsConnected()) { mSignal.waitForSignal(); ereader.processMsgs(); } }), TaskCreationOptions.LongRunning); if (mApi.ServerVersion > 0) { task.Start(); } }
// Conenction to the server private void ConnectionToTheServer() { // Connection singleWrapper.ClientSocket.eConnect(connectionHost, connectionPort, dataHandlerID); // Set up the form object in the EWrapper to send Back the Signals //singleWrapper.myform = (MainForm)Application.OpenForms[0]; // ATTENTION!!!! The rest of the method was copied, I have little understanding of the workings, so don't touch as long as it works!!! //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(singleWrapper.ClientSocket, singleWrapper.Signal); reader.Start(); //Once the messages are in the queue, an additional thread need to fetch them new Thread(() => { while (singleWrapper.ClientSocket.IsConnected()) { singleWrapper.Signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); /*************************************************************************************************************************************************/ /* 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 (singleWrapper.NextOrderId <= 0) { } }
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); }
public InteractiveBrokerTradingClient(string accountName) { _accountName = accountName; ibClient = new EWrapperImpl(); ibClient.ClientSocket.eConnect("127.0.0.1", 7497, 0); var reader = new EReader(ibClient.ClientSocket, ibClient.Signal); reader.Start(); new Thread(() => { while (ibClient.ClientSocket.IsConnected()) { ibClient.Signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); ibClient.ClientSocket.reqIds(-1); /* * var contract = new Contract() * { * ConId = 0, Symbol = "MSFT", SecType = "STK", * Exchange = "SMART", Currency = "USD", LocalSymbol = "MSFT" * }; * * List<TagValue> mktDataOptions = new List<TagValue>(); * * * ibClient.ClientSocket.reqMktData(10, contract, "", false, false, mktDataOptions); */ }
internal void Connect() { if (!IsConnected) { try { HandleErrorMessage(new ErrorMessage(-1, -1, "Connecting...")); responder = new Responder(); clientSocket = responder.ClientSocket; EReaderSignal readerSignal = responder.Signal; clientSocket.eConnect(gatewayCredentials.Host, gatewayCredentials.Port, gatewayCredentials.ClientId); EReader reader = new EReader(clientSocket, readerSignal); reader.Start(); new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); int counter = 0; while (responder.NextOrderId <= 0) { counter++; Thread.Sleep(1000); if (counter > 10) { HandleErrorMessage(new ErrorMessage(-1, -1, "Failure to Connect.")); IsConnected = false; return; } } NextOrderNo = responder.NextOrderId; IsConnected = true; HandleErrorMessage(new ErrorMessage(-1, -1, "Connected.")); } catch (Exception) { HandleErrorMessage(new ErrorMessage(-1, -1, "Please check your connection attributes.")); } } else { IsConnected = false; HandleErrorMessage(new ErrorMessage(-1, -1, "Disconnected.")); } }
public void Connect(string clientUrl, int clientPort) { clientSocket.eConnect(clientUrl, clientPort, ClientId); // Create a reader to consume incoming messages // and store them in a queue. var reader = new EReader(clientSocket, readerSignal); reader.Start(); // Once the messages are in the queue, an additional thread is needed to process them. // This is best accomplished by a dedicated long-running background thread. Task.Factory.StartNew(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); // It's worth noting that message processing is what raises all EWrapper events, // e.g. NextValidId, TickPrice, Position, PositionEnd, Error, ConnectionClosed, etc. // Events are handled by the thread that raises them, i.e. this thread! reader.processMsgs(); } }, TaskCreationOptions.LongRunning); }
//######################################################## // Initialization and Settings //######################################################## #region Initialization public IntBrokerSocket(int _clientId, int _connectionPort) { clientId = _clientId; testImpl = new EWrapperImpl(); clientSocket = testImpl.ClientSocket; connectionPort = _connectionPort; // Request permission to connect //if (connectionPort == Control.LiveTradingPort) //{ // Console.Write("You are connecting to the live trading account. Do you want to continue ? (Y/N)"); // if (Console.ReadLine().ToUpper() == "N") // { // Environment.Exit(0); // } //} // Connect to TWS clientSocket.eConnect("127.0.0.1", connectionPort, clientId); var reader = new EReader(clientSocket, testImpl.signal); reader.Start(); new Thread(() => { while (clientSocket.IsConnected()) { testImpl.signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); }
/// <summary> /// Open local connection to TWS /// </summary> public static void Connect() { // Connection method per the TWS example application try { // Open a connection to TWS ibclient.ClientId = 0; // Connection on the local machine ibclient.ClientSocket.eConnect("127.0.0.1", 7497, 0); // Start an IB reader thread var reader = new EReader(ibclient.ClientSocket, signal); reader.Start(); // background thread to process TWS messages and pass them back to the reader. new Thread(() => { while (ibclient.ClientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } catch (Exception) { // TODO: Not quite sure when we get here. May need to add hierarchy FSM as these could possibly occur in any state. throw new NotImplementedException(); } }
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); }
public void ConnectToIB(int port, int clientId) { ClientSocket.eConnect("", port, clientId); var reader = new EReader(ClientSocket, Signal); reader.Start(); new Thread(() => { while (ClientSocket.IsConnected()) { Signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); // Pause here until the connection is complete while (NextOrderId <= 0) { } }
/// <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(); } }
/* IMPORTANT: always use your paper trading account. The code below will submit orders as part of the demonstration. */ /* IB will not be responsible for accidental executions on your live account. */ /* Any stock or option symbols displayed are for illustrative purposes only and are not intended to portray a recommendation. */ /* Before contacting our API support team please refer to the available documentation. */ public static int Main(string[] args) { EWrapperImpl testImpl = new EWrapperImpl(); EClientSocket clientSocket = testImpl.ClientSocket; EReaderSignal readerSignal = testImpl.Signal; //! [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 need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); int tickerId = 100; clientSocket.reqMarketDataType(2); getStockPrice(clientSocket, "AAPL", tickerId); Thread.Sleep(300000); Console.WriteLine("Disconnecting..."); clientSocket.eDisconnect(); return(0); }
/// <summary> /// Connects to the IB machine /// </summary> private void Connect() { EReaderSignal readerSignal = ibClient.Signal; EClientSocket clientSocket = ibClient.ClientSocket; clientSocket.eConnect("127.0.0.1", 7496, 3); //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 need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); /*************************************************************************************************************************************************/ /* 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 (ibClient.NextOrderId <= 0) { } Log.Info(2, string.Format("Exiting Connect")); }
private void btnConnect_Click(object sender, EventArgs e) { if (!IsConnected) { try { this.ibClient.ClientSocket.eConnect("127.0.0.1", ServerPort, 99); var reader = new EReader(this.ibClient.ClientSocket, signal); reader.Start(); new Thread(() => { while (this.ibClient.ClientSocket.IsConnected()) { this.signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); tbConnect.Text = ibClient.ClientSocket.ServerTime; ibClient.ClientSocket.reqCurrentTime(); ibClient.ClientSocket.reqIds(-1); } catch (Exception ex) { tbConnect.Text = ex.ToString(); } } }
/* IMPORTANT: always use your paper trading account. The code below will submit orders as part of the demonstration. */ /* IB will not be responsible for accidental executions on your live account. */ /* Any stock or option symbols displayed are for illustrative purposes only and are not intended to portray a recommendation. */ /* Before contacting our API support team please refer to the available documentation. */ public static int Main(string[] args) { EWrapperImpl testImpl = new EWrapperImpl(); EClientSocket clientSocket = testImpl.ClientSocket; EReaderSignal readerSignal = testImpl.Signal; //! [connect] clientSocket.eConnect("127.0.0.1", 7496, 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 need 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 (testImpl.NextOrderId <= 0) { } testIBMethods(clientSocket, testImpl.NextOrderId); Console.WriteLine("Disconnecting..."); clientSocket.eDisconnect(); return(0); }
public void Connect() { try { ibClient = new EWrapperImpl(); // subscribe to events triggered by wrapper, to update form ibClient.AccountValueUpdated += UpdateAccountValue; ibClient.TickPriceUpdated += UpdateTickPrice; ibClient.ErrorUpdated += UpdateError; ibClient.MarketRuleUpdated += UpdateMarketRule; ibClient.ContractDetailsUpdated += UpdateContractDetails; ibClient.ClientSocket.eConnect(iBGatewayClientConnectionData.Server, iBGatewayClientConnectionData.Port, iBGatewayClientConnectionData.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(); // Pause here until the connection is complete DateTime connectionTime = DateTime.Now; while (ibClient.NextOrderId <= 0) { if (DateTime.Now > connectionTime.AddSeconds(1)) { throw new Exception(strTimeOutMessage); } } orderNumber = ibClient.NextOrderId; frmMain.SetConnectionStatus(true); SubscribeAccount(ibClient, frmMain.AccountNumber()); } catch (Exception e) { if (e.Message == strTimeOutMessage) { frmMain.AddNotification("Connection timeout. Please check that IB Gateway or TWS is running."); return; } throw; } }
private void StartLoopProcessMsgs(EWrapperImpl wrapper, EReader reader, CancellationToken stoppingToken) { while (wrapper.ClientSocket.IsConnected() && !stoppingToken.IsCancellationRequested) { wrapper.signal.waitForSignal(); reader.processMsgs(); } subscription.SetNotRequestedForAllSymbols(); }
/// <summary> /// 连接到TWS /// </summary> /// <param name="IP_Address">TWS 客户端所在的IP地址</param> /// <param name="Port">端口号,默认为7496,模拟账号默认为7497</param> /// <returns>如果成功连接返回true,否则返回false</returns> public bool ConnectToTWS(string IP_Address, int Port) { if (IP_Address == Host && Port == this.Port && IsConnected()) { return(true); } else if (IsConnected()) { Disconnect(); } try { wrapper.ClientSocket.eConnect(IP_Address, Port, 0, false); EClientSocket clientSocket = wrapper.ClientSocket; EReaderSignal readerSignal = wrapper.Signal; //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 need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); while (wrapper.NextOrderId <= 0) { } new Thread(() => { while (clientSocket.IsConnected()) { clientSocket.reqPositions(); Thread.Sleep(500); } }) { IsBackground = true }.Start(); //wrapper.NextOrderId = 2000; OrderID = wrapper.NextOrderId; //IsConnected = true; this.Port = Port; this.Host = IP_Address; return(true); } catch (Exception exp) { Console.WriteLine(exp.Message.ToString()); return(false); } finally { } }
public void StartMessageProcessing() { reader = new EReader(clientSocket, signal); reader.Start(); messageProcessingTask = new Task(() => { while (clientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }); messageProcessingTask.Start(); }
public void connectAck() { try { if (Connected == clientSocket.IsConnected()) { return; } Connected = clientSocket.IsConnected(); if (!Connected) { return; } //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue EReader reader = new EReader(clientSocket, signal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { try { while (clientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } } catch (Exception ex) { Console.WriteLine($"Exception in reader thread: {ex.Message}"); throw ex; } }) { IsBackground = true }.Start(); } catch (Exception ex) { Log(new LogMessage(ToString(), ex.Message, LogMessageType.SystemError)); Console.WriteLine($"EXCEPTION:{GetCurrentMethod()} {ex.Message}"); return; } }
public void Connect(string username, string password, int port = 7497, string ip = "127.0.0.1") { Output.WriteLine("Connecting to TWS..."); int numTries = 0; do { numTries++; if (numTries > 1) { Output.WriteLine("Launching TWS..."); LaunchTWS(username, password, port); } ClientSocket.eConnect(ip, port, 0); if (ClientSocket.IsConnected()) { Output.WriteLine("Socket connected."); break; } } while (numTries <= 3); EReaderSignal readerSignal = Signal; var reader = new EReader(ClientSocket, readerSignal); reader.Start(); new Thread(() => { while (ClientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); while (NextOrderId <= 0) { // once we are connected, we will have an order id > 0 } Output.WriteLine("TWS API connected."); }
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"); } }
public void GetHistoricData() { logger.Info("Start GetHistoricData"); EWrapperImpl ibClient = new EWrapperImpl(); ibClient.ClientSocket.eConnect(iBGatewayClientConnectionData.Server, iBGatewayClientConnectionData.Port, iBGatewayClientConnectionData.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(); // Pause here until the connection is complete while (ibClient.NextOrderId <= 0) { } // Make historic data request HistoricDataRequestManager historicDataRequestManager = new HistoricDataRequestManager(ibClient.ClientSocket); historicDataRequestManager.GetHistoricDataRequestsFromDB(); historicDataRequestManager.MakeRequests(); // Keep console up Console.WriteLine("Press any key to quit..."); Console.ReadKey(); // end request historicDataRequestManager.EndRequests(); // Disconnect from TWS ibClient.ClientSocket.eDisconnect(); logger.Info("End GetHistoricData"); }
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; }
public EWrapperImpl() { signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); clientSocket.eConnect("127.0.0.1", 7496, 0); //Create a reader to consume messages from the TWS. The EReader will consume the incoming messages and put them in a queue reader = new EReader(clientSocket, signal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (clientSocket.IsConnected()) { signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); }
// 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"); } }
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")); } }
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(); }