### Place VWAP Order Example (VB.NET) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html A VB.NET example showing how to place a VWAP order. It involves creating a limit order, setting VWAP parameters via FillVwapParams, and then submitting the order. ```vbnet Dim baseOrder As Order = OrderSamples.LimitOrder("BUY", 1000, 1) AvailableAlgoParams.FillVwapParams(baseOrder, 0.2, "09:00:00 US/Eastern", "16:00:00 US/Eastern", True, True, True) client.placeOrder(increment(nextOrderId), ContractSamples.USStockAtSmart(), baseOrder) ``` -------------------------------- ### Place VWAP Order Example (C#) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing a VWAP order in C#. It first creates a limit order and then uses FillVwapParams to configure the VWAP strategy before placing the order. ```csharp Order baseOrder = OrderSamples.LimitOrder("BUY", 1000, 1); AvailableAlgoParams.FillVwapParams(baseOrder, 0.2, "09:00:00 US/Eastern", "16:00:00 US/Eastern", true, true, true); client.placeOrder(nextOrderId++, ContractSamples.USStockAtSmart(), baseOrder); ``` -------------------------------- ### Start Source: https://interactivebrokers.github.io/tws-api/classIBApi_1_1EReader.html Starts the EReader to begin capturing and processing incoming API messages. ```APIDOC ## Start ### Description Starts the EReader to begin capturing and processing incoming API messages. ### Method void ### Endpoint N/A (Method call) ``` -------------------------------- ### Configure PctVolTm Strategy Parameters Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Sets up the 'PctVolTm' algorithm strategy for an order, including start and end percentages of volume, start and end times, and a flag to disable taking liquidity. ```python 4 endTime: str, noTakeLiq: bool): baseOrder.algoStrategy = "PctVolTm" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("startPctVol", startPctVol)) baseOrder.algoParams.append(TagValue("endPctVol", endPctVol)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append(TagValue("noTakeLiq", int(noTakeLiq))) ``` -------------------------------- ### Requesting Market Data Snapshots (C++) Source: https://interactivebrokers.github.io/tws-api/md_request.html C++ example for requesting market data snapshots. ```cpp m_pClient->reqMktData(1003, ContractSamples::FutureComboContract(), "", true, false, TagValueListSPtr()); ``` -------------------------------- ### Place Order with FillBalanceImpactRiskParams (C++) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html This C++ snippet shows how to place an order using the FillBalanceImpactRiskParams function. Note that this example uses a different algorithm ('BalanceImpactRisk') than the VWAP examples. ```cpp Order baseOrder = OrderSamples::LimitOrder("BUY", DecimalFunctions::stringToDecimal("1000"), 1); AvailableAlgoParams::FillBalanceImpactRiskParams(baseOrder, 0.1, "Aggressive", true); m_pClient->placeOrder(m_orderId++, ContractSamples::USStockAtSmart(), baseOrder); ``` -------------------------------- ### Requesting Market Data Snapshots (VB.NET) Source: https://interactivebrokers.github.io/tws-api/md_request.html VB.NET example for requesting market data snapshots. ```vbnet client.reqMktData(1003, ContractSamples.FutureComboContract(), String.Empty, True, False, Nothing) ``` -------------------------------- ### Requesting Market Data Snapshots (Python) Source: https://interactivebrokers.github.io/tws-api/md_request.html Python example for requesting market data snapshots. ```python self.reqMktData(1002, ContractSamples.FutureComboContract(), "", True, False, []) ``` -------------------------------- ### startApi Source: https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClientSocket-members.html Starts the API client. This method should be called after setting connection options and before attempting to connect. ```APIDOC ## startApi ### Description Initializes and starts the TWS API client. This method should be called after configuring connection parameters and before calling the connect method. ``` -------------------------------- ### startApi Source: https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient-members.html Starts the API functionality. ```APIDOC ## startApi ### Description Starts the API functionality. ### Method (Not specified, likely internal) ### Parameters None ``` -------------------------------- ### Place Midprice Order (Java) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing a Midprice order using Java. The price cap is optional. ```java Order order = new Order(); order.action(action); order.orderType("MIDPRICE"); order.totalQuantity(quantity); order.lmtPrice(priceCap); // optional client.placeOrder(nextOrderId++, ContractSamples.USStockAtSmart(), OrderSamples.Midprice("BUY", Decimal.ONE, 150)); ``` -------------------------------- ### Implementing EWrapper Interface in C++ Source: https://interactivebrokers.github.io/tws-api/client_wrapper.html Provides an example of implementing the EWrapper interface in C++. ```cpp class TestCppClient : public EWrapper { } ``` -------------------------------- ### Place Midprice Order (C#) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing a Midprice order using C#. The price cap is optional. ```csharp Order order = new Order(); order.Action = action; order.OrderType = "MIDPRICE"; order.TotalQuantity = quantity; order.LmtPrice = priceCap; client.placeOrder(nextOrderId++, ContractSamples.USStockAtSmart(), OrderSamples.Midprice("BUY", 1, 150)); ``` -------------------------------- ### Place Midprice Order (Python) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing a Midprice order using Python. The price cap is optional. ```python 1 order = Order() 2 order.action = action 3 order.orderType = "MIDPRICE" 4 order.totalQuantity = quantity 5 order.lmtPrice = priceCap # optional 1 self.placeOrder(self.nextOrderId(), ContractSamples.USStockAtSmart(), OrderSamples.Midprice("BUY", 1, 150)) ``` -------------------------------- ### Create and Start EReader Thread in C++ Source: https://interactivebrokers.github.io/tws-api/connection.html Initializes a unique pointer to an EReader object and starts it. This setup is part of managing the message reading process in C++. ```cpp m_pReader = std::unique_ptr( new EReader(m_pClient, &m_osSignal) ); m_pReader->start(); ``` -------------------------------- ### Python Order Placement with QBAlgo Source: https://interactivebrokers.github.io/tws-api/qbalgos.html Demonstrates placing an order using a Python helper method for the QBAlgo (STROBE) strategy. It includes setting the contract details and calling the helper to configure the order parameters. ```Python 1 AvailableAlgoParams.FillQBAlgoInLineParams(baseOrder, "10:00:00 US/Eastern", "16:00:00 US/Eastern", -99, "TWAP", 0.25, True) 2 self.placeOrder(self.nextOrderId(), ContractSamples.QBAlgoContract(), baseOrder) ``` -------------------------------- ### Configure Pegged-to-Best Order (Python) Source: https://interactivebrokers.github.io/tws-api/ibkrats.html A Python example for setting up a Pegged-to-Best order. It uses numbered lines for clarity, but standard Python syntax applies. ```python 1 order = Order() 2 order.action = action 3 order.orderType = "PEG BEST" 4 order.lmtPrice = limitPrice 5 order.totalQuantity = quantity 6 order.notHeld = True 7 order.minTradeQty = minTradeQty 8 order.minCompeteSize = minCompeteSize 9 order.competeAgainstBestOffset = competeAgainstBestOffset ``` -------------------------------- ### EClient Functions (Starting with 'r') Source: https://interactivebrokers.github.io/tws-api/functions_0x72.html This section lists EClient functions that start with the letter 'r'. ```APIDOC ## EClient Functions (Starting with 'r') ### Description This is a subset of EClient functions that begin with the letter 'r', covering various request types. ### Functions - **replaceFA()**: Replaces Financial Advisor configuration. - **reqAccountSummary()**: Requests a summary of account information. - **reqAccountUpdates()**: Requests updates for account information. - **reqAccountUpdatesMulti()**: Requests multi-threaded updates for account information. - **reqAllOpenOrders()**: Requests all currently open orders. - **reqAutoOpenOrders()**: Requests auto-open orders. - **reqCompletedOrders()**: Requests a list of completed orders. - **reqContractDetails()**: Requests detailed information about a financial contract. - **reqCurrentTime()**: Requests the current time from the TWS. - **reqExecutions()**: Requests execution details. - **reqFamilyCodes()**: Requests family codes for financial instruments. - **reqFundamentalData()**: Requests fundamental data for a contract. - **reqGlobalCancel()**: Cancels all orders globally. - **reqHeadTimestamp()**: Requests the head timestamp for historical data. - **reqHistogramData()**: Requests histogram data for a contract. - **reqHistoricalData()**: Requests historical market data. - **reqHistoricalNews()**: Requests historical news articles. - **reqHistoricalTicks()**: Requests historical tick data. - **reqIds()**: Requests a new unique ID. - **reqManagedAccts()**: Requests a list of managed accounts. - **reqMarketDataType()**: Sets the market data type. - **reqMarketDepth()**: Requests market depth (Level 2) data. - **reqMarketRule()**: Requests market rule details. - **reqMatchingSymbols()**: Requests matching symbols for a given input. - **reqMktData()**: Requests real-time market data. - **reqMktDepthExchanges()**: Requests available exchanges for market depth. - **reqNewsArticle()**: Requests a specific news article. - **reqNewsBulletins()**: Requests news bulletins. - **reqNewsProviders()**: Requests a list of available news providers. - **reqOpenOrders()**: Requests all open orders. - **reqPnL()**: Requests Profit and Loss (PnL) information. - **reqPnLSingle()**: Requests single PnL information. - **reqPositions()**: Requests current positions. - **reqPositionsMulti()**: Requests multi-threaded positions. - **reqRealTimeBars()**: Requests real-time bar data. - **reqScannerParameters()**: Requests available parameters for market scanners. - **reqScannerSubscription()**: Subscribes to market scanner results. - **reqSecDefOptParams()**: Requests option parameter definitions. - **reqSmartComponents()**: Requests smart component information. - **reqSoftDollarTiers()**: Requests soft dollar tier information. - **reqTickByTickData()**: Requests tick-by-tick data. - **requestFA()**: Requests Financial Advisor configuration. - **reqUserInfo()**: Requests user information. - **reqWshEventData()**: Requests WSH event data. - **reqWshMetaData()**: Requests WSH metadata. ``` -------------------------------- ### Implement Market Order - VB Source: https://interactivebrokers.github.io/tws-api/basic_orders.html This VB.NET example demonstrates creating a Market order. Set the action, order type to 'MKT', and the total quantity. ```vb Dim order As Order = New Order order.Action = action order.OrderType = "MKT" order.TotalQuantity = quantity ``` -------------------------------- ### IND Formula and Example Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for Indexes (IND) using symbol. Example demonstrates a request for ES. ```text =S[twsuser]|tik!'id[reqId]?req?[symbol]_[SecType]_[exchange]_[currency]_~/ ``` ```text =Ssample123|tik!'id6?req?ES_IND_CME_USD_~/ ``` -------------------------------- ### Place Midprice Order (VB.NET) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing a Midprice order using VB.NET. The price cap is optional. ```vbnet Dim order As Order = New Order order.Action = action order.OrderType = "MIDPRICE" order.TotalQuantity = quantity order.LmtPrice = priceCap ' optional client.placeOrder(increment(nextOrderId), ContractSamples.USStockAtSmart(), OrderSamples.Midprice("BUY", 1, 150)) ``` -------------------------------- ### STK Formula and Example Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for Stocks (STK) using symbol. Example shows a request for IBKR. ```text =S[twsuser]|tik!'id[reqId]?req?[symbol]_[SecType]_[exchange]_[currency]_~/ ``` ```text =Ssample123|tik!'id2?req?IBKR_STK_SMART_USD_~/ ``` -------------------------------- ### Place VWAP Order Example (Java) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html This Java code snippet demonstrates how to place a VWAP order. It initializes a limit order, configures it with VWAP parameters using FillVwapParams, and then places the order. ```java Order baseOrder = OrderSamples.LimitOrder("BUY", Decimal.get(1000), 1); AvailableAlgoParams.FillVwapParams(baseOrder, 0.2, "09:00:00 US/Eastern", "16:00:00 US/Eastern", true, true, true); client.placeOrder(nextOrderId++, ContractSamples.USStockAtSmart(), baseOrder); ``` -------------------------------- ### C++ Adaptive Algo Implementation Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Provides a C++ example for implementing the Adaptive Algo strategy and setting the 'adaptivePriority'. ```cpp void AvailableAlgoParams::FillAdaptiveParams(Order& baseOrder, std::string priority){ baseOrder.algoStrategy = "Adaptive"; baseOrder.algoParams.reset(new TagValueList()); TagValueSPtr tag1(new TagValue("adaptivePriority", priority)); baseOrder.algoParams->push_back(tag1); } ``` -------------------------------- ### FX Pairs Formula and Example Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for FX Pairs using symbol. Example demonstrates a request for EUR/USD. ```text =S[twsuser]|tik!'id[reqId]?req?[symbol]_[SecType]_[exchange]_[currency]_~/ ``` ```text =Ssample123|tik!'id1?req?EUR_CASH_IDEALPRO_USD_~/ ``` -------------------------------- ### Java Contract and Order Placement with QBAlgo Source: https://interactivebrokers.github.io/tws-api/qbalgos.html Demonstrates how to define a contract for the QBALGO exchange and place an order using the AvailableAlgoParams helper method in Java. Ensure the Contract object is correctly populated before calling placeOrder. ```Java Contract contract = new Contract(); contract.symbol("ES"); contract.secType("FUT"); contract.exchange("QBALGO"); contract.currency("USD"); contract.lastTradeDateOrContractMonth("202003"); ... AvailableAlgoParams.FillQBAlgoInlineParams(baseOrder, "10:00:00 US/Eastern", "16:00:00 US/Eastern", -99, "TWAP", 0.25, true ); client.placeOrder(nextOrderId++, ContractSamples.QBAlgoContract(), baseOrder); ``` -------------------------------- ### Place Midprice Order (C++) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing a Midprice order using C++. The price cap is optional. ```cpp Order order; order.action = action; order.orderType = "MIDPRICE"; order.totalQuantity = quantity; order.lmtPrice = priceCap; // optional m_pClient->placeOrder(m_orderId++, ContractSamples::USStockAtSmart(), OrderSamples::Midprice("BUY", DecimalFunctions::stringToDecimal("1"), 150)); ``` -------------------------------- ### BAG Formula and Example Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for a Basket (BAG) security type, including details for multiple legs. Example shows a complex BAG request. ```text =S[twsuser]|tik!'id[reqId]?req?[symbol]_[SecType]_[exchange]_[currency]_CMBLGS_[num of legs]_[legId]_[legQuantity]_[legAction]_[legExchange]_[legPrice]...CMBLGS_~/ ``` ```text =Ssample123|tik!'id7?req? SPY_BAG_SMART_USD_CMBLGS_2_141149249_1_BUY_SMART_0_141149252_1_SELL_SMART_0_CMBLGS_~/ ``` -------------------------------- ### Configure Pegged-to-Best with Offset Difference (C++ Style) Source: https://interactivebrokers.github.io/tws-api/ibkrats.html C++ style example for Pegged-to-Best orders with UP_TO_MID offset. Note the direct property access and mid-price offset parameters. ```cpp Order order; order.action = action; order.orderType = "PEG BEST"; order.lmtPrice = limitPrice; order.totalQuantity = quantity; order.notHeld = true; order.minTradeQty = minTradeQty; order.minCompeteSize = minCompeteSize; order.competeAgainstBestOffset = COMPETE_AGAINST_BEST_OFFSET_UP_TO_MID; order.midOffsetAtWhole = midOffsetAtWhole; order.midOffsetAtHalf = midOffsetAtHalf; ``` -------------------------------- ### Create and Start EReader Thread in C# Source: https://interactivebrokers.github.io/tws-api/connection.html Instantiates an EReader to consume messages from TWS and starts it. An additional thread is created to process messages from the queue after a signal. ```csharp 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(); ``` -------------------------------- ### FUT Formula and Example (Local Symbol) Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for Futures (FUT) using the contract's local symbol (req2). Example shows a request for ESZ6. ```text =S[twsuser]|tik!'id[reqId]?req2?[symbol]_[SecType]_[exchange]_[currency]_~/ ``` ```text =Ssample123|tik!'id3?req2?ESZ6_FUT_CME_USD_~/ ``` -------------------------------- ### Automatic EReader Start in Python Source: https://interactivebrokers.github.io/tws-api/connection.html In the Python IB API, the EReader is automatically started upon connection within the Client::connect() method. User intervention is not required for this step. ```python # You don't need to run this in your code! self.reader = reader.EReader(self.conn, self.msg_queue) self.reader.start() # start thread ``` -------------------------------- ### Place Order with Accumulate/Distribute Algo (Java) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing an order using the Accumulate/Distribute algo with Java. Ensure the base order and contract details are correctly set up before calling this. ```java Order baseOrder = OrderSamples.LimitOrder("BUY", Decimal.get(1000), 1); // The Time Zone in "startTime" and "endTime" attributes is ignored and always defaulted to GMT AvailableAlgoParams.FillAccumulateDistributeParams(baseOrder, 10, 60, true, true, 1, true, true, "12:00:00", "16:00:00"); client.placeOrder(nextOrderId++, ContractSamples.USStockAtSmart(), baseOrder); ``` -------------------------------- ### Implement Auction Order - C++ Source: https://interactivebrokers.github.io/tws-api/basic_orders.html This C++ example shows how to instantiate and configure an Auction order. Set the action, time-in-force to 'AUC', order type to 'MTL', total quantity, and limit price. ```cpp Order order; order.action = action; order.tif = "AUC"; order.orderType = "MTL"; order.totalQuantity = quantity; order.lmtPrice = price; ``` -------------------------------- ### FOP Formula and Example (Local Symbol) Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for Futures on Options (FOP) using the contract's local symbol (req2). Example shows a request for XTZ6 C1100. ```text =S[twsuser]|tik!'id[reqId]?req2?[symbol]_[SecType]_[exchange]_[currency]_~/ ``` ```text =Ssample123|tik!'id5?req2?XTZ6 C1100_FOP_CME_USD_~/ ``` -------------------------------- ### Configure PctVolPx Strategy Parameters (C++) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Sets up the parameters for the PctVolPx strategy in C++. Ensure all required parameters are correctly formatted and added to the order's algoParams. ```cpp baseOrder.algoStrategy = "PctVolPx"; baseOrder.algoParams.reset(new TagValueList()); TagValueSPtr tag1(new TagValue("pctVol", std::to_string(pctVol))); TagValueSPtr tag2(new TagValue("deltaPctVol", std::to_string(deltaPctVol))); TagValueSPtr tag3(new TagValue("minPctVol4Px", std::to_string(minPctVol4Px))); TagValueSPtr tag4(new TagValue("maxPctVol4Px", std::to_string(maxPctVol4Px))); TagValueSPtr tag5(new TagValue("startTime", startTime)); TagValueSPtr tag6(new TagValue("endTime", endTime)); TagValueSPtr tag7(new TagValue("noTakeLiq", noTakeLiq ? "1" : "0")); baseOrder.algoParams->push_back(tag1); baseOrder.algoParams->push_back(tag2); baseOrder.algoParams->push_back(tag3); baseOrder.algoParams->push_back(tag4); baseOrder.algoParams->push_back(tag5); baseOrder.algoParams->push_back(tag6); baseOrder.algoParams->push_back(tag7); ``` -------------------------------- ### FUT Formula and Example (Underlying Symbol) Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for Futures (FUT) using the underlying's symbol, multiplier, and expiration date (req1). Example shows a request for ES. ```text =S[twsuser]|tik!'id[reqId]?req?[underlying_symbol]_[SecType]_[expiry]_[multiplier]_[exchange]_[currency]_~_~/ ``` ```text =Ssample123|tik!'id3?req?ES_FUT_201612_50_CME_USD_~_~/ ``` -------------------------------- ### Implement Market Order - C++ Source: https://interactivebrokers.github.io/tws-api/basic_orders.html This C++ snippet shows how to create a Market order. Specify the action, order type as 'MKT', and the total quantity. ```cpp Order order; order.action = action; order.orderType = "MKT"; order.totalQuantity = quantity; ``` -------------------------------- ### Place Order with Accumulate/Distribute Algo (C#) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing an order using the Accumulate/Distribute algo with C#. Ensure the base order and contract details are correctly set up before calling this. ```csharp Order baseOrder = OrderSamples.LimitOrder("BUY", 1000, 1); // The Time Zone in "startTime" and "endTime" attributes is ignored and always defaulted to GMT AvailableAlgoParams.FillAccumulateDistributeParams(baseOrder, 10, 60, true, true, 1, true, true, "12:00:00", "16:00:00"); client.placeOrder(nextOrderId++, ContractSamples.USStockAtSmart(), baseOrder); ``` -------------------------------- ### OPT Formula and Example (Underlying Symbol) Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for Options (OPT) using the underlying's symbol, multiplier, expiration date, and strike (req1). Example shows a request for DBK. ```text =S[twsuser]|tik!'id[reqId]?req?[underlying_symbol]_[SecType]_[expiry]_[strike]_[P/C]_[multiplier]_[exchange]_[currency]_~_~/ ``` ```text =Ssample123|tik!'id4?req?DBK_OPT_20221007_13_C_100_EUREX_EUR_~_~/ ``` -------------------------------- ### Fill Time Variant Percentage of Volume Parameters (C#) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Configures an order to use the PctVolTm strategy with specified start and end percentages of volume, start and end times, and a no-take-liquidity flag. ```csharp public static void FillTimeVariantPctVolParams(Order baseOrder, double startPctVol, double endPctVol, String startTime, String endTime, bool noTakeLiq) { baseOrder.AlgoStrategy = "PctVolTm"; baseOrder.AlgoParams = new List(); baseOrder.AlgoParams.Add(new TagValue("startPctVol", startPctVol.ToString())); baseOrder.AlgoParams.Add(new TagValue("endPctVol", endPctVol.ToString())); baseOrder.AlgoParams.Add(new TagValue("startTime", startTime)); baseOrder.AlgoParams.Add(new TagValue("endTime", endTime)); baseOrder.AlgoParams.Add(new TagValue("noTakeLiq", noTakeLiq ? "1" : "0")); } ``` -------------------------------- ### C# Adaptive Algo Implementation Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Demonstrates how to set up an order with the Adaptive Algo strategy and 'adaptivePriority' in C#. ```csharp public static void FillAdaptiveParams(Order baseOrder, string priority) { baseOrder.AlgoStrategy = "Adaptive"; baseOrder.AlgoParams = new List(); baseOrder.AlgoParams.Add(new TagValue("adaptivePriority", priority)); } ``` -------------------------------- ### Create and Start EReader Thread in Java Source: https://interactivebrokers.github.io/tws-api/connection.html Initializes an EReader with the client and signal, then starts it. A new thread is created to continuously wait for signals and process messages from the queue, handling potential exceptions. ```java final EReader reader = new EReader(m_client, m_signal); reader.start(); //An additional thread is created in this program design to empty the messaging queue new Thread(() -> { while (m_client.isConnected()) { m_signal.waitForSignal(); try { reader.processMsgs(); } catch (Exception e) { System.out.println("Exception: "+e.getMessage()); } } }).start(); ``` -------------------------------- ### Implement Auction Order - Java Source: https://interactivebrokers.github.io/tws-api/basic_orders.html This Java snippet demonstrates how to set up an Auction order. Key parameters include action, time-in-force ('AUC'), order type ('MTL'), quantity, and limit price. ```java Order order = new Order(); order.action(action); order.tif("AUC"); order.orderType("MTL"); order.totalQuantity(quantity); order.lmtPrice(price); ``` -------------------------------- ### Place Order with Accumulate/Distribute Algo (VB.NET) Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Example of placing an order using the Accumulate/Distribute algo with VB.NET. Ensure the base order and contract details are correctly set up before calling this. ```vbnet Dim baseOrder As Order = OrderSamples.LimitOrder("BUY", 1000, 1) ' The Time Zone in "startTime" and "endTime" attributes is ignored and always defaulted to GMT AvailableAlgoParams.FillAccumulateDistributeParams(baseOrder, 10, 60, True, True, 1, True, True, "12:00:00", "16:00:00") client.placeOrder(increment(nextOrderId), ContractSamples.USStockAtSmart(), baseOrder) ``` -------------------------------- ### FOP Formula and Example (Underlying Symbol) Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for Futures on Options (FOP) using the underlying's symbol, multiplier, expiration date, and strike (req1). Example shows a request for EUR. ```text =S[twsuser]|tik!'id[reqId]?req?[underlying_symbol]_[SecType]_[expiry]_[strike]_[P/C]_[multiplier]_[exchange]_[currency]_~_[tradingClass]/ ``` ```text =Ssample123|tik!'id5?req?EUR_FOP_20161209_1.1_C_125000_CME_USD_~_XT/ ``` -------------------------------- ### PctVol Algorithm Setup in C++ Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Configures an order with the PctVol algorithm strategy and its parameters in C++. It initializes the strategy and adds specific parameters like percentage, start/end times, and no-take-liquidity flag. ```cpp void AvailableAlgoParams::FillPctVolParams(Order& baseOrder, double pctVol, std::string startTime, std::string endTime, bool noTakeLiq){ baseOrder.algoStrategy = "PctVol"; baseOrder.algoParams.reset(new TagValueList()); TagValueSPtr tag1(new TagValue("pctVol", std::to_string(pctVol))); TagValueSPtr tag2(new TagValue("startTime", startTime)); TagValueSPtr tag3(new TagValue("endTime", endTime)); TagValueSPtr tag4(new TagValue("noTakeLiq", noTakeLiq ? "1" : "0")); baseOrder.algoParams->push_back(tag1); baseOrder.algoParams->push_back(tag2); baseOrder.algoParams->push_back(tag3); baseOrder.algoParams->push_back(tag4); } ``` -------------------------------- ### OPT Formula and Example (Local Symbol) Source: https://interactivebrokers.github.io/tws-api/dde_reference.html Formula for Options (OPT) using the contract's local symbol (req2). Example shows a request for C DBK DEC 22 1300. ```text =S[twsuser]|tik!'id[reqId]?req2?[symbol]_[SecType]_[exchange]_[currency]_~/ ``` ```text =Ssample123|tik!'id4?req2?C DBK DEC 22 1300_OPT_EUREX_EUR_~/ ``` -------------------------------- ### Implement Market Order - C# Source: https://interactivebrokers.github.io/tws-api/basic_orders.html This C# snippet shows how to create a Market order. It requires specifying the action, order type as 'MKT', and the total quantity. ```csharp Order order = new Order(); order.Action = action; order.OrderType = "MKT"; order.TotalQuantity = quantity; ``` -------------------------------- ### Create and Start EReader Thread in VB.NET Source: https://interactivebrokers.github.io/tws-api/connection.html Creates a new thread for message processing. The thread is set as a background thread and started only if the server version is greater than 0. The message processing logic is defined in a separate subroutine. ```vbnet 'Once the messages are in the queue, an additional thread need to fetch them Dim msgThread As Thread = New Thread(AddressOf messageProcessing) msgThread.IsBackground = True If (wrapperImpl.serverVersion() > 0) Then Call msgThread.Start() ... Private Sub messageProcessing() Dim reader As EReader = New EReader(wrapperImpl.socketClient, wrapperImpl.eReaderSignal) reader.Start() While (wrapperImpl.socketClient.IsConnected) wrapperImpl.eReaderSignal.waitForSignal() reader.processMsgs() End While End Sub ``` -------------------------------- ### Request Account Summary with Python (LEDGER:ALL) Source: https://interactivebrokers.github.io/tws-api/account_summary.html Example of requesting all ledger data for all accounts and currencies using Python. ```Python 1 self.reqAccountSummary(9004, "All", "$LEDGER:ALL") ``` -------------------------------- ### serverVersion Source: https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClient-members.html Gets the current server version. ```APIDOC ## serverVersion ### Description Gets the current server version. ### Method (Not specified, likely internal) ### Parameters None ``` -------------------------------- ### Create and Configure VolumeCondition (C#) Source: https://interactivebrokers.github.io/tws-api/order_conditions.html Demonstrates creating a VolumeCondition and setting its properties for volume-based order rules. Use this for C# implementations. ```csharp VolumeCondition volCond = (VolumeCondition)OrderCondition.Create(OrderConditionType.Volume); //Whenever contract... volCond.ConId = conId; //When traded at volCond.Exchange = exchange; //reaches a volume higher/lower volCond.IsMore = isMore; //than this... volCond.Volume = volume; //AND | OR next condition (will be ignored if no more conditions are added) volCond.IsConjunctionConnection = isConjunction; ``` -------------------------------- ### startApi Source: https://interactivebrokers.github.io/tws-api/functions_func.html Starts the API connection. This function is part of the EClient class. ```APIDOC ## startApi ### Description Starts the API connection. This function is part of the EClient class. ### Method Not specified (assumed to be a client-side method call) ### Endpoint Not applicable (client-side function) ### Parameters None explicitly listed in the source. ### Request Example ```APIDOC // Example usage would depend on the specific TWS API client implementation client.startApi() ``` ### Response Not specified. The return type is EClient, indicating it's a method of the EClient class. ``` -------------------------------- ### Python Pegged-to-Midpoint Order Source: https://interactivebrokers.github.io/tws-api/ibkrats.html Example of creating a Pegged-to-Midpoint order in Python. ```python order = Order() order.action = action order.orderType = "PEG MID" order.lmtPrice = limitPrice order.totalQuantity = quantity order.notHeld = True order.minTradeQty = minTradeQty order.midOffsetAtWhole = midOffsetAtWhole order.midOffsetAtHalf = midOffsetAtHalf; ``` -------------------------------- ### Place Jefferies VWAP Order (Java) Source: https://interactivebrokers.github.io/tws-api/jefferies.html Example of setting up a contract and placing a Jefferies VWAP order using the FillJefferiesVWAPParams helper function. The contract must be routed to JEFFALGO. ```java Contract contract = new Contract(); contract.symbol("AAPL"); contract.secType("STK"); contract.exchange("JEFFALGO"); // must be direct-routed to JEFFALGO contract.currency("USD"); // only available for US stocks ... AvailableAlgoParams.FillJefferiesVWAPParams(baseOrder, "10:00:00 US/Eastern", "16:00:00 US/Eastern", 10, 10, "Exclude_Both", 130, 135, 1, 10, "Patience", false, "Midpoint"); client.placeOrder(nextOrderId++, ContractSamples.JefferiesContract(), baseOrder); ... ``` -------------------------------- ### VB.NET Pegged-to-Midpoint Order Source: https://interactivebrokers.github.io/tws-api/ibkrats.html Example of creating a Pegged-to-Midpoint order in VB.NET. ```vbnet Dim order As Order = New Order order.Action = action order.OrderType = "PEG MID" order.LmtPrice = limitPrice order.TotalQuantity = quantity order.NotHeld = True order.MinTradeQty = minTradeQty order.MidOffsetAtWhole = midOffsetAtWhole order.MidOffsetAtHalf = midOffsetAtHalf; ``` -------------------------------- ### PctVol Algorithm Setup in C# Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Sets up the PctVol algorithm strategy and parameters on a base Order object. This method is typically called before placing an order. ```csharp public static void FillPctVolParams(Order baseOrder, double pctVol, string startTime, string endTime, bool noTakeLiq) { baseOrder.AlgoStrategy = "PctVol"; baseOrder.AlgoParams = new List(); baseOrder.AlgoParams.Add(new TagValue("pctVol", pctVol.ToString())); baseOrder.AlgoParams.Add(new TagValue("startTime", startTime)); baseOrder.AlgoParams.Add(new TagValue("endTime", endTime)); baseOrder.AlgoParams.Add(new TagValue("noTakeLiq", noTakeLiq ? "1" : "0")); } ``` -------------------------------- ### C# Pegged-to-Midpoint Order Source: https://interactivebrokers.github.io/tws-api/ibkrats.html Example of creating a Pegged-to-Midpoint order in C#. ```csharp Order order = new Order(); order.Action = action; order.OrderType = "PEG MID"; order.LmtPrice = limitPrice; order.TotalQuantity = quantity; order.NotHeld = true; order.MinTradeQty = minTradeQty; order.MidOffsetAtWhole = midOffsetAtWhole; order.MidOffsetAtHalf = midOffsetAtHalf; ``` -------------------------------- ### Place Jefferies VWAP Order (C#) Source: https://interactivebrokers.github.io/tws-api/jefferies.html Example of setting up a contract and placing a Jefferies VWAP order using the FillJefferiesVWAPParams helper function. The contract must be routed to JEFFALGO. ```csharp Contract contract = new Contract(); contract.Symbol = "AAPL"; contract.SecType = "STK"; contract.Exchange = "JEFFALGO"; // must be direct-routed to JEFFALGO contract.Currency = "USD"; // only available for US stocks ... AvailableAlgoParams.FillJefferiesVWAPParams(baseOrder, "10:00:00 US/Eastern", "16:00:00 US/Eastern", 10, 10, "Exclude_Both", 130, 135, 1, 10, "Patience", false, "Midpoint"); client.placeOrder(nextOrderId++, ContractSamples.JefferiesContract(), baseOrder); ... ``` -------------------------------- ### Request Histogram Data (C++) Source: https://interactivebrokers.github.io/tws-api/histograms.html Example of requesting histogram data in C++. ```cpp m_pClient->reqHistogramData(15001, ContractSamples::IBMUSStockAtSmart(), false, "1 weeks"); ``` -------------------------------- ### Place US Stock Limit Order (Python Example) Source: https://interactivebrokers.github.io/tws-api/order_submission.html Submits a SELL order for a US stock with a limit price using Python. Ensure `nextOrderId` is managed correctly. ```Python 1 self.simplePlaceOid = self.nextOrderId() 2 self.placeOrder(self.simplePlaceOid, ContractSamples.USStock(), 3 OrderSamples.LimitOrder("SELL", 1, 50)) ``` -------------------------------- ### Request Histogram Data (C#) Source: https://interactivebrokers.github.io/tws-api/histograms.html Example of requesting histogram data in C#. ```csharp client.reqHistogramData(15001, ContractSamples.USStockWithPrimaryExch(), false, "1 week"); ``` -------------------------------- ### reqScannerSubscription (overload) Source: https://interactivebrokers.github.io/tws-api/classIBApi_1_1EClientSocket.html Starts a subscription to market scan results based on the provided parameters. ```APIDOC ## reqScannerSubscription ### Description Starts a subscription to market scan results based on the provided parameters. ### Method void ### Endpoint N/A (SDK Method) ### Parameters * **reqId** (int) - Description not provided. * **subscription** (ScannerSubscription) - Description not provided. * **scannerSubscriptionOptions** (string) - Description not provided. * **scannerSubscriptionFilterOptions** (string) - Description not provided. ``` -------------------------------- ### PctVol Algorithm Setup in Java Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Initializes and populates the PctVol algorithm parameters for an order in Java. It sets the strategy name and adds specific parameters as TagValue objects. ```java public static void FillPctVolParams(Order baseOrder, double pctVol, String startTime, String endTime, boolean noTakeLiq) { baseOrder.algoStrategy("PctVol"); baseOrder.algoParams(new ArrayList<>()); baseOrder.algoParams().add(new TagValue("pctVol", String.valueOf(pctVol))); baseOrder.algoParams().add(new TagValue("startTime", startTime)); baseOrder.algoParams().add(new TagValue("endTime", endTime)); baseOrder.algoParams().add(new TagValue("noTakeLiq", noTakeLiq ? "1" : "0")); } ``` -------------------------------- ### Python rerouteMktDepthReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market depth requests in Python. ```python def rerouteMktDepthReq(self, reqId: int, conId: int, exchange: str): super().rerouteMktDataReq(reqId, conId, exchange) print("Re-route market depth request. ReqId:", reqId, "ConId:", conId, "Exchange:", exchange) ``` -------------------------------- ### Request Account Summary with C++ (LEDGER:ALL) Source: https://interactivebrokers.github.io/tws-api/account_summary.html Example of requesting all ledger data for all accounts and currencies using C++. ```C++ m_pClient->reqAccountSummary(9004, "All", "$LEDGER:ALL"); ``` -------------------------------- ### C++: Configure Arrival Price Order Parameters Source: https://interactivebrokers.github.io/tws-api/ibalgos.html Use this C++ function to set up an Order object with parameters for the Arrival Price algorithm strategy. It configures parameters like maximum percentage of volume, risk aversion, start and end times, and completion settings. ```cpp void AvailableAlgoParams::FillArrivalPriceParams(Order& baseOrder, double maxPctVol, std::string riskAversion, std::string startTime, std::string endTime, bool forceCompletion, bool allowPastTime){ baseOrder.algoStrategy = "ArrivalPx"; baseOrder.algoParams.reset(new TagValueList()); TagValueSPtr tag1(new TagValue("maxPctVol", std::to_string(maxPctVol))); TagValueSPtr tag2(new TagValue("riskAversion", riskAversion)); TagValueSPtr tag3(new TagValue("startTime", startTime)); TagValueSPtr tag4(new TagValue("endTime", endTime)); TagValueSPtr tag5(new TagValue("forceCompletion", forceCompletion ? "1" : "0")); TagValueSPtr tag6(new TagValue("allowPastEndTime", allowPastTime ? "1" : "0")); baseOrder.algoParams->push_back(tag1); baseOrder.algoParams->push_back(tag2); baseOrder.algoParams->push_back(tag3); baseOrder.algoParams->push_back(tag4); baseOrder.algoParams->push_back(tag5); baseOrder.algoParams->push_back(tag6); } ``` -------------------------------- ### Python rerouteMktDataReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market data requests in Python. ```python def rerouteMktDataReq(self, reqId: int, conId: int, exchange: str): super().rerouteMktDataReq(reqId, conId, exchange) print("Re-route market data request. ReqId:", reqId, "ConId:", conId, "Exchange:", exchange) ``` -------------------------------- ### C++ rerouteMktDepthReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market depth requests in C++. ```cpp void TestCppClient::rerouteMktDepthReq(int reqId, int conid, const std::string& exchange) { printf( "Re-route market depth request. ReqId: %d, ConId: %d, Exchange: %s\n", reqId, conid, exchange.c_str()); } ``` -------------------------------- ### Create Relative Market Combo Order (C++) Source: https://interactivebrokers.github.io/tws-api/basic_orders.html This C++ example shows how to initialize a Relative Market Combo order. It includes setting the action, quantity, and order type, along with handling smart combo routing parameters. ```cpp Order order; order.action = action; order.totalQuantity = quantity; order.orderType = "Rel + MKT"; if(nonGuaranteed){ TagValueSPtr tag1(new TagValue("NonGuaranteed", "1")); order.smartComboRoutingParams.reset(new TagValueList()); order.smartComboRoutingParams->push_back(tag1); } ``` -------------------------------- ### C++ rerouteMktDataReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market data requests in C++. ```cpp void TestCppClient::rerouteMktDataReq(int reqId, int conid, const std::string& exchange) { printf( "Re-route market data request. ReqId: %d, ConId: %d, Exchange: %s\n", reqId, conid, exchange.c_str()); } ``` -------------------------------- ### Place US Stock Limit Order (C++ Example) Source: https://interactivebrokers.github.io/tws-api/order_submission.html Submits a SELL order for a US stock with a limit price using C++. Ensure `m_orderId` is managed correctly. ```C++ m_pClient->placeOrder(m_orderId++, ContractSamples::USStock(), OrderSamples::LimitOrder("SELL", DecimalFunctions::stringToDecimal("1"), 50)); ``` -------------------------------- ### Exercise Options (Python - Multi-line) Source: https://interactivebrokers.github.io/tws-api/options.html A multi-line Python example for exercising options, demonstrating the function call spread across two lines for readability. ```python 1 self.exerciseOptions(5003, ContractSamples.OptionWithTradingClass(), 1, 2 1, self.account, 1, "20231018-12:00:00") ``` -------------------------------- ### VB.NET rerouteMktDepthReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market depth requests in VB.NET. ```vbnet Public Sub rerouteMktDepthReq(reqId As Integer, conId As Integer, exchange As String) Implements IBApi.EWrapper.rerouteMktDepthReq Console.WriteLine("Re-route market depth request. Req Id: {0}, Con Id: {1}, Exchange: {2}", reqId, conId, exchange) End Sub ``` -------------------------------- ### Configure Pegged-to-Best Order (VB.NET) Source: https://interactivebrokers.github.io/tws-api/ibkrats.html Example of configuring a Pegged-to-Best order using VB.NET syntax. Properties are assigned directly. ```vbnet Dim order As Order = New Order order.Action = action order.OrderType = "PEG BEST" order.LmtPrice = limitPrice order.TotalQuantity = quantity order.NotHeld = True order.MinTradeQty = minTradeQty order.MinCompeteSize = minCompeteSize order.CompeteAgainstBestOffset = competeAgainstBestOffset ``` -------------------------------- ### VB.NET rerouteMktDataReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market data requests in VB.NET. ```vbnet Public Sub rerouteMktDataReq(reqId As Integer, conId As Integer, exchange As String) Implements IBApi.EWrapper.rerouteMktDataReq Console.WriteLine("Re-route market data request. Req Id: {0}, Con Id: {1}, Exchange: {2}", reqId, conId, exchange) End Sub ``` -------------------------------- ### Python: Configure Arrival Price Order Parameters Source: https://interactivebrokers.github.io/tws-api/ibalgos.html This Python static method configures an Order object for the Arrival Price algorithm. It sets the strategy and appends various parameters including volume percentage, risk aversion, and time constraints. ```python @staticmethod def FillArrivalPriceParams(baseOrder: Order, maxPctVol: float, riskAversion: str, startTime: str, endTime: str, forceCompletion: bool, allowPastTime: bool): baseOrder.algoStrategy = "ArrivalPx" baseOrder.algoParams = [] baseOrder.algoParams.append(TagValue("maxPctVol", maxPctVol)) baseOrder.algoParams.append(TagValue("riskAversion", riskAversion)) baseOrder.algoParams.append(TagValue("startTime", startTime)) baseOrder.algoParams.append(TagValue("endTime", endTime)) baseOrder.algoParams.append(TagValue("forceCompletion", int(forceCompletion))) baseOrder.algoParams.append(TagValue("allowPastEndTime", int(allowPastTime))) ``` -------------------------------- ### Java rerouteMktDepthReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market depth requests in Java. ```java @Override public void rerouteMktDepthReq(int reqId, int conId, String exchange) { System.out.println(EWrapperMsgGenerator.rerouteMktDepthReq(reqId, conId, exchange)); } ``` -------------------------------- ### Java rerouteMktDataReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market data requests in Java. ```java @Override public void rerouteMktDataReq(int reqId, int conId, String exchange) { System.out.println(EWrapperMsgGenerator.rerouteMktDataReq(reqId, conId, exchange)); } ``` -------------------------------- ### C# rerouteMktDepthReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market depth requests in C#. ```csharp public void rerouteMktDepthReq(int reqId, int conId, string exchange) { Console.WriteLine("Re-route market depth request. Req Id: {0}, ConId: {1}, Exchange: {2}", reqId, conId, exchange); } ``` -------------------------------- ### Subscribe to Account Updates (C++) Source: https://interactivebrokers.github.io/tws-api/account_updates.html Initiates a subscription to receive account and portfolio information. Use 'true' to start the subscription and provide the account ID. Updates occur every three minutes unless there's a position change. ```cpp m_pClient->reqAccountUpdates(true, "U150462"); ``` -------------------------------- ### Create and Configure VolumeCondition (Java) Source: https://interactivebrokers.github.io/tws-api/order_conditions.html Shows how to instantiate a VolumeCondition and chain method calls to set contract ID, exchange, volume, and conjunction parameters. Suitable for Java. ```java VolumeCondition volCon = (VolumeCondition)OrderCondition.create(OrderConditionType.Volume); //Whenever contract... volCon.conId(conId); //When traded at volCon.exchange(exchange); //reaches a volume higher/lower volCon.isMore(isMore); //than this... volCon.volume(volume); //AND | OR next condition (will be ignored if no more conditions are added) volCon.conjunctionConnection(isConjunction); ``` -------------------------------- ### C# rerouteMktDataReq Example Source: https://interactivebrokers.github.io/tws-api/md_receive.html Callback function for re-routing market data requests in C#. ```csharp public void rerouteMktDataReq(int reqId, int conId, string exchange) { Console.WriteLine("Re-route market data request. Req Id: {0}, ConId: {1}, Exchange: {2}", reqId, conId, exchange); } ``` -------------------------------- ### Python Auction Relative Order Source: https://interactivebrokers.github.io/tws-api/basic_orders.html Example of creating an Auction Relative order in Python. ```python 1 order = Order() 2 order.action = action 3 order.orderType = "REL" 4 order.totalQuantity = quantity 5 order.auxPrice = offset ```