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); */ }
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 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); }
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.")); } }
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); }
/// <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(); } }
//######################################################## // 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(); }
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(); } }
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")); }
// 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 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."); }
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 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; }
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 StartLoopProcess(string host, int port, int clientId, CancellationToken token) { try { logger.LogDebug("Starting connection TWS..."); foreach (var contract in option.Mapping) { subscription.AddSymbol(contract.Key, contract.Value); } var wrapper = new EWrapperImpl(subscription, queue, state, loggerFactory); logger.LogDebug("Connecting to {0}:{1} ...", option.Host, option.Port); wrapper.ClientSocket.eConnect(host, port, clientId); while (!wrapper.ClientSocket.IsConnected() && !token.IsCancellationRequested) { logger.LogDebug("Waiting connection to {0}:{1}", option.Host, option.Port); Thread.Sleep(TimeSpan.FromSeconds(1)); } logger.LogInformation("Successfully connected to {0}:{1} ...", option.Host, option.Port); var reader = new EReader(wrapper.ClientSocket, wrapper.signal); reader.Start(); Task.Run(() => StartSubscribeProcess(wrapper, token)); StartLoopProcessMsgs(wrapper, reader, token); logger.LogDebug("Disconnecting to TWS {0}:{1}", option.Host, option.Port); wrapper.ClientSocket.eDisconnect(); wrapper.ClientSocket.Close(); logger.LogInformation("Successfully disconnected {0}:{1} ...", option.Host, option.Port); } catch (Exception e) { logger.LogError("TwsProducer.StartLoopProcess error: {0}:{1}", e.GetType().Name, e.Message); return; } finally { subscription.ClearSymbols(); } }
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")); } }
void mReader_ReaderResponse(EReader.Response EResponse) { this.Invoke(new dlProcessResponse(ProcessReaderResponse), new object[] { EResponse }); }
/// <summary> /// Determina el estado de la lectora y coloca un icono verde o rojo que muestra el estado detectado /// </summary> private void ConectarLectora() { try { //Get an array of connected readers int[] iReaders = Utility.GetConnectedReaders(); if (iReaders.Length > 0) { //Now we found reader so lets connect it. if (iReaders.Length > 1) { //We have multiple reader connected to system. //Handle this properly } else { //Create instance of the object mReader = new EReader(); //Open virtula serial port reader is connected to. mReader.Open(iReaders[0]); //Now add reader response event handler mReader.ReaderResponse += new dlReaderResponse(mReader_ReaderResponse); this.pictureLectora.Image = RFIDEnturnador.Properties.Resources.Ball_green_32; } } else { this.pictureLectora.Image = RFIDEnturnador.Properties.Resources.Ball_red_32; } } catch (Exception ex) { MessageBox.Show("Ocurrió un error al conectarse a la lectora, por favor intente de nuevo", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); string inner = ""; if (ex.InnerException != null) inner = ex.InnerException.Message; this.objUtil.LogError("Camiones", "LeerArchivo", ex.Message, inner, CGlobal.IdUsuario); } }
/// <summary> /// Manejador del evento de la respuesta de la lectora /// </summary> /// <param name="EResponse"></param> void ProcessReaderResponse(EReader.Response EResponse) { try { //Now when reader response is MSG_OK we will process command. //MSG_OK means reader received command successfully and command was executed successfully. //It doesn't mean reader was able to read tag (in case of ReadTag() command). //It is just indicator of reader tried to read tag successfully. //But if we have message other than MSG_OK, it indicates failure. if (EResponse.ResponseCode == EReader.CommandCode.MSGOK) { //Now parse response as we need //Now most of the command like write tag, write tag memory, set hardware information //just needs confirmation of successfull execution so MSG_OK response indicates success for such commands. //Where as other commands like read tag, read tag memory, get hardware information, get firmware version //response comes back with some kind of data in response to issued command. //For such cases each command has different kind of response, so we need different way to parse it. //We have made this easy for developer by using response class for each specific command. //Here you will see how to use it. //We know the respone is MSG_OK (inside if ) so we can check for command specific response. //Here we have illustrated few commands. You can add more response as you need switch (EResponse.CommandEcho) { case EReader.Command.GET_FIRMWARE_VERSION: //If response is not null then if (EResponse.CommandSpecificResponse != null) { //Now we want to parse specific response as per GET_FIRMWARE_VERSION command //No problem EReader.FirmwareResponse specificRes = (EReader.FirmwareResponse)EResponse.CommandSpecificResponse; //This is easy //Now you can process values easily Try yourself by typing specificRes. //specificRes.MinorVersion } break; case EReader.Command.READ_TAG: //If response is not null then if (EResponse.CommandSpecificResponse != null) { EReader.ReadTagResponse specificRes = (EReader.ReadTagResponse)EResponse.CommandSpecificResponse; //This is easy //Now for the case of read_tag command we have to see if we were able to find any tag or not before we can look for tag value if (specificRes.Decode == EReader.ReadTagResponse.TagDecode.GOOD_TAG) { //Hurreyy..we found good tag now we can use tag value for business logic. byte[] bTagData = specificRes.TagData; //Get tag data as an array string sTagData = Utility.ToHex(specificRes.TagData);//convert tag data as string of Hex string tag = Utility.ByteToString(bTagData); tag.TrimStart(); tag = tag.Replace("\0", ""); //MessageBox.Show(this, "Hexa: " + sTagData + "\n" + "Barcode: " + tag, "Lectura", MessageBoxButtons.OK); this.txtCodigoRFID.Text = sTagData; } else { //MessageBox.Show("no tag found. Display proper message"); //no tag found. Display proper message. } } break; case EReader.Command.READ_TAG_MEMORY: //As per previous examples if (EResponse.CommandSpecificResponse != null) { EReader.ReadTagMemoryResponse specificRes = (EReader.ReadTagMemoryResponse)EResponse.CommandSpecificResponse; //This is easy //Now for the case of read_tag command we have to see if we were able to find any tag or not before we can look for tag value if (specificRes.Decode == EReader.ReadTagMemoryResponse.TagDecode.GOOD_TAG) { //Hurreyy..we found good tag now we can use tag value for business logic. byte[] bTagData = specificRes.TagData; //Get tag data as an array string sTagData = Utility.ToHex(specificRes.TagData);//convert tag data as string of Hex } else { //no tag found. Display proper message. } } break; } } else { //Print error message only in debugging mode MessageBox.Show("Intente la operación nuevamente", "Error", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception ex) { //Se guarda log del error MessageBox.Show("Ocurrió un error durante la operación d electura", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); string inner = ""; if (ex.InnerException != null) inner = ex.InnerException.Message; this.objUtil.LogError("Camiones", "ProcessReaderResponse", ex.Message, inner, CGlobal.IdUsuario); } }