//! [socket_init] public EWrapperImpl() { Signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, Signal); repository = new DL.BarRepository(); }
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 IbkrLiveTradingProvider(int port, int clientId) { Port = port; ClientId = clientId; signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); }
/* 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); }
public EClientSocket(EWrapper wrapper, EReaderSignal eReaderSignal) : base(wrapper) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; this.eReaderSignal = eReaderSignal; }
/// <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")); }
/* 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 EReader(EClientSocket clientSocket, EReaderSignal signal) { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; eClientSocket = clientSocket; eReaderSignal = signal; processMsgsDecoder = new EDecoder(eClientSocket.ServerVersion, eClientSocket.Wrapper, eClientSocket); }
public EWrapperImpl() { Signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, Signal); InitLog(); InitContracts(); }
public IbkrDataProvider(int port, int clientId) { Port = port; this.ClientId = clientId; signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); RequestTimer.Elapsed += RequestTimerTick; }
public IbkrLiveDataProvider(int port, int clientId) { Port = port; ClientId = clientId; signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); InitializeSnapshotTimer(); }
//! [socket_declare] //! [socket_init] public EWrapperImpl(SubscriptionDictionary subscription, IBackground <Quote> queue, IBackground <string> state, ILoggerFactory loggerFactory) { this.subscription = subscription; this.logger = loggerFactory.CreateLogger <EWrapperImpl>(); this.signal = new EReaderMonitorSignal(); this.clientSocket = new EClientSocket(this, signal); this.queue = queue; this.state = state; this.quotes = new ConcurrentDictionary <string, Quote>(); }
public WrapperImplementationEx(string host, int port, int?clientId) { this.host = host; this.port = port; this.clientId = clientId ?? defaultClientId; Initialize(); signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, signal); }
/// <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 IBClient(EReaderSignal signal) { ClientSocket = new EClientSocket(this, signal); ManagedAccountsObservable = Observable.FromEvent <Action <string>, string>( onNext => (string a) => onNext(a), h => ManagedAccounts += h, h => ManagedAccounts -= h ) .ObserveOn(TaskPoolScheduler.Default) .Catch <string, Exception>(exc => { Error(-1, 0, nameof(ManagedAccounts), exc); return(new string[0].ToObservable()); }); }
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."); }
/// <summary> /// Initializes a new instance of the <see cref="TwsControllerBase"/> class. /// </summary> /// <param name="clientSocket">The client socket</param> /// <param name="twsCallbackHandler">The callback handler</param> /// <param name="host">The host</param> /// <param name="port">The port</param> /// <param name="clientId">The client id</param> public TwsControllerBase(ITwsClientSocket clientSocket, ITwsCallbackHandler twsCallbackHandler, string host, int port, int clientId) { this.clientSocket = clientSocket; this.twsCallbackHandler = twsCallbackHandler; this.host = host; this.port = port; this.clientId = clientId; this.accountUpdates = new ConcurrentDictionary <string, string>(); this.signal = new EReaderMonitorSignal(); this.twsRequestIdGenerator = new TwsRequestIdGenerator(); // Some events come in unrequested, this will subscribe before the connection is created this.twsCallbackHandler.NextValidIdEvent += this.OnNextValidId; this.twsCallbackHandler.UpdateAccountValueEvent += this.OnUpdateAccountValueEvent; }
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(); }
public void Login(int port, int id) { if (!_Client.IsConnected()) { EReaderSignal readerSignal = _Core.Signal; //! [connect] _Client.eConnect("127.0.0.1", port, id); var reader = new EReader(_Client, readerSignal); reader.Start(); //Once the messages are in the queue, an additional thread can be created to fetch them new Thread(() => { while (_Client.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); } }
public TradeService(int clientId) { ClientId = clientId; readerSignal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, readerSignal); // TradeBot events PropertyChanged += OnPropertyChanged; // EWrapperImpl events Error += OnError; ConnectAck += OnConnectAck; ConnectionClosed += OnConnectionClosed; ManagedAccounts += OnManagedAccounts; NextValidId += OnNextValidId; TickPrice += OnTickPrice; TickSize += OnTickSize; TickGeneric += OnTickGeneric; UpdatePortfolio += OnUpdatePortfolio; AccountDownloadEnd += OnAccountDownloadEnd; CommissionReport += OnCommissionReport; }
private static void ConnectToIb() { RequestsClient client = new RequestsClient( MyAppSettings.PushSocketPort, MyAppSettings.RequestSocketPort); client.Connect(); wrapper = new IbClient(client, MyAppSettings); EClientSocket clientSocket = wrapper.ClientSocket; EReaderSignal readerSignal = wrapper.Signal; clientSocket.eConnect(MyAppSettings.InteractiveBrokersIP, MyAppSettings.InteractiveBrokersPort, 0); //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) { } }
public EReader(EClientSocket clientSocket, EReaderSignal signal) { eClientSocket = clientSocket; eReaderSignal = signal; processMsgsDecoder = new EDecoder(eClientSocket.ServerVersion, eClientSocket.Wrapper, eClientSocket); }
public IBClient(EReaderSignal signal) { clientSocket = new EClientSocket(this, signal); }
public EReader(EClientSocket clientSocket, EReaderSignal signal) { eClientSocket = clientSocket; eReaderSignal = signal; processMsgsDecoder = new EDecoder(eClientSocket.ServerVersion, eClientSocket.Wrapper, eClientSocket); }
public EClientSocketSSL(EWrapper wrapper, EReaderSignal signal) : base(wrapper, signal) { }
public EWrapperImpl() { Signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, Signal); }
public EClientSocketSSL(EWrapper wrapper, EReaderSignal signal) : base(wrapper, signal) { }
public EClientSocket(EWrapper wrapper, EReaderSignal eReaderSignal): base(wrapper) { this.eReaderSignal = eReaderSignal; }
//! [socket_declare] //! [socket_init] public AbstractIBWrapper() { Signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, Signal); }
public static int Main(string[] args) { // specify account and strategy string IBaccount = TradeBooks.accountInit(); string tradingModel = "es_growth"; string tradingInstrument = "ES"; int multipler = 50; int tryCNT = 1; int tryGap = (int)openBook.gap * 20; int bestCNT = 0; double[] Returns = new double[2]; double[] Premium = new double[tryCNT]; int[] LegB_ID = new int[tryCNT]; int[] LegB = new int[tryCNT]; int legS; int legS_ID; openBook.positionCNT = 1; for (int n = 0; n < openBook.positionCNT; n++) { openBook.symbol[n] = tradingInstrument; openBook.multipler[n] = multipler; } //! start the connection int[] channel = new int[2]; channel = TradeBooks.channelSetup(IBaccount, tradingModel); EClientSocket clientSocket = Allture.ClientSocket; EReaderSignal readerSignal = Allture.Signal; //! [connect] clientSocket.eConnect("127.0.0.1", channel[0], channel[1]); //! [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] //**** current time ***** string date_time, last_time; date_time = DateTime.Now.ToString("hh:mm:ss tt"); //************************** //*** Account Info *** //************************** clientSocket.reqAccountSummary(9001, "All", AccountSummaryTags.GetAllTags()); Thread.Sleep(1000); Console.WriteLine("account ID: " + Allture.account_ID); Console.WriteLine("account Value: " + Allture.account_value); Console.WriteLine("account_BuyingPower: " + Allture.account_BuyingPower); Console.WriteLine("account_InitMarginReq: " + Allture.account_InitMarginReq); Console.WriteLine("account_MaintMarginReq: " + Allture.account_MaintMarginReq); Console.WriteLine("account_ExcessLiquidity: " + Allture.account_ExcessLiquidity); Console.WriteLine("account_AvailableFunds: " + Allture.account_AvailableFunds); Console.WriteLine("\n"); Allture.remainingOrderSize = 100000; // set to maxium order size clientSocket.reqMarketDataType(1); // clientSocket.reqGlobalCancel(); Thread.Sleep(sleep1); while ((DateTime.Now > Convert.ToDateTime("09:30:00 AM")) && (DateTime.Now < Convert.ToDateTime("16:00:00 PM"))) { last_time = date_time; for (int n = 0; n < openBook.positionCNT; n++) { if (openBook.status[n] == "complete") { continue; } if (openBook.status[n] == "submit") { Allture.currOrderId = openBook.currOrderID[n]; Allture.remainingOrderSize = 0; Allture.checkOrderEnd = false; clientSocket.reqOpenOrders(); while (!Allture.checkOrderEnd) { Thread.Sleep(200); } if (Allture.remainingOrderSize == 0) { openBook.status[n] = "complete"; openBook.capital[n] = 0; openBook.size[n] = 0; continue; // if remaining size = 0, means this order has completely filled. then go to the next position } } legS = 2700; legS_ID = getContractID(clientSocket, Allture, openBook, n, legS, "FOP", "GLOBEX"); LegB[0] = legS - 100; LegB_ID[0] = getContractID(clientSocket, Allture, openBook, n, LegB[0], "FOP", "GLOBEX"); //******* check the order status again. if still exiting, cancel the order order, update the order size and capital if (openBook.status[n] == "submit") { Allture.currOrderId = openBook.currOrderID[n]; Allture.remainingOrderSize = 0; Allture.checkOrderEnd = false; clientSocket.reqOpenOrders(); while (!Allture.checkOrderEnd) { Thread.Sleep(200); } if (Allture.remainingOrderSize == 0) { openBook.status[n] = "complete"; openBook.capital[n] = 0; openBook.size[n] = 0; continue; } else { clientSocket.cancelOrder(openBook.currOrderID[n]); //cancel existing order Thread.Sleep(sleep1); openBook.status[n] = "cancel"; if (Allture.remainingOrderSize > openBook.size[n]) { Allture.remainingOrderSize = openBook.size[n]; } openBook.capital[n] = openBook.capital[n] - (openBook.size[n] - Allture.remainingOrderSize) * openBook.margin[n]; openBook.size[n] = (int)(openBook.usingCapital * openBook.capital[n] / 10000); } } else { openBook.size[n] = (int)(100); } //********* Place order ************************ clientSocket.reqIds(-1); Thread.Sleep(sleep1); clientSocket.placeOrder(Allture.NextOrderId, ContractSamples.Contract_Combo(openBook.symbol[n], "BAG", openBook.expiration[n], openBook.CallPut[n], LegB_ID[0], legS_ID, openBook.multipler[n].ToString(), "GLOBEX"), OrderSamples.ComboLimitOrder("BUY", openBook.size[n], -1.0, false)); Thread.Sleep(sleep1); //********* update remaining of the trading book ************** openBook.status[n] = "submit"; openBook.currOrderID[n] = Allture.NextOrderId; openBook.legS[n] = legS; openBook.legB[n] = LegB[0]; openBook.premium[n] = 1.0; } } clientSocket.reqGlobalCancel(); Thread.Sleep(sleep1); Console.WriteLine("today's trading is done...time: " + DateTime.Now); clientSocket.eDisconnect(); return(0); }
public IBClient(EReaderSignal signal) { clientSocket = new EClientSocket(this, signal); sc = SynchronizationContext.Current; }
public IBClient(EReaderSignal signal) { clientSocket = new EClientSocket(this, signal); scheduler = TaskScheduler.FromCurrentSynchronizationContext(); }
public EClientSocket(EWrapper wrapper, EReaderSignal eReaderSignal) : base(wrapper) { this.eReaderSignal = eReaderSignal; }