### InterReactClient Creation Example Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/InterReactOptions.md Demonstrates how to create an InterReactClient with default or custom InterReactOptions. ```APIDOC ## Usage Example ```csharp using System.Net; using InterReact; // Minimal configuration (uses defaults) var client = await InterReactClient.CreateAsync(); // Custom configuration var client = await InterReactClient.CreateAsync(options => { // Connect to remote TWS instance options.TwsIpAddress = IPAddress.Parse("192.168.1.100"); // Try specific ports in order options.TwsPortAddresses = new[] { 7496, 7497 }; // Set explicit client ID options.TwsClientId = 2; // Enable order placement options.AllowOrderPlacement = true; // Use real ticks instead of delayed ticks options.UseDelayedTicks = false; // Add custom logging options.LogFactory = new CustomLoggerFactory(); }); ``` ``` -------------------------------- ### Request All Account Positions Source: https://github.com/dshe/interreact/blob/master/_autodocs/README.md Demonstrates fetching all account positions asynchronously. Use this to get a snapshot of current positions. ```csharp var positions = await client.Service.GetAccountPositionsAsync(); ``` -------------------------------- ### Cancel Order Example Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/OrderMonitor.md Shows how to explicitly cancel an order using the CancelOrderAsync method after it has been placed. ```csharp var monitor = await client.Service.PlaceOrderAsync(order, contract); // Later: cancel await monitor.CancelOrderAsync(); ``` -------------------------------- ### Subscribe to Market Data Ticks Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Subscribe to real-time market data for a specific contract. This example filters for the last price tick. ```csharp using System.Reactive.Linq; // Define contract var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "AAPL", Currency = "USD", Exchange = "SMART" }; // Subscribe to ticks var subscription = client.Service .CreateMarketDataObservable(contract) .OfTickClass(selector => selector.PriceTick) .Where(tick => tick.TickType == TickType.LastPrice) .Subscribe( onNext: tick => Console.WriteLine($"Last: {tick.Price}"), onError: ex => Console.WriteLine($"Error: {ex}"), onCompleted: () => Console.WriteLine("Completed")); // Unsubscribe when done subscription.Dispose(); ``` -------------------------------- ### OrderMonitor Usage Example Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/OrderMonitor.md Demonstrates placing an order, subscribing to various message types (OrderStatusReport, Execution, CommissionReport, Alert), modifying and replacing the order, and finally cancelling it. Ensure proper disposal of subscriptions and the monitor itself. ```csharp using System; using System.Reactive.Linq; using InterReact; var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "AMZN", Currency = "USD", Exchange = "SMART" }; var order = new Order { Action = OrderAction.Buy, TotalQuantity = 100, OrderType = OrderTypes.Limit, LimitPrice = 150.00, TimeInForce = OrderTimeInForce.GoodTillCanceled }; // Place order var monitor = await client.Service.PlaceOrderAsync(order, contract); Console.WriteLine($"Placed order {monitor.OrderId}"); // Subscribe to status updates var statusSubscription = monitor.Messages .OfType() .Subscribe(status => { Console.WriteLine($"Order {monitor.OrderId}: {status.Status}"); Console.WriteLine($" Filled: {status.Filled}/{status.Filled + status.Remaining}"); Console.WriteLine($" Avg Price: {status.AverageFillPrice}"); }); // Subscribe to executions var execSubscription = monitor.Messages .OfType() .Subscribe(exec => { Console.WriteLine($"Execution: {exec.Shares} @ {exec.Price}"); }); // Subscribe to commissions var commissionSubscription = monitor.Messages .OfType() .Subscribe(commission => { Console.WriteLine($"Commission: {commission.Commission} {commission.CurrencyId}"); }); // Monitor for errors var alertSubscription = monitor.Messages .OfType() .Subscribe(alert => { Console.WriteLine($"Alert: {alert.Code} - {alert.Message}"); }); // Let order fill... await Task.Delay(5000); // Modify and replace order monitor.Order.LimitPrice = 155.00; await monitor.ReplaceOrderAsync(); Console.WriteLine("Order replaced"); // Later: cancel order await monitor.CancelOrderAsync(); Console.WriteLine("Order cancelled"); // Cleanup statusSubscription.Dispose(); execSubscription.Dispose(); commissionSubscription.Dispose(); alertSubscription.Dispose(); await monitor.DisposeAsync(); ``` -------------------------------- ### Get All Account Positions Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Service.md Retrieves all current account positions as an array. Use this to get a static list of all your positions at a specific point in time. ```csharp public async Task GetAccountPositionsAsync( TimeSpan? timeout = null, CancellationToken ct = default) ``` ```csharp var positions = await client.Service.GetAccountPositionsAsync( timeout: TimeSpan.FromSeconds(10)); foreach (var pos in positions) { Console.WriteLine($"{pos.Contract.Symbol}: {pos.Quantity} @ {pos.AverageCost}"); } ``` -------------------------------- ### Define an Option Contract Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Constants.md Use ContractSecurityType.Option along with ContractOptionRight.Call or ContractOptionRight.Put to define an option contract. This example demonstrates initializing an option contract with its strike price and right. ```csharp var contract = new Contract { SecurityType = ContractSecurityType.Option, Symbol = "SPY", LastTradeDateOrContractMonth = "202403", Strike = 450.0, Right = ContractOptionRight.Call, Currency = "USD", Exchange = "CBOE" }; ``` -------------------------------- ### Get Account Positions Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Retrieve all account positions. A timeout can be specified for the request. ```csharp // Get all positions try { var positions = await client.Service.GetAccountPositionsAsync( timeout: TimeSpan.FromSeconds(10)); foreach (var pos in positions) { Console.WriteLine($"{pos.Account}: {pos.Contract.Symbol} x {pos.Quantity}"); } } catch (TimeoutException) { Console.WriteLine("Request timeout"); } ``` -------------------------------- ### ArgumentException Trigger Examples Source: https://github.com/dshe/interreact/blob/master/_autodocs/errors.md Shows common cases where ArgumentException is thrown due to invalid argument values in InterReact methods. This includes incorrect date/time combinations or invalid contract properties. ```csharp // Examples await request.RequestHistoricalDataAsync(id, contract, "2024-01-01", "1 year", keepUpToDate: true); // Throws: endDateTime specified with keepUpToDate=true service.CreateContractDetailsObservable(contract); // contract has ComboLegs // Throws: Contract must not include ComboLegs ``` -------------------------------- ### Modify and Replace Order Example Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/OrderMonitor.md Illustrates modifying the order properties directly on the Order object and then calling ReplaceOrderAsync to resubmit it with the updated details. ```csharp var monitor = await client.Service.PlaceOrderAsync(order, contract); // Later: modify and replace monitor.Order.TotalQuantity = 200; monitor.Order.LimitPrice = 155.00; await monitor.ReplaceOrderAsync(); ``` -------------------------------- ### Get Market Data Snapshot Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Retrieve a snapshot of market data for a given contract. This is useful for obtaining current tick data without establishing a continuous subscription. ```csharp var snapshot = await client.Service.GetMarketDataSnapshotAsync( contract, timeout: TimeSpan.FromSeconds(5)); foreach (var tick in snapshot) { Console.WriteLine($"{tick.GetType().Name}: {tick}"); } ``` -------------------------------- ### Handle Request-Specific AlertException Source: https://github.com/dshe/interreact/blob/master/_autodocs/errors.md Catch and inspect AlertException for request-specific errors. This example uses a switch statement to handle different alert codes. ```csharp try { var details = await client.Service.GetContractDetailsAsync( new Contract { Symbol = "INVALID_SYMBOL", ... }); } catch (AlertException ex) { switch (ex.AlertMessage.Code) { case 200: Console.WriteLine("No security definition found"); break; case 321: Console.WriteLine("Cannot find EFP contract"); break; default: Console.WriteLine($"Unknown error: {ex.AlertMessage.Message}"); break; } } ``` -------------------------------- ### Get Contract Details Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Retrieve detailed information for a given contract selector. This is useful for validating contract parameters and discovering available fields. ```csharp // Specify partial contract var selector = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "MSFT", Currency = "USD", Exchange = "SMART" }; // Get all matching contracts try { var details = await client.Service.GetContractDetailsAsync(selector); foreach (var detail in details) { Console.WriteLine($"ContractId: {detail.Contract.ContractId}"); Console.WriteLine($"MinTick: {detail.MinTick}"); } } catch (Exception ex) { Console.WriteLine($"Error: {ex}"); } ``` -------------------------------- ### Request Historical Data Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Request historical bar data for a specified contract and duration. This example requests one-hour bars for the past month. ```csharp var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "GOOGL", Currency = "USD", Exchange = "SMART" }; int requestId = client.Request.GetNextId(); await client.Request.RequestHistoricalDataAsync( requestId: requestId, contract: contract, endDateTime: "", // Current time duration: HistoricalDataDuration.OneMonth, barSize: HistoricalDataBarSize.OneHour, whatToShow: HistoricalDataWhatToShow.Trades); // Subscribe to bars client.Service.Request.Response .OfType() .Where(bar => bar.RequestId == requestId) .Subscribe(bar => Console.WriteLine($"{bar.Time}: O={bar.Open} H={bar.High} L={bar.Low} C={bar.Close}")); ``` -------------------------------- ### ArgumentNullException Trigger Examples Source: https://github.com/dshe/interreact/blob/master/_autodocs/errors.md Illustrates scenarios where ArgumentNullException is thrown due to null arguments being passed to InterReact methods. Ensure that required parameters like contract or order objects are not null. ```csharp // Thrown if contract or order is null await request.PlaceOrderAsync(orderId, null, contract); // throws await request.RequestContractDetailsAsync(requestId, null); // throws ``` -------------------------------- ### InvalidOperationException Trigger Examples Source: https://github.com/dshe/interreact/blob/master/_autodocs/errors.md Demonstrates situations that lead to InvalidOperationException in InterReact, such as attempting to place orders without enabling the option or accessing properties of a null client instance. ```csharp // Order placement disabled await request.PlaceOrderAsync(orderId, order, contract); // Throws: "To place orders, first set Options.AllowOrderPlacement to true." // Using NullInterReactClient var client = NullInterReactClient.Instance; _ = client.RemoteIpEndPoint; // throws ``` -------------------------------- ### InterReactClient Creation with Minimal Configuration Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/InterReactOptions.md Demonstrates creating an InterReactClient using default configuration options. No explicit options need to be provided. ```csharp using System.Net; using InterReact; // Minimal configuration (uses defaults) var client = await InterReactClient.CreateAsync(); ``` -------------------------------- ### Connecting to TWS/Gateway with InterReactClient Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/IInterReactClient.md Demonstrates how to create a client instance using default connection settings or with custom configurations for IP address, ports, client ID, and order placement permissions. Ensure to dispose the client when done. ```csharp using InterReact; // Simple connection with defaults (localhost, port 7496 or 7497) IInterReactClient client = await InterReactClient.CreateAsync(); // Custom configuration IInterReactClient client = await InterReactClient.CreateAsync(options => { options.TwsIpAddress = IPAddress.Parse("192.168.1.100"); options.TwsPortAddresses = new[] { 7496, 7497 }; options.TwsClientId = 1; options.AllowOrderPlacement = true; }); try { // Use client... } finally { await client.DisposeAsync(); } ``` -------------------------------- ### Get Managed Accounts Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Service.md Retrieves a list of accounts managed by the current login. Use this method to get a list of account IDs associated with your trading credentials. ```csharp public async Task> GetManagedAccountsAsync( TimeSpan? timeout = null, CancellationToken ct = default) ``` ```csharp var accounts = await client.Service.GetManagedAccountsAsync(); Console.WriteLine($"Managed accounts: {string.Join(", ", accounts)}"); ``` -------------------------------- ### Connect to Localhost with Default Configuration Source: https://github.com/dshe/interreact/blob/master/_autodocs/configuration.md Connect to a local TWS/Gateway instance using the default configuration settings. ```csharp // Connect to localhost TWS/Gateway using defaults IInterReactClient client = await InterReactClient.CreateAsync(); ``` -------------------------------- ### InterReactClient Creation with Custom Configuration Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/InterReactOptions.md Shows how to create an InterReactClient with custom connection parameters, client ID, order placement permissions, tick usage, and logging. ```csharp using System.Net; using InterReact; // Custom configuration var client = await InterReactClient.CreateAsync(options => { // Connect to remote TWS instance options.TwsIpAddress = IPAddress.Parse("192.168.1.100"); // Try specific ports in order options.TwsPortAddresses = new[] { 7496, 7497 }; // Set explicit client ID options.TwsClientId = 2; // Enable order placement options.AllowOrderPlacement = true; // Use real ticks instead of delayed ticks options.UseDelayedTicks = false; // Add custom logging options.LogFactory = new CustomLoggerFactory(); }); ``` -------------------------------- ### Enable Order Placement and Console Logging Source: https://github.com/dshe/interreact/blob/master/_autodocs/configuration.md Configure the client to allow order placement and set up built-in console logging with a specified minimum log level. ```csharp using Microsoft.Extensions.Logging; IInterReactClient client = await InterReactClient.CreateAsync(options => { options.AllowOrderPlacement = true; // Use built-in console logging var logFactory = LoggerFactory.Create(builder => builder.AddConsole().SetMinimumLevel(LogLevel.Debug)); options.LogFactory = logFactory; }); ``` -------------------------------- ### Create and Connect Client Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Instantiate an InterReact client and establish a connection to the TWS or Gateway. Ensure the client is disposed of properly. ```csharp using System; using InterReact; // Create and connect client (defaults to localhost, port 7496) IInterReactClient client = await InterReactClient.CreateAsync(); try { // Use client... } finally { await client.DisposeAsync(); } ``` -------------------------------- ### Configure InterReact Client with Options Source: https://github.com/dshe/interreact/blob/master/_autodocs/configuration.md Configure the InterReact client by passing an action delegate to `InterReactClient.CreateAsync` to set various options such as IP address, ports, client ID, order placement, delayed ticks, and logging. ```csharp IInterReactClient client = await InterReactClient.CreateAsync(options => { options.TwsIpAddress = IPAddress.Parse("192.168.1.100"); options.TwsPortAddresses = new[] { 7496, 7497 }; options.TwsClientId = 1; options.AllowOrderPlacement = true; options.UseDelayedTicks = false; options.LogFactory = new MyLoggerFactory(); }); ``` -------------------------------- ### Place and Monitor an Order Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Service.md Places an order for a contract and returns an OrderMonitor to track its status and allow cancellation. Requires `InterReactOptions.AllowOrderPlacement = true`. ```csharp public async ValueTask PlaceOrderAsync( Order order, Contract contract) ``` ```csharp var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "AMZN", Currency = "USD", Exchange = "SMART" }; var order = new Order { Action = OrderAction.Buy, TotalQuantity = 50, OrderType = OrderTypes.Limit, LimitPrice = 150.00 }; var monitor = await client.Service.PlaceOrderAsync(order, contract); monitor.Messages .OfType() .Subscribe(status => Console.WriteLine($"Order {monitor.OrderId}: {status.Status}")); // Later: cancel the order await monitor.CancelOrderAsync(); ``` -------------------------------- ### ExerciseOptionsAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Exercises options based on specified parameters. ```APIDOC ## ExerciseOptionsAsync ### Description Exercises options based on specified parameters. ### Method `ExerciseOptionsAsync(int requestId, Contract contract, OptionExerciseAction exerciseAction, int exerciseQuantity, string account, bool overrideOrder)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **requestId** (int) - Required - The ID for the option exercise request. - **contract** (Contract) - Required - The option contract to exercise. - **exerciseAction** (OptionExerciseAction) - Required - The action to perform for exercising options. - **exerciseQuantity** (int) - Required - The quantity of options to exercise. - **account** (string) - Required - The account to exercise the options under. - **overrideOrder** (bool) - Required - Whether to override existing order settings. ``` -------------------------------- ### Observable Error Recovery with Catch Source: https://github.com/dshe/interreact/blob/master/_autodocs/errors.md Recover from specific exceptions in an observable stream by using the Catch operator. This example catches AlertException and returns an empty observable. ```csharp client.Service.CreateMarketDataObservable(contract) .Catch((AlertException ex) => { Console.WriteLine($"Error {ex.AlertMessage.Code}: {ex.AlertMessage.Message}"); return Observable.Empty(); }) .Subscribe(tick => Console.WriteLine(tick)); ``` -------------------------------- ### Server Version Negotiation Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/InterReactOptions.md Explains the process of server version negotiation between the client and TWS/Gateway. ```APIDOC ## Server Version Negotiation - Client reports supported version range to TWS during login - TWS selects and reports highest compatible version - Negotiated version is available in `ServerVersionCurrent` (read-only) - Methods check compatibility against current version ``` -------------------------------- ### CreateAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/IInterReactClient.md Factory method to create and connect a new client to TWS/Gateway. It allows for optional configuration of connection options. ```APIDOC ## CreateAsync ### Description Factory method to create and connect a new client to TWS/Gateway. ### Method `static async Task CreateAsync( Action? action = null, CancellationToken ct = default )` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **action** (`Action?`) - Optional - Optional configuration delegate to customize connection options - **ct** (`CancellationToken`) - Optional - Cancellation token for the connection operation ### Response #### Success Response (200) - **IInterReactClient** (`Task`) - Connected client instance ready for use #### Response Example ```csharp // Simple connection with defaults (localhost, port 7496 or 7497) IInterReactClient client = await InterReactClient.CreateAsync(); // Custom configuration IInterReactClient client = await InterReactClient.CreateAsync(options => { options.TwsIpAddress = IPAddress.Parse("192.168.1.100"); options.TwsPortAddresses = new[] { 7496, 7497 }; options.TwsClientId = 1; options.AllowOrderPlacement = true; }); try { // Use client... } finally { await client.DisposeAsync(); } ``` ### Throws - `InvalidOperationException` — If connection fails to all specified ports - `InvalidDataException` — If server version negotiation fails ``` -------------------------------- ### InvalidDataException Trigger Examples Source: https://github.com/dshe/interreact/blob/master/_autodocs/errors.md Illustrates scenarios where InvalidDataException is thrown due to malformed data received from TWS. This can occur during login if the server version is unparseable or if unsupported data types are encountered. ```csharp // Server version parsing failed during login // Throws: "Could not parse server version '{value}'" // Unsupported data type in RequestMessage // Throws: "RequestMessage: unsupported data type = {typename}" ``` -------------------------------- ### IInterReactClient.CreateAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/MANIFEST.txt Factory method to create an instance of the IInterReactClient interface, used to establish a connection to the Interactive Brokers Trader Workstation. ```APIDOC ## IInterReactClient.CreateAsync ### Description Factory method to create an instance of the IInterReactClient interface, used to establish a connection to the Interactive Brokers Trader Workstation. ### Method Factory Method ### Endpoint N/A (Client-side library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var client = await InterReactClient.CreateAsync(); ``` ### Response #### Success Response - **IInterReactClient** - An instance of the client interface connected to TWS. ``` -------------------------------- ### CreateAsync Factory Method Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/IInterReactClient.md Factory method to create and connect a new client to TWS/Gateway. It accepts an optional configuration delegate for customizing connection options and a cancellation token. ```csharp public static async Task CreateAsync( Action? action = null, CancellationToken ct = default) ``` -------------------------------- ### Use Real-Time Ticks Source: https://github.com/dshe/interreact/blob/master/_autodocs/configuration.md Configure the client to use real-time ticks by setting `UseDelayedTicks` to false. This requires a market data subscription. ```csharp // Use real-time ticks (requires market data subscription) var client = await InterReactClient.CreateAsync(options => { options.UseDelayedTicks = false; }); ``` -------------------------------- ### Create Observable with Request ID Management Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Extensions.md Use ToObservableWithId for advanced observable creation with automatic request ID management. It takes functions to get the next ID, request with an ID, and cancel by ID. ```csharp public static IObservable ToObservableWithId( this IObservable source, Func getIdFunc, Func requestFunc, Func? cancelFunc = null) { // Implementation details omitted for brevity throw new NotImplementedException(); } ``` ```csharp var observable = client.Request.Response .ToObservableWithId( client.Request.GetNextId, id => client.Request.RequestMarketDataAsync(id, contract), id => client.Request.CancelMarketDataAsync(id)); ``` -------------------------------- ### RequestFinancialAdvisorConfigurationAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Requests the financial advisor configuration. ```APIDOC ## RequestFinancialAdvisorConfigurationAsync ### Description Requests the financial advisor configuration. ### Method `RequestFinancialAdvisorConfigurationAsync(FinancialAdvisorDataType dataType)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **dataType** (FinancialAdvisorDataType) - Required - The type of financial advisor data to request. ``` -------------------------------- ### Define a Buy Order Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Constants.md Use OrderAction.Buy to specify a long buy order. This snippet shows the initialization of a basic limit order. ```csharp var order = new Order { Action = OrderAction.Buy, TotalQuantity = 100, OrderType = OrderTypes.Limit, LimitPrice = 150.00 }; ``` -------------------------------- ### PlaceOrderAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Submit an order to the exchange. This method allows users to place orders with specified details for a given contract, with notes on required configurations and potential exceptions. ```APIDOC ## PlaceOrderAsync ### Description Submit an order to the exchange. ### Method `public async ValueTask PlaceOrderAsync(int orderId, Order order, Contract contract)` ### Parameters #### Path Parameters - `orderId` (int) - Yes - Unique order identifier (from `GetNextId()`) - `order` (Order) - Yes - Order details (type, quantity, price, etc.) - `contract` (Contract) - Yes - Contract to place order for ### Returns `ValueTask` — Completes when order is sent ### Throws - `InvalidOperationException` — If `InterReactOptions.AllowOrderPlacement` is `false` - `ArgumentNullException` — If order or contract is null ### Response Messages - `OpenOrder` — Order acknowledgment - `OrderStatusReport` — Status updates - `Execution` — Trade fills - `CommissionReport` — Commission/fees - `Alert` — Errors or rejections ### Notes - Requires `Options.AllowOrderPlacement = true` - Order must have `OrderId` property set (or use `Service.PlaceOrderAsync()` which handles this) ### Request Example ```csharp var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "AMZN", Currency = "USD", Exchange = "SMART" }; var order = new Order { Action = OrderAction.Buy, TotalQuantity = 100, OrderType = OrderTypes.Limit, LimitPrice = 150.00 }; int orderId = client.Request.GetNextId(); await client.Request.PlaceOrderAsync(orderId, order, contract); ``` ``` -------------------------------- ### Connect to Paper Trading Instance Source: https://github.com/dshe/interreact/blob/master/_autodocs/configuration.md Connect to a paper trading instance of TWS/Gateway by specifying the appropriate port address. ```csharp // Connect to paper trading instance on port 7497 IInterReactClient client = await InterReactClient.CreateAsync(options => { options.TwsPortAddresses = new[] { 7497 }; }); ``` -------------------------------- ### PlaceOrderAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Service.md Places an order and returns an `OrderMonitor` object that can be used to track the order's status and lifecycle. ```APIDOC ## PlaceOrderAsync ### Description Place an order and receive an `OrderMonitor` for tracking. ### Method POST ### Endpoint `/orders` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `order` (Order) - Required - Order details - `contract` (Contract) - Required - Contract to place order for ### Request Example ```csharp var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "AMZN", Currency = "USD", Exchange = "SMART" }; var order = new Order { Action = OrderAction.Buy, TotalQuantity = 50, OrderType = OrderTypes.Limit, LimitPrice = 150.00 }; var monitor = await client.Service.PlaceOrderAsync(order, contract); monitor.Messages .OfType() .Subscribe(status => Console.WriteLine($"Order {monitor.OrderId}: {status.Status}")); // Later: cancel the order await monitor.CancelOrderAsync(); ``` ### Response #### Success Response (200) - `OrderMonitor` - Monitor object for tracking order ### Requires `InterReactOptions.AllowOrderPlacement = true` ``` -------------------------------- ### Place Order Async Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Submit an order to the exchange. Requires `InterReactOptions.AllowOrderPlacement` to be true. Ensure the `Order` object has its `OrderId` property set. ```csharp public async ValueTask PlaceOrderAsync(int orderId, Order order, Contract contract) ``` ```csharp var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "AMZN", Currency = "USD", Exchange = "SMART" }; var order = new Order { Action = OrderAction.Buy, TotalQuantity = 100, OrderType = OrderTypes.Limit, LimitPrice = 150.00 }; int orderId = client.Request.GetNextId(); await client.Request.PlaceOrderAsync(orderId, order, contract); ``` -------------------------------- ### Subscribe to Account Positions Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Service.md Provides an observable stream of account positions, including initial positions and subsequent updates. Use this for real-time monitoring of your account positions. ```csharp public IObservable AccountPositionsObservable { get; } ``` ```csharp var subscription = client.Service.AccountPositionsObservable .TakeWhile(pos => !pos.IsEndMessage) .Subscribe(pos => { Console.WriteLine($"{pos.Account}: {pos.Contract.Symbol} x {pos.Quantity}"); }); ``` -------------------------------- ### Configure InterReact Client Connection Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Connect to a remote Interactive Brokers TWS or Gateway instance. Configure IP address, ports, client ID, and order placement permissions. ```csharp using System.Net; var client = await InterReactClient.CreateAsync(options => { // Connect to remote server options.TwsIpAddress = IPAddress.Parse("192.168.1.100"); // Try specific ports options.TwsPortAddresses = new[] { 7496, 7497 }; // Set unique client ID options.TwsClientId = 1; // Enable order placement options.AllowOrderPlacement = true; // Use real ticks (not delayed) options.UseDelayedTicks = false; }); ``` -------------------------------- ### Handle TWS Alert and Argument Exceptions Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Demonstrates how to catch specific exceptions like AlertException for TWS errors and ArgumentException for invalid inputs. ```csharp using System; try { var details = await client.Service.GetContractDetailsAsync(contract); } catch (AlertException ex) { Console.WriteLine($"TWS Error {ex.AlertMessage.Code}: {ex.AlertMessage.Message}"); } catch (ArgumentException ex) { Console.WriteLine($"Invalid argument: {ex.Message}"); } catch (TimeoutException) { Console.WriteLine("Request timeout"); } catch (OperationCanceledException) { Console.WriteLine("Request cancelled"); } ``` -------------------------------- ### Handle Order Rejection with AlertException Source: https://github.com/dshe/interreact/blob/master/_autodocs/errors.md Process order rejections by monitoring the message stream for Alerts and converting them to AlertException for detailed handling. ```csharp try { var monitor = await client.Service.PlaceOrderAsync(order, contract); var error = await monitor.Messages .OfType() .FirstOrDefaultAsync(); if (error != null) throw error.ToAlertException(); } catch (AlertException ex) { Console.WriteLine($"Order rejected: {ex.AlertMessage.Message}"); if (!string.IsNullOrEmpty(ex.AlertMessage.AdvancedOrderRejectJson)) Console.WriteLine($"Details: {ex.AlertMessage.AdvancedOrderRejectJson}"); } ``` -------------------------------- ### Add InterReact Package Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Use the dotnet CLI to add the InterReact NuGet package to your .NET project. ```bash dotnet add package InterReact ``` -------------------------------- ### Handling AlertException Source: https://github.com/dshe/interreact/blob/master/_autodocs/errors.md Demonstrates how to catch and handle AlertException when interacting with InterReact services. This snippet shows how to access the alert code and message, and optionally, advanced order rejection details. ```csharp using InterReact; try { var details = await client.Service.GetContractDetailsAsync(contract) .TimeoutAfter(TimeSpan.FromSeconds(5)); } catch (AlertException ex) { Console.WriteLine($"Code: {ex.AlertMessage.Code}"); Console.WriteLine($"Message: {ex.AlertMessage.Message}"); // For advanced orders, JSON details available if (!string.IsNullOrEmpty(ex.AlertMessage.AdvancedOrderRejectJson)) Console.WriteLine($"Details: {ex.AlertMessage.AdvancedOrderRejectJson}"); } ``` -------------------------------- ### Monitor Account Positions Continuously Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Subscribe to real-time account position updates. The subscription can be stopped by disposing of the returned disposable object. ```csharp var subscription = client.Service.AccountPositionsObservable .TakeWhile(pos => !pos.IsEndMessage) .Subscribe(pos => Console.WriteLine($"{pos.Contract.Symbol}: {pos.Quantity}")); // Keep subscription alive await Task.Delay(TimeSpan.FromHours(1)); subscription.Dispose(); ``` -------------------------------- ### ReplaceFinancialAdvisorConfigurationAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Replaces the financial advisor configuration with new XML data. ```APIDOC ## ReplaceFinancialAdvisorConfigurationAsync ### Description Replaces the financial advisor configuration with new XML data. ### Method `ReplaceFinancialAdvisorConfigurationAsync(int requestId, FinancialAdvisorDataType dataType, string xml)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **requestId** (int) - Required - The ID for the configuration replacement request. - **dataType** (FinancialAdvisorDataType) - Required - The type of financial advisor data being replaced. - **xml** (string) - Required - The XML string containing the new configuration. ``` -------------------------------- ### Connect Multiple Clients with Different IDs Source: https://github.com/dshe/interreact/blob/master/_autodocs/configuration.md Establish connections for multiple clients to the same TWS/Gateway account, each with a unique client ID. Ensure proper disposal of clients after use. ```csharp // Connect multiple clients to same account with different IDs var client1 = await InterReactClient.CreateAsync(options => { options.TwsClientId = 1; }); var client2 = await InterReactClient.CreateAsync(options => { options.TwsClientId = 2; }); try { // Use clients... } finally { await client1.DisposeAsync(); await client2.DisposeAsync(); } ``` -------------------------------- ### PlaceOrderAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Places an order for a given contract. ```APIDOC ## PlaceOrderAsync ### Description Places an order for a given contract. ### Method `PlaceOrderAsync(int orderId, Order order, Contract contract)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **orderId** (int) - Required - The ID of the order. - **order** (Order) - Required - The order details. - **contract** (Contract) - Required - The contract details for the order. ``` -------------------------------- ### Place a Limit Order Source: https://github.com/dshe/interreact/blob/master/_autodocs/getting-started.md Place a limit order for a specified contract. Ensure order placement is enabled in client options. This snippet also shows how to subscribe to order status and execution updates. ```csharp // Enable order placement var client = await InterReactClient.CreateAsync(options => { options.AllowOrderPlacement = true; }); var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "AMZN", Currency = "USD", Exchange = "SMART" }; var order = new Order { Action = OrderAction.Buy, TotalQuantity = 100, OrderType = OrderTypes.Limit, LimitPrice = 150.00, TimeInForce = OrderTimeInForce.GoodTillCanceled }; // Place order and get monitor var monitor = await client.Service.PlaceOrderAsync(order, contract); Console.WriteLine($"Order {monitor.OrderId} placed"); // Subscribe to status updates monitor.Messages .OfType() .Subscribe(status => Console.WriteLine($"Status: {status.Status}, Filled: {status.Filled}")); // Subscribe to executions monitor.Messages .OfType() .Subscribe(exec => Console.WriteLine($"Filled: {exec.Shares} @ {exec.Price}")); // Cancel order when done await monitor.CancelOrderAsync(); await monitor.DisposeAsync(); ``` -------------------------------- ### InterReact File Organization Source: https://github.com/dshe/interreact/blob/master/_autodocs/INDEX.md This snippet shows the directory structure for the InterReact project, outlining the location of main documentation files and API reference files. ```text /output/ ├── README.md ← Start here for overview ├── getting-started.md ← Quick start guide ├── configuration.md ← Connection configuration ├── types.md ← Data types (Contract, Order, Alert, etc.) ├── errors.md ← Exception and error handling ├── INDEX.md ← This file └── api-reference/ ├── IInterReactClient.md ← Client factory and interface ├── InterReactOptions.md ← Configuration options ├── Request.md ← Low-level request API ├── Service.md ← High-level service API ├── OrderMonitor.md ← Order tracking ├── Extensions.md ← Observable operators └── Constants.md ← Enum constants ``` -------------------------------- ### InterReact Imports Source: https://github.com/dshe/interreact/blob/master/README.md Essential using directives for InterReact and System.Reactive functionalities. Ensure these are included at the top of your C# files when using the library. ```csharp using System; using System.Threading.Tasks; using System.Reactive.Linq; using InterReact; ``` -------------------------------- ### Subscribe to Market Data Observable Source: https://github.com/dshe/interreact/blob/master/_autodocs/README.md Demonstrates subscribing to a stream of market data ticks, filtering for specific tick types. Use this for real-time market data. ```csharp client.Service.CreateMarketDataObservable(contract) .Where(tick => tick.TickType == TickType.LastPrice) .Subscribe(onNext: ...) ``` -------------------------------- ### Connect to Remote Server on Specific Port Source: https://github.com/dshe/interreact/blob/master/_autodocs/configuration.md Establish a connection to a remote TWS/Gateway server, specifying the IP address and a particular port. ```csharp // Connect to remote server on specific port IInterReactClient client = await InterReactClient.CreateAsync(options => { options.TwsIpAddress = IPAddress.Parse("192.168.100.50"); options.TwsPortAddresses = new[] { 7496 }; }); ``` -------------------------------- ### Create Market Data Observable Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Service.md Creates an observable stream of market data ticks for a contract. Results are cached and replayed to new subscribers. ```csharp public IObservable CreateMarketDataObservable( Contract contract, IList? genericTickTypes = null, IList? options = null) ``` ```csharp var contract = new Contract { SecurityType = ContractSecurityType.Stock, Symbol = "TSLA", Currency = "USD", Exchange = "SMART" }; var subscription = client.Service .CreateMarketDataObservable(contract) .OfTickClass(selector => selector.PriceTick) .Where(tick => tick.TickType == TickType.LastPrice) .Subscribe(tick => Console.WriteLine($"Last: {tick.Price}")); // Dispose subscription to stop receiving ticks subscription.Dispose(); ``` -------------------------------- ### Subscribe to Live Stock Prices Source: https://github.com/dshe/interreact/blob/master/README.md Connects to TWS, defines a stock contract for AMZN, and subscribes to real-time last price updates. Requires TWS or Gateway to be running with API access enabled. ```csharp // Create the InterReact client by connecting to TWS/Gateway on the local host. IInterReactClient client = await InterReactClient.ConnectAsync(); // Create a contract object. Contract contract = new() { SecurityType = ContractSecurityType.Stock, Symbol = "AMZN", Currency = "USD", Exchange = "SMART" }; // Create and then subscribe to the observable which can observe ticks for the contract. IDisposable subscription = client .Service .CreateMarketDataObservable(contract) .OfTickClass(selector => selector.PriceTick) .Where(tick => tick.TickType == TickType.LastPrice) .Subscribe(onNext: priceTick => Console.WriteLine($"Last Price = {priceTick.Price}")); Console.WriteLine(Environment.NewLine + "press a key to exit..."); Console.ReadKey(); Console.Clear(); // Dispose the subscription to stop receiving ticks. subscription.Dispose(); // Disconnect from TWS/Gateway. await client.DisposeAsync(); ``` -------------------------------- ### RequestAutoOpenOrdersAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Requests auto-open orders based on a subscription flag. ```APIDOC ## RequestAutoOpenOrdersAsync ### Description Requests auto-open orders based on a subscription flag. ### Method `RequestAutoOpenOrdersAsync(bool autoBind)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **autoBind** (bool) - Required - Flag to subscribe to auto-open orders. ``` -------------------------------- ### Real-time Bar What To Show Constants Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Constants.md Constants for specifying the type of data to retrieve for real-time bars. Available types are trades, bid, ask, and midpoint. ```csharp public static class RealtimeBarWhatToShow { public const string Trades = "TRADES"; public const string Bid = "BID"; public const string Ask = "ASK"; public const string MidPoint = "MIDPOINT"; } ``` -------------------------------- ### RequestAllOpenOrdersAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Requests a list of all open orders, including those that may not be currently active. ```APIDOC ## RequestAllOpenOrdersAsync ### Description Requests a list of all open orders, including those that may not be currently active. ### Method `RequestAllOpenOrdersAsync()` ### Endpoint N/A (SDK Method) ``` -------------------------------- ### RequestOpenOrdersAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Requests a list of all currently open orders. ```APIDOC ## RequestOpenOrdersAsync ### Description Requests a list of all currently open orders. ### Method `RequestOpenOrdersAsync()` ### Endpoint N/A (SDK Method) ``` -------------------------------- ### Historical Data What To Show Constants Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Constants.md Constants for specifying the type of historical data to retrieve. Options include trades, midpoints, bid/ask, and volatility. ```csharp public static class HistoricalDataWhatToShow { public const string Trades = "TRADES"; public const string Midpoint = "MIDPOINT"; public const string Bid = "BID"; public const string Ask = "ASK"; public const string BidAsk = "BID_ASK"; public const string HistoricalVolatility = "HISTORICAL_VOLATILITY"; public const string OptionImpliedVolatility = "OPTION_IMPLIED_VOLATILITY"; } ``` -------------------------------- ### RequestRealTimeBarsAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Requests real-time bar data for a contract. ```APIDOC ## RequestRealTimeBarsAsync ### Description Requests real-time bar data for a contract. ### Method `RequestRealTimeBarsAsync(int requestId, Contract contract, ...)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **requestId** (int) - Required - The ID for the real-time bars request. - **contract** (Contract) - Required - The contract for which to request real-time bars. (Other parameters not fully specified in source, represented by '...') ``` -------------------------------- ### RequestAccountSummaryAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Request.md Requests a summary of account details. ```APIDOC ## RequestAccountSummaryAsync ### Description Requests a summary of account details. ### Method `RequestAccountSummaryAsync(int requestId, string group = "All", IList? tags = null)` ### Endpoint N/A (SDK Method) ### Parameters #### Path Parameters - **requestId** (int) - Required - The ID for the account summary request. - **group** (string) - Optional - The account group to request summary for. Defaults to 'All'. - **tags** (IList) - Optional - A list of tags to filter the account summary. ``` -------------------------------- ### OrderAction Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/Constants.md Buy/sell action constants. These constants define the action to be taken for an order, such as buying or selling. ```APIDOC ## OrderAction ### Description Buy/sell action constants. ### Constants | Constant | Value | Description | |---|---|---| | `Buy` | `"BUY"` | Long buy order | | `Sell` | `"SELL"` | Sell to close | | `SShort` | `"SSHORT"` | Short sell | | `SLong` | `"SLONG"` | Buy to open | | `Undefined` | `""` | Unspecified | ``` -------------------------------- ### OrderAction Constants Source: https://github.com/dshe/interreact/blob/master/_autodocs/types.md Defines constants for order actions, specifying whether an order is a buy or sell. ```csharp public static class OrderAction { public const string Undefined = ""; public const string Buy = "BUY"; public const string Sell = "SELL"; public const string SShort = "SSHORT"; public const string SLong = "SLONG"; } ``` -------------------------------- ### InterReactOptions Properties Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/InterReactOptions.md Details of the configurable properties within InterReactOptions. ```APIDOC ## Properties | Property | Type | Default | Description | |----------|------|---------|-------------| | `TwsIpAddress` | `IPAddress` | `IPAddress.IPv6Loopback` (`::1`) | IP address of TWS/Gateway server | | `TwsPortAddresses` | `IReadOnlyList` | `[7496, 7497, 4001, 4002]` | Port(s) to attempt connection on, tried in order | | `TwsClientId` | `int` | Random (100,000–999,999) | Unique client identifier; up to 8 clients per account allowed | | `AllowOrderPlacement` | `bool` | `false` | Whether to permit order placement; must be explicitly enabled | | `OptionalCapabilities` | `string` | `""` | Optional TWS API capabilities string | | `UseDelayedTicks` | `bool` | `true` | If true, delayed ticks used for delayed market data; if false, real ticks substituted | | `Logger` | `ILogger` | `NullLogger.Instance` | Microsoft.Extensions.Logging.ILogger for custom logging | | `LogFactory` | `ILoggerFactory` | `NullLoggerFactory.Instance` | Microsoft.Extensions.Logging.ILoggerFactory for dependency injection | | `ServerVersionMin` | `ServerVersion` | `BOND_ISSUERID` | Minimum supported API version (read-only) | | `ServerVersionMax` | `ServerVersion` | `BOND_ISSUERID` | Maximum supported API version (read-only) | | `ServerVersionCurrent` | `ServerVersion` | `NONE` | Current negotiated server version (read-only; set during login) | ``` -------------------------------- ### InterReactOptions Class Definition Source: https://github.com/dshe/interreact/blob/master/_autodocs/api-reference/InterReactOptions.md Defines the configuration options for the InterReactClient, controlling its connection and behavior. ```APIDOC ## Class Definition ```csharp public sealed class InterReactOptions { // IP address of TWS/Gateway server public IPAddress TwsIpAddress { get; set; } // Port(s) to attempt connection on, tried in order public IReadOnlyList TwsPortAddresses { get; set; } // Unique client identifier; up to 8 clients per account allowed public int TwsClientId { get; set; } // Whether to permit order placement; must be explicitly enabled public bool AllowOrderPlacement { get; set; } // Optional TWS API capabilities string public string OptionalCapabilities { get; set; } // If true, delayed ticks used for delayed market data; if false, real ticks substituted public bool UseDelayedTicks { get; set; } // Microsoft.Extensions.Logging.ILogger for custom logging public ILogger Logger { get; set; } // Microsoft.Extensions.Logging.ILoggerFactory for dependency injection public ILoggerFactory LogFactory { get; set; } } ``` ``` -------------------------------- ### RequestPositionsAsync Source: https://github.com/dshe/interreact/blob/master/_autodocs/MANIFEST.txt Retrieves the current open positions for all accounts associated with the client. ```APIDOC ## RequestPositionsAsync ### Description Retrieves the current open positions for all accounts associated with the client. ### Method POST (Implied, as it's a request) ### Endpoint N/A (Client-side library method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp var positions = await client.Request.RequestPositionsAsync(); foreach (var position in positions) { Console.WriteLine($"Account: {position.Account}, Symbol: {position.Contract.Symbol}, Position: {position.Position}"); } ``` ### Response #### Success Response - **IEnumerable** - A collection of position objects, each representing an open position in an account. ```