private static int getContractID(EClientSocket client, EWrapperImpl Allture, TradeBooks Book, int m, int leg, string sectype, string exchange) { Allture.checkContractEnd = false; client.reqContractDetails(20010, ContractSamples.Contract_Options(Book.symbol[m], sectype, Book.expiration[m], Book.CallPut[m], leg, Book.multipler[m].ToString(), exchange)); //Thread.Sleep(sleep1); while (!Allture.checkContractEnd) { Thread.Sleep(200); } Console.WriteLine("contract_ID: " + Allture.contract_ID + "\n"); return(Allture.contract_ID); }
public static int Main(string[] args) { EWrapperImpl testImpl = new EWrapperImpl(); testImpl.ClientSocket.eConnect("127.0.0.1", 7496, 0, false); /*************************************************************************************************************************************************/ /* One good 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(testImpl); Console.WriteLine("Disconnecting..."); testImpl.ClientSocket.eDisconnect(); return 0; }
private static double getMktData(EClientSocket client, EWrapperImpl Allture, string symbol, string sectype, string expiration, string exchange) { if (string.IsNullOrEmpty(expiration)) { client.reqMktData(1005, ContractSamples.Contract_RT(symbol, sectype, exchange), string.Empty, false, false, null); } else { client.reqMktData(1005, ContractSamples.Contract_FUT(symbol, sectype, expiration, exchange), string.Empty, false, false, null); } Thread.Sleep(sleep2); client.cancelMktData(1005); // Thread.Sleep(sleep0); Console.WriteLine("\n price: " + Allture.mkt_price + "\n"); return(Allture.mkt_price); }
private static double getSpreadPremium(EClientSocket client, EWrapperImpl Allture, TradeBooks Book, int m, double LegS, double LegB, string sectype, string exchange) { double LegB_price, LegS_price; client.reqMktData(3011, ContractSamples.Contract_Options(Book.symbol[m], sectype, Book.expiration[m], Book.CallPut[m], LegB, Book.multipler[m].ToString(), exchange), string.Empty, false, false, null); Thread.Sleep(1000); client.cancelMktData(3011); LegB_price = Allture.ask_price; Console.WriteLine("legB ask: " + LegB_price + "\n"); client.reqMktData(3012, ContractSamples.Contract_Options(Book.symbol[m], sectype, Book.expiration[m], Book.CallPut[m], LegS, Book.multipler[m].ToString(), exchange), string.Empty, false, false, null); Thread.Sleep(1000); client.cancelMktData(3012); LegS_price = Allture.ask_price; Console.WriteLine("legS ask: " + LegS_price + "\n"); return(LegS_price - LegB_price); }
static void Main(string[] args) { var ibClient = new EWrapperImpl(); Console.WriteLine("Connecting..."); ibClient.ClientSocket.eConnect("127.0.0.1", 4002, 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(ibClient.ClientSocket, ibClient.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()) { ibClient.Signal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); Contract contract = new Contract(); contract.Symbol = "USD"; contract.SecType = "CASH"; contract.Currency = "CAD"; contract.Exchange = "IDEALPRO"; Console.WriteLine("Requesting Data..."); ibClient.ClientSocket.reqMktData(1, contract, "", false, false, null); Thread.Sleep(1000); ibClient.ClientSocket.reqRealTimeBars(1, contract, 5, "MIDPOINT", true, null); Thread.Sleep(1000); Console.WriteLine("Press any key to exit"); Console.Read(); ibClient.ClientSocket.eDisconnect(); }
/*****************************************************************/ /* Below are few quick-to-test examples on the IB API functions. */ /*****************************************************************/ private static void testIBMethods(EWrapperImpl wrapper) { /***************************************************/ /*** Real time market data operations - Tickers ***/ /***************************************************/ /*** Requesting real time market data ***/ //wrapper.ClientSocket.reqMarketDataType(2); //wrapper.ClientSocket.reqMktData(1001, ContractSamples.getEurUsdForex(), "", false, GetFakeParameters(3)); //wrapper.ClientSocket.reqMktData(1002, ContractSamples.getOption(), "", false, GetFakeParameters(3)); //wrapper.ClientSocket.reqMktData(1003, ContractSamples.getEuropeanStock(), "", false); //Thread.Sleep(2000); /*** Canceling the market data subscription ***/ //wrapper.ClientSocket.cancelMktData(1001); //wrapper.ClientSocket.cancelMktData(1002); //wrapper.ClientSocket.cancelMktData(1003); /********************************************************/ /*** Real time market data operations - Market Depth ***/ /********************************************************/ /*** Requesting the Deep Book ***/ //wrapper.ClientSocket.reqMarketDepth(2001, ContractSamples.getEurGbpForex(), 5, GetFakeParameters(2)); //Thread.Sleep(2000); /*** Canceling the Deep Book request ***/ //wrapper.ClientSocket.cancelMktDepth(2001); /**********************************************************/ /*** Real time market data operations - Real Time Bars ***/ /**********************************************************/ /*** Requesting real time bars ***/ //wrapper.ClientSocket.reqRealTimeBars(3001, ContractSamples.getEurGbpForex(), -1, "MIDPOINT", true, GetFakeParameters(4)); //Thread.Sleep(2000); /*** Canceling real time bars ***/ //wrapper.ClientSocket.cancelRealTimeBars(3001); /**************************************************************/ /*** Real time market data operations - Streamed or Frozen ***/ /**************************************************************/ /*** Switch to frozen or streaming***/ //wrapper.ClientSocket.reqMarketDataType(1); /**********************************/ /*** Historical Data operations ***/ /**********************************/ /*** Requesting historical data ***/ //wrapper.ClientSocket.reqHistoricalData(4001, ContractSamples.getEurGbpForex(), "20130722 23:59:59", "1 D", "1 min", "MIDPOINT", 1, 1, GetFakeParameters(4)); //wrapper.ClientSocket.reqHistoricalData(4002, ContractSamples.getEuropeanStock(), "20131009 23:59:59", "10 D", "1 min", "TRADES", 1, 1); /*** Canceling historical data requests ***/ //wrapper.ClientSocket.cancelHistoricalData(4001); //wrapper.ClientSocket.cancelHistoricalData(4002); /*************************/ /*** Options Specifics ***/ /*************************/ /*** Calculating implied volatility ***/ //wrapper.ClientSocket.calculateImpliedVolatility(5001, ContractSamples.getOption(), 5, 85, GetFakeParameters(6)); /*** Canceling implied volatility ***/ //wrapper.ClientSocket.cancelCalculateImpliedVolatility(5001); /*** Calculating option's price ***/ //wrapper.ClientSocket.calculateOptionPrice(5002, ContractSamples.getOption(), 0.22, 85, GetFakeParameters(1)); /*** Canceling option's price calculation ***/ //wrapper.ClientSocket.cancelCalculateOptionPrice(5002); /*** Exercising options ***/ //wrapper.ClientSocket.exerciseOptions(5003, ContractSamples.GetSANTOption(), 1, 1, null, 1); /****************************/ /*** Contract information ***/ /****************************/ //wrapper.ClientSocket.reqContractDetails(6001, ContractSamples.GetbyIsin()); //wrapper.ClientSocket.reqContractDetails(210, ContractSamples.getOptionForQuery()); //wrapper.ClientSocket.reqContractDetails(211, ContractSamples.GetBondForQuery()); /***********************/ /*** Market Scanners ***/ /***********************/ /*** Requesting all available parameters which can be used to build a scanner request ***/ //wrapper.ClientSocket.reqScannerParameters(); /*** Triggering a scanner subscription ***/ //wrapper.ClientSocket.reqScannerSubscription(7001, ScannerSubscriptionSamples.GetScannerSubscription(), GetFakeParameters(5)); /*** Canceling the scanner subscription ***/ //wrapper.ClientSocket.cancelScannerSubscription(7001); /*****************************/ /*** Reuter's Fundamentals ***/ /*****************************/ /*** Requesting Fundamentals ***/ //wrapper.ClientSocket.reqFundamentalData(8001, ContractSamples.GetUSStock(), "snapshot", GetFakeParameters(4)); /*** Camceling fundamentals request ***/ //wrapper.ClientSocket.cancelFundamentalData(8001); /***********************/ /*** IB's Bulletins ***/ /***********************/ /*** Requesting Interactive Broker's news bulletins */ //wrapper.ClientSocket.reqNewsBulletins(true); /*** Canceling IB's news bulletins ***/ //wrapper.ClientSocket.cancelNewsBulletin(); /**************************/ /*** Account Management ***/ /**************************/ /*** Requesting managed accounts***/ //wrapper.ClientSocket.reqManagedAccts(); /*** Requesting accounts' summary ***/ //wrapper.ClientSocket.reqAccountSummary(9001, "All", AccountSummaryTags.GetAllTags()); /*** Subscribing to an account's information. Only one at a time! ***/ //wrapper.ClientSocket.reqAccountUpdates(true, "U150462"); /*** Requesting all accounts' positions. ***/ //wrapper.ClientSocket.reqPositions(); /**********************/ /*** Order handling ***/ /**********************/ /*** Requesting the next valid id ***/ //wrapper.ClientSocket.reqIds(-1); /*** Requesting all open orders ***/ //wrapper.ClientSocket.reqAllOpenOrders(); /*** Taking over orders to be submitted via TWS ***/ //wrapper.ClientSocket.reqAutoOpenOrders(true); /*** Requesting this API client's orders ***/ //wrapper.ClientSocket.reqOpenOrders(); /*** Placing/modifying an order - remember to ALWAYS increment the nextValidId after placing an order so it can be used for the next one! ***/ //Order order = OrderSamples.LimitOrder(); //order.OrderMiscOptions = GetFakeParameters(3); //wrapper.ClientSocket.placeOrder(wrapper.NextOrderId++, ContractSamples.getComboContract(), order); //wrapper.ClientSocket.placeOrder(wrapper.NextOrderId++, ContractSamples.getComboContract(), OrderSamples.LimitOrderForComboWithLegPrice()); //wrapper.ClientSocket.placeOrder(wrapper.NextOrderId++, ContractSamples.getVixComboContract(), OrderSamples.LimitOrder()); /*** Cancel all orders for all accounts ***/ //wrapper.ClientSocket.reqGlobalCancel(); /*** Request the day's executions ***/ //wrapper.ClientSocket.reqExecutions(10001, new ExecutionFilter()); /************************************/ /*** Financial Advisor Exclusive Operations ***/ /************************************/ /*** Requesting FA information ***/ //wrapper.ClientSocket.requestFA(Constants.FaAliases); //wrapper.ClientSocket.requestFA(Constants.FaGroups); //wrapper.ClientSocket.requestFA(Constants.FaProfiles); /*** Replacing FA information - Fill in with the appropriate XML string. ***/ //wrapper.ClientSocket.replaceFA(Constants.FaGroups, ""); /********************/ /*** Miscelaneous ***/ /********************/ /*** Request TWS' current time ***/ //wrapper.ClientSocket.reqCurrentTime(); /*** Setting TWS logging level ***/ //wrapper.ClientSocket.setServerLogLevel(1); /********************/ /*** Linking ***/ /********************/ //wrapper.ClientSocket.verifyRequest("a name", "9.71"); //wrapper.ClientSocket.verifyMessage("apiData"); //wrapper.ClientSocket.queryDisplayGroups(123); //wrapper.ClientSocket.subscribeToGroupEvents(124, 1); //wrapper.ClientSocket.updateDisplayGroup(125, "contract info"); //wrapper.ClientSocket.unsubscribeFromGroupEvents(124); //Thread.Sleep(3000); Console.WriteLine("Done"); Thread.Sleep(500000); }
public static int Main(string[] args) { contractId = new Dictionary <int, SpecContract>(); ListToMonitor = new List <SpecContract>(); //{ // new SpecContract() // { // Symbol = "AAPL", // Strike = 320, // LastTradeDateOrContractMonth = "200131" // }, // new SpecContract() // { // Symbol = "NFLX", // Strike = 340, // LastTradeDateOrContractMonth = "200124" // } //}; var symbols = Properties.Settings.Default.Stock.Split(','); for (int i = 0; i < symbols.Length; i++) { ListToMonitor.Add(new SpecContract() { Symbol = symbols[i], Strike = double.Parse(Properties.Settings.Default.Strike.Split(',')[i]), LastTradeDateOrContractMonth = Properties.Settings.Default.ExpDate.Split(',')[i] } ); } EWrapperImpl testImpl = new EWrapperImpl(); EClientSocket clientSocket = testImpl.ClientSocket; EReaderSignal readerSignal = testImpl.Signal; //! [connect] //clientSocket.eConnect("127.0.0.1", 7496, 0); clientSocket.eConnect("", 7496, 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 need to fetch them new Thread(() => { while (clientSocket.IsConnected()) { readerSignal.waitForSignal(); reader.processMsgs(); } }) { IsBackground = true }.Start(); int tickerId = 100; int tickerId_Option = 200; foreach (var stock in ListToMonitor) { Console.WriteLine($"Symbol {stock.Symbol} - {stock.LastTradeDateOrContractMonth}"); stock.TickerId = tickerId++; stock.TickerOptionId = tickerId_Option++; clientSocket.reqMarketDataType(2); getStockPrice(clientSocket, stock.Symbol, stock.TickerId, stock.LastTradeDateOrContractMonth); string expDate = stock.LastTradeDateOrContractMonth; getContractDetails(clientSocket, stock.Symbol, stock.TickerOptionId, expDate, stock.Strike); while (contractId.Count == 0) { } Thread.Sleep(500); Console.WriteLine("====================================="); Console.WriteLine("Contract Id set to: " + contractId); foreach (var contId in contractId) { Console.WriteLine($"ContractId {contId.Value.ConId} , tickerId {contId.Key}"); getOptionPrice(clientSocket, stock.Symbol, contId.Key, contId.Value.ConId, stock.Strike); } } Console.ReadKey(); foreach (var stock in ListToMonitor) { clientSocket.cancelMktData(stock.TickerId); clientSocket.cancelMktData(stock.TickerOptionId); } Console.WriteLine("Disconnecting..."); clientSocket.eDisconnect(); return(0); }