private static void HedgeSample(EClientSocket client, int nextOrderId) { //F Hedge order //! [hedgesubmit] //Parent order on a contract which currency differs from your base currency Order parent = OrderSamples.LimitOrder("BUY", 100, 10); parent.OrderId = nextOrderId++; //Hedge on the currency conversion Order hedge = OrderSamples.MarketFHedge(parent.OrderId, "BUY"); //Place the parent first... client.placeOrder(parent.OrderId, ContractSamples.EuropeanStock(), parent); //Then the hedge order client.placeOrder(nextOrderId++, ContractSamples.EurGbpFx(), hedge); //! [hedgesubmit] }
private EWrapperImpl() { //this.MAX_QUOTE_LIST = maxQuote; this.clientSocket = new EClientSocket(this); this.equityDict = new Dictionary <int, Equities>(); this.PairPosDict = new Dictionary <int, PairPos>(); try { File.Copy("mylogger.txt", "backup_logger.txt", true); } catch (Exception) { Console.WriteLine("Skip backing up and created a new logger file"); } MyLogger.Instance.Open("mylogger.txt", false); // create/open logger file this.readSymbols(SYMBOL_FILE_DIR); }
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(); }
private static void marketDepthOperations(EClientSocket client) { /*** Requesting the Deep Book ***/ //! [reqmarketdepth] client.reqMarketDepth(2001, ContractSamples.EurGbpFx(), 5, null); //! [reqmarketdepth] Thread.Sleep(2000); /*** Canceling the Deep Book request ***/ //! [cancelmktdepth] client.cancelMktDepth(2001); //! [cancelmktdepth] /*** Requesting Market Depth Exchanges ***/ Thread.Sleep(2000); //! [reqMktDepthExchanges] client.reqMktDepthExchanges(); //! [reqMktDepthExchanges] }
//* @param durationString the amount of time for which the data needs to be retrieved: //* - " S (seconds) //* - " D (days) //* - " W (weeks) //* - " M (months) //* - " Y (years) //* @param barSizeSetting the size of the bar: //* - 1 sec //* - 5 secs //* - 15 secs //* - 30 secs //* - 1 min //* - 2 mins //* - 3 mins //* - 5 mins //* - 15 mins //* - 30 mins //* - 1 hour //* - 1 day private static void historicalDataRequests(EClientSocket client) { /*** Requesting historical data ***/ //! [reqhistoricaldata] String queryTime = DateTime.Now.ToString("yyyyMMdd HH:mm:ss"); client.reqHistoricalData(1000, ContractSamples.USStock(), queryTime, "7 D", "1 hour", "MIDPOINT", 1, 1, false, null); //client.reqHistoricalData(4002, ContractSamples.USOptionContract(), "20180604", "1 day", "1 min", "MIDPOINT", 1, 1, false, null); //client.reqHistoricalData(4001, ContractSamples.EurGbpFx(), queryTime, "1 M", "1 day", "MIDPOINT", 1, 1, false, null); //client.reqHistoricalData(4002, ContractSamples.EuropeanStock(), queryTime, "10 D", "1 min", "TRADES", 1, 1, false, null); //! [reqhistoricaldata] //Thread.Sleep(2000); /*** Canceling historical data requests ***/ //client.cancelHistoricalData(4001); //client.cancelHistoricalData(4002); }
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); }
private static void marketScanners(EClientSocket client) { /*** Requesting all available parameters which can be used to build a scanner request ***/ //! [reqscannerparameters] client.reqScannerParameters(); //! [reqscannerparameters] Thread.Sleep(2000); /*** Triggering a scanner subscription ***/ //! [reqscannersubscription] client.reqScannerSubscription(7001, ScannerSubscriptionSamples.HighOptVolumePCRatioUSIndexes(), "", null); TagValue t1 = new TagValue("usdMarketCapAbove", "10000"); TagValue t2 = new TagValue("optVolumeAbove", "1000"); TagValue t3 = new TagValue("avgVolumeAbove", "100000000"); List <TagValue> TagValues = new List <TagValue> { t1, t2, t3 }; client.reqScannerSubscription(7002, ScannerSubscriptionSamples.HotUSStkByVolume(), null, TagValues); // requires TWS v973+ //! [reqscannersubscription] //! [reqcomplexscanner] TagValue t = new TagValue("underConID", "265598"); List <TagValue> AAPLConIDTag = new List <TagValue> { t }; client.reqScannerSubscription(7003, ScannerSubscriptionSamples.ComplexOrdersAndTrades(), null, AAPLConIDTag); // requires TWS v975+ //! [reqcomplexscanner] Thread.Sleep(2000); /*** Canceling the scanner subscription ***/ //! [cancelscannersubscription] client.cancelScannerSubscription(7001); client.cancelScannerSubscription(7002); client.cancelScannerSubscription(7003); //! [cancelscannersubscription] }
private static void tickByTickOperations(EClientSocket client) { /*** Requesting tick-by-tick data (only refresh) ***/ //! [reqtickbytick] client.reqTickByTickData(19001, ContractSamples.USStockAtSmart(), "Last"); client.reqTickByTickData(19002, ContractSamples.USStockAtSmart(), "AllLast"); client.reqTickByTickData(19003, ContractSamples.USStockAtSmart(), "BidAsk"); client.reqTickByTickData(19004, ContractSamples.EurGbpFx(), "MidPoint"); //! [reqtickbytick] Thread.Sleep(10000); //! [canceltickbytick] client.cancelTickByTickData(19001); client.cancelTickByTickData(19002); client.cancelTickByTickData(19003); client.cancelTickByTickData(19004); //! [canceltickbytick] }
private static void marketScanners(EClientSocket client) { /*** Requesting all available parameters which can be used to build a scanner request ***/ //! [reqscannerparameters] client.reqScannerParameters(); //! [reqscannerparameters] Thread.Sleep(2000); /*** Triggering a scanner subscription ***/ //! [reqscannersubscription] client.reqScannerSubscription(7001, ScannerSubscriptionSamples.HighOptVolumePCRatioUSIndexes(), null); //! [reqscannersubscription] Thread.Sleep(2000); /*** Canceling the scanner subscription ***/ //! [cancelscannersubscription] client.cancelScannerSubscription(7001); //! [cancelscannersubscription] }
private static void tickDataOperations(EClientSocket client) { /*** Requesting real time market data ***/ //Thread.Sleep(1000); //! [reqmktdata] client.reqMktData(1001, ContractSamples.StockComboContract(), string.Empty, false, null); //! [reqmktdata] //! [reqmktdata_snapshot] client.reqMktData(1003, ContractSamples.FutureComboContract(), string.Empty, true, null); //! [reqmktdata_snapshot] //! [reqmktdata_genticks] //Requesting RTVolume (Time & Sales), shortable and Fundamental Ratios generic ticks client.reqMktData(1004, ContractSamples.USStock(), "233,236,258", false, null); //! [reqmktdata_genticks] //! [reqmktdata_contractnews] client.reqMktData(1005, ContractSamples.USStock(), "mdoff,292:BZ", false, null); client.reqMktData(1006, ContractSamples.USStock(), "mdoff,292:BT", false, null); client.reqMktData(1007, ContractSamples.USStock(), "mdoff,292:FLY", false, null); client.reqMktData(1008, ContractSamples.USStock(), "mdoff,292:MT", false, null); //! [reqmktdata_contractnews] //! [reqmktdata_broadtapenews] client.reqMktData(1009, ContractSamples.BTbroadtapeNewsFeed(), "mdoff,292", false, null); client.reqMktData(1010, ContractSamples.BZbroadtapeNewsFeed(), "mdoff,292", false, null); client.reqMktData(1011, ContractSamples.FLYbroadtapeNewsFeed(), "mdoff,292", false, null); client.reqMktData(1012, ContractSamples.MTbroadtapeNewsFeed(), "mdoff,292", false, null); //! [reqmktdata_broadtapenews] //! [reqoptiondatagenticks] //Requesting data for an option contract will return the greek values client.reqMktData(1002, ContractSamples.OptionWithLocalSymbol(), string.Empty, false, null); //! [reqoptiondatagenticks] Thread.Sleep(10000); /*** Canceling the market data subscription ***/ //! [cancelmktdata] client.cancelMktData(1001); client.cancelMktData(1002); client.cancelMktData(1003); //! [cancelmktdata] }
public IBCore() { _Core = new EWrapperImpl(); _Portfolios = new List <IBPortfolioModel>(); _Account = new List <IBAccountModel>(); _MktData = new List <MktData>(); _DailyContractPL = new Dictionary <int, Contract>(); _Core.OnManagedAccounts += _core_OnManagedAccounts; _Core.OnUpdatePortfolio += _core_OnUpdatePortfolio; _Core.OnUpdateAccount += _Core_OnUpdateAccount; _Core.OnManagedTickPrice += _Core_OnManagedTickPrice; _Core.OntickOptionComputation += _Core_OntickOptionComputation; _Core.OnpnlSingle += _Core_OnpnlSingle; _Core.Onpnl += _Core_Onpnl; _Core.OnError1 += _Core_OnError1; _Client = _Core.ClientSocket; }
private static void historicalDataRequests(EClientSocket client) { //Console.WriteLine(account.Email); /*** Requesting historical data ***/ //! [reqhistoricaldata] if (tradeConfig.Historical) { String queryTime = DateTime.Now.ToString("yyyyMMdd HH:mm:ss"); foreach (StockConfig sc in tradeConfig.Stocks) { client.reqHistoricalData(sc.Id, ContractSamples.GetContract(sc.Symbol), queryTime, "9 M", "1 min", "MIDPOINT", 1, 1, false, null); } //client.reqHistoricalData(1002, ContractSamples.USStock2(), queryTime, "9 M", "1 min", "MIDPOINT", 1, 1, false, null); //! [reqhistoricaldata] //Thread.Sleep(2000); /*** Canceling historical data requests ***/ //client.cancelHistoricalData(1001); } }
private static void rerouteCFDOperations(EClientSocket client) { //! [reqmktdatacfd] client.reqMktData(16001, ContractSamples.USStockCFD(), string.Empty, false, false, null); Thread.Sleep(1000); client.reqMktData(16002, ContractSamples.EuropeanStockCFD(), string.Empty, false, false, null); Thread.Sleep(1000); client.reqMktData(16003, ContractSamples.CashCFD(), string.Empty, false, false, null); Thread.Sleep(1000); //! [reqmktdatacfd] //! [reqmktdepthcfd] client.reqMarketDepth(16004, ContractSamples.USStockCFD(), 10, false, null); Thread.Sleep(1000); client.reqMarketDepth(16005, ContractSamples.EuropeanStockCFD(), 10, false, null); Thread.Sleep(1000); client.reqMarketDepth(16006, ContractSamples.CashCFD(), 10, false, null); Thread.Sleep(1000); //! [reqmktdepthcfd] }
//String etfDir, String stkDir public EWrapperImpl(string symbolFileDir, string quoteFolderDir, int maxQuote) { //this.MAX_QUOTE_LIST = maxQuote; this.SYMBOL_FILE_DIR = symbolFileDir; this.QUOTE_FOLDER_DIR = quoteFolderDir; this.clientSocket = new EClientSocket(this); this.tickerSymbolDict = new Dictionary <int, string>(); this.etfSymbolLst = new List <string>(); // quote dict has been moved //this.quoteDict = new Dictionary<int, List<QuoteTick>>(); this.PairPosDict = new Dictionary <int, PairPos>(); MyLogger.Instance.Open("mylogger.txt", true); // create/open logger file this.CSVReader(SYMBOL_FILE_DIR); this.CreatePairObjs(); }
private static void realTimeBars(EClientSocket client) { /*** Requesting real time bars ***/ if (tradeConfig.Realtime) { #region Realtime with today's RSI String queryTime = DateTime.Now.ToString("yyyyMMdd HH:mm:ss"); foreach (StockConfig sc in tradeConfig.Stocks) { client.reqHistoricalData(sc.Id, ContractSamples.GetContract(sc.Symbol), queryTime, "1 D", "1 min", "MIDPOINT", 1, 1, false, null); } //client.reqHistoricalData(1001, ContractSamples.USStock(), queryTime, "1 D", "1 min", "MIDPOINT", 1, 1, false, null); Thread.Sleep(10000); //client.cancelHistoricalData(1001); foreach (StockConfig sc in tradeConfig.Stocks) { client.reqRealTimeBars(sc.Id, ContractSamples.GetContract(sc.Symbol), 5, "MIDPOINT", true, null); } //client.reqRealTimeBars(1001, ContractSamples.USStock(), 5, "MIDPOINT", true, null); #endregion } if (tradeConfig.AfterRTH) { #region After RTH trading foreach (StockConfig sc in tradeConfig.Stocks) { client.reqRealTimeBars(sc.Id, ContractSamples.GetContract(sc.Symbol), 5, "MIDPOINT", false, null); } //client.reqRealTimeBars(1001, ContractSamples.USStock(), 5, "MIDPOINT", false, null); #endregion } //client.reqRealTimeBars(1002, ContractSamples.USOptionContract2(), 5, "MIDPOINT", true, null); //! [reqrealtimebars] //Thread.Sleep(2000); /*** Canceling real time bars ***/ //! [cancelrealtimebars] //client.cancelRealTimeBars(3001); //! [cancelrealtimebars] }
private static void linkingOperations(EClientSocket client) { client.verifyRequest("a name", "9.71"); client.verifyMessage("apiData"); //! [querydisplaygroups] client.queryDisplayGroups(9001); //! [querydisplaygroups] //! [subscribetogroupevents] client.subscribeToGroupEvents(9002, 1); //! [subscribetogroupevents] //! [updatedisplaygroup] client.updateDisplayGroup(9002, "8314@SMART"); //! [updatedisplaygroup] //! [subscribefromgroupevents] client.unsubscribeFromGroupEvents(9002); //! [subscribefromgroupevents] }
public static int Main(string[] args) { string jsonText = File.ReadAllText("TradeConfig.json"); tradeConfig = JsonConvert.DeserializeObject <TradeConfig>(jsonText); 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 can be created 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); }
private static void tickByTickOperations(EClientSocket client) { /*** Requesting tick-by-tick data (only refresh) ***/ //! [reqtickbytick] client.reqTickByTickData(19001, ContractSamples.USStockAtSmart(), "Last", 0, false); client.reqTickByTickData(19002, ContractSamples.USStockAtSmart(), "AllLast", 0, false); client.reqTickByTickData(19003, ContractSamples.USStockAtSmart(), "BidAsk", 0, true); client.reqTickByTickData(19004, ContractSamples.EurGbpFx(), "MidPoint", 0, false); //! [reqtickbytick] Thread.Sleep(10000); //! [canceltickbytick] client.cancelTickByTickData(19001); client.cancelTickByTickData(19002); client.cancelTickByTickData(19003); client.cancelTickByTickData(19004); //! [canceltickbytick] Thread.Sleep(5000); /*** Requesting tick-by-tick data (historical + refresh) ***/ //! [reqtickbytick] client.reqTickByTickData(19005, ContractSamples.EuropeanStock(), "Last", 10, false); client.reqTickByTickData(19006, ContractSamples.EuropeanStock(), "AllLast", 10, false); client.reqTickByTickData(19007, ContractSamples.EuropeanStock(), "BidAsk", 10, false); client.reqTickByTickData(19008, ContractSamples.EurGbpFx(), "MidPoint", 10, true); //! [reqtickbytick] Thread.Sleep(10000); //! [canceltickbytick] client.cancelTickByTickData(19005); client.cancelTickByTickData(19006); client.cancelTickByTickData(19007); client.cancelTickByTickData(19008); //! [canceltickbytick] }
private static void optionsOperations(EClientSocket client) { //! [reqsecdefoptparams] client.reqSecDefOptParams(0, "IBM", "", "STK", 8314); //! [reqsecdefoptparams] /*** Calculating implied volatility ***/ //! [calculateimpliedvolatility] client.calculateImpliedVolatility(5001, ContractSamples.OptionAtBOX(), 5, 85, null); //! [calculateimpliedvolatility] /*** Canceling implied volatility ***/ client.cancelCalculateImpliedVolatility(5001); /*** Calculating option's price ***/ //! [calculateoptionprice] client.calculateOptionPrice(5002, ContractSamples.OptionAtBOX(), 0.22, 85, null); //! [calculateoptionprice] /*** Canceling option's price calculation ***/ client.cancelCalculateOptionPrice(5002); /*** Exercising options ***/ //! [exercise_options] client.exerciseOptions(5003, ContractSamples.OptionWithTradingClass(), 1, 1, null, 1); //! [exercise_options] }
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 financialAdvisorOperations(EClientSocket client) { /*** Requesting FA information ***/ //! [requestfaaliases] client.requestFA(Constants.FaAliases); //! [requestfaaliases] //! [requestfagroups] client.requestFA(Constants.FaGroups); //! [requestfagroups] //! [requestfaprofiles] client.requestFA(Constants.FaProfiles); //! [requestfaprofiles] /*** Replacing FA information - Fill in with the appropriate XML string. ***/ //! [replacefaonegroup] client.replaceFA(Constants.FaGroups, FaAllocationSamples.FaOneGroup); //! [replacefaonegroup] //! [replacefatwogroups] client.replaceFA(Constants.FaGroups, FaAllocationSamples.FaTwoGroups); //! [replacefatwogroups] //! [replacefaoneprofile] client.replaceFA(Constants.FaProfiles, FaAllocationSamples.FaOneProfile); //! [replacefaoneprofile] //! [replacefatwoprofiles] client.replaceFA(Constants.FaProfiles, FaAllocationSamples.FaTwoProfiles); //! [replacefatwoprofiles] //! [reqSoftDollarTiers] client.reqSoftDollarTiers(4001); //! [reqSoftDollarTiers] }
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 InteractiveBrokersApi() { Logger = LogManager.GetLogger("IbApi"); EReaderSignal = new EReaderMonitorSignal(); Client = new EClientSocket(this, EReaderSignal); }
public IBClient(EReaderSignal signal) { clientSocket = new EClientSocket(this, signal); }
public MainForm() { mApi = new EClientSocket((EWrapper) new ApiEventSource(this, SynchronizationContext.Current), mSignal); InitializeComponent(); }
public EWrapperImpl() { Signal = new EReaderMonitorSignal(); clientSocket = new EClientSocket(this, Signal); }
public IBClient(IBTradeApp parent) { parentUI = parent; clientSocket = new EClientSocket(this); }
public EWrapperImpl() { clientSocket = new EClientSocket(this); }
public LoggingEClientSocketFacade(EClientSocket socket) { this.socket = socket; }
public ClientCommandAsync(EClientSocket clientSocket, IClientMessage clientMessage, TimeSpan timeout) { _timeout = timeout; _clientSocket = clientSocket; _clientMessage = clientMessage; }