public void Connect(string host, int port, int clientId, bool extraAuth = false) { if (IsConnected) { throw new Exception(String.Format("Code: {0}, Msg: {1}", EClientErrors.AlreadyConnected.Code, EClientErrors.AlreadyConnected.Message)); } tcpClient = new TcpClient(host, port); tcpClientStream = tcpClient.GetStream(); var tcpWriter = new BinaryWriter(tcpClientStream); IbWriter = new IbWriter(tcpWriter); IbReader = new IbReader(new BinaryReader(tcpClientStream)); ClientId = clientId; ExtraAuth = extraAuth; try { tcpWriter.Write(UTF8Encoding.UTF8.GetBytes(Constants.ClientVersion.ToString())); tcpWriter.Write(Constants.EOL); } catch (IOException e) { throw new IOException("Could not establish connection. Make sure the TWS is enabled to accept socket clients!", e); } // Receive the response from the remote device. ServerVersion = IbReader.ReadInt(); if (ServerVersion < MinServerVer.MIN_VERSION) { throw new Exception(String.Format("Code: {0}, Msg: {1}", EClientErrors.UPDATE_TWS.Code, EClientErrors.UPDATE_TWS.Message)); } if (ServerVersion >= 20) { string twsTime = IbReader.ReadString(); } IsConnected = true; if (ServerVersion >= 3) { if (ServerVersion < MinServerVer.LINKING) { tcpWriter.Write(UTF8Encoding.UTF8.GetBytes(clientId.ToString())); tcpWriter.Write(Constants.EOL); } else if (!extraAuth) { StartApi(); } } }
public void StartApi() { if (!IsConnected) { // todo: should an exception be thrown here? return; } const int VERSION = 1; List <byte> paramsList = new List <byte>(); paramsList.AddParameter(OutgoingMessages.StartApi); paramsList.AddParameter(VERSION); paramsList.AddParameter(ClientId); IbWriter.Send(paramsList); }