Interactive Brokers API
1 Establishing a connection
ibkr-session%
new
connect
send-msg
2 Request messages
2.1 Base interface and class
req-msg<%>
->string
ibkr-msg%
new
2.2 Account Data
account-data-req%
new
2.3 Contract Details
contract-details-req%
new
2.4 Executions (otherwise known as trades)
executions-req%
new
2.5 Historical Data
historical-data-req%
new
cancel-historical-data-req%
new
2.6 Market Data
market-data-req%
new
cancel-market-data-req%
new
market-data-type-req%
new
2.7 Orders
open-orders-req%
new
place-order-req%
new
3 Response messages
account-value-rsp
commission-report-rsp
contract-details-rsp
err-rsp
execution-rsp
historical-data-rsp
market-data-rsp
next-valid-id-rsp
open-order-rsp
order-status-rsp
portfolio-value-rsp
4 Base Structs
bar
combo-leg
condition
8.12

Interactive Brokers API🔗ℹ

evdubs

Racket implementation for the Interactive Brokers’ Trader Workstation Client API.

This implementation is based on the Java TWS API version 976.01. The protocol used to communicate between the client and server establishes the client version and should allow the server to continue consuming and producing messages compatible with our version even when the server is updated. However, when there are desirable new features added, this library may be updated and its version number updated to reflect the version of the TWS API the new code uses.

The overall design of this library is to use objects to represent the connection and request messages and to use structs to represent response messages. Using objects for the connection and request messages seemed to make the process of creation easier as there are many fields that are often not cared about and can be omitted. We also use an interface and a base class for request messages. For response message, we stick to structs as we don’t care about inheritance, nor do we need an ease-of-use creation method as the library creates the fully-filled-in instances. This is maybe a weird design.

1 Establishing a connection🔗ℹ

 (require interactive-brokers-api)
  package: interactive-brokers-api

The general code flow to establish a (default) connection and send a message is as follows:

(define ibkr (new ibkr-session%))
(send ibkr connect)
; The connection should be established after call to connect
; Doing the below may be useful for testing
(require interactive-brokers-api/request-messages)
(send ibkr send-msg (new executions-req%))

class

ibkr-session% : class?

  superclass: object%

This object is responsible for establishing a connection, sending messages, and registering callbacks to receive messages. One quirk of this implementation is that calls to send-msg will block until we receive a response. During testing, it was seen that attempting to send multiple requests without waiting for a response forced a disconnect.

constructor

(new ibkr-session% 
    [[client-id client-id] 
    [handle-account-value-rsp handle-account-value-rsp] 
    [handle-accounts-rsp handle-accounts-rsp] 
    [handle-commission-report-rsp handle-commission-report-rsp] 
    [handle-contract-details-rsp handle-contract-details-rsp] 
    [handle-err-rsp handle-err-rsp] 
    [handle-execution-rsp handle-execution-rsp] 
    [handle-historical-data-rsp handle-historical-data-rsp] 
    [handle-market-data-rsp handle-market-data-rsp] 
    [handle-next-valid-id-rsp handle-next-valid-id-rsp] 
    [handle-open-order-rsp handle-open-order-rsp] 
    [handle-order-status-rsp handle-order-status-rsp] 
    [handle-portfolio-value-rsp handle-portfolio-value-rsp] 
    [handle-server-time-rsp handle-server-time-rsp] 
    [hostname hostname] 
    [port-no port-no] 
    [write-messages write-messages]]) 
  (is-a?/c ibkr-session%)
  client-id : integer? = 0
  handle-account-value-rsp : (-> account-value-rsp? any)
   = (λ (av) void)
  handle-accounts-rsp : (-> (listof string?) any) = (λ (a) void)
  handle-commission-report-rsp : (-> commission-report-rsp? any)
   = (λ (cr) void)
  handle-contract-details-rsp : (-> contract-details-rsp? any)
   = (λ (cd) void)
  handle-err-rsp : (-> err-rsp? any) = (λ (e) void)
  handle-execution-rsp : (-> execution-rsp? any) = (λ (e) void)
  handle-historical-data-rsp : (-> historical-data-rsp? any)
   = (λ (hd) void)
  handle-market-data-rsp : (-> market-data-rsp? any)
   = (λ (md) void)
  handle-next-valid-id-rsp : (-> next-valid-id-rsp? any)
   = (λ (nvi) void)
  handle-open-order-rsp : (-> open-order-rsp? any)
   = (λ (oo) void)
  handle-order-status-rsp : (-> order-status-rsp? any)
   = (λ (os) void)
  handle-portfolio-value-rsp : (-> portfolio-value-rsp? any)
   = (λ (pv) void)
  handle-server-time-rsp : (-> moment? any) = (λ (st) void)
  hostname : string? = "127.0.0.1"
  port-no : port-number? = 7497
  write-messages : boolean? = #f
On construction, we attempt to connect to the TWS server from the specified hostname and port-no. Encryption is not used currently; this library is not recommended to be used over an unsecure network.

All response handlers will execute in the same, separate thread from the thread that constructs ibkr-session%.

The write-messages field, when set to #t, will write both request and response messages to the current-output-port.

method

(send an-ibkr-session connect)  void?

When called, a thread is created to read from the socket and call the appropriate response handler with the received message. Currently, this thread will die when the connection is interruped. When this happens, I just create a new ibkr-session% to connect again rather than attempt to call connect on the existing session.

method

(send an-ibkr-session send-msg msg)  void?

  msg : (is-a?/c req-msg<%>)

Sends a message over the established session. See the request-messages section for information on available request messages.

2 Request messages🔗ℹ

 (require interactive-brokers-api/request-messages)
  package: interactive-brokers-api

2.1 Base interface and class🔗ℹ

interface

req-msg<%> : interface?

This interface makes sure all request messages provide a ->string method that can be used to serialize the object into a string that can be processed by the server.

method

(send a-req-msg ->string)  string?

class

ibkr-msg% : class?

  superclass: object%

This is the base class for all request messages. There is no need for a client of this library to instantiate this class. This class is just a declaration that each request message will contain a msg-id and version.

constructor

(new ibkr-msg%    
    [msg-id msg-id]    
    [version version])  (is-a?/c ibkr-msg%)
  msg-id : integer?
  version : integer?

2.2 Account Data🔗ℹ

class

account-data-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to receive account-value-rsps and portfolio-value-rsps. Each component of an account (e.g Net Liquidation, Account Code, Cash Balance, etc.) will be received in an individual response; there is no large structure or map that will be returned that has all of the account components. Likewise for the components of a portfolio. If you wish to aggregate the account and portfolio components, you will need to do that in your own application code. To receive account data, do:

(send ibkr send-msg (new account-data-req% [subscribe #t]))

By default subscribe is #f. To actually subscribe to data, you will need to set this value to #t. When you are finished consuming account data, you can do the following to unsubscribe:

(send ibkr send-msg (new account-data-req% [subscribe #f]))

constructor

(new account-data-req% 
    [[subscribe subscribe] 
    [account-code account-code]]) 
  (is-a?/c account-data-req%)
  subscribe : boolean? = #f
  account-code : string? = ""

2.3 Contract Details🔗ℹ

class

contract-details-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to receive a contract-details-rsp. Here, if there is any ambiguity in your request, you will receive all of the contract details that match your request. As an example,
(send ibkr send-msg
      (new contract-details-req% [symbol "AAPL"]
                                 [security-type 'opt]
                                 [strike 200.0]))
will retrieve all actively trading AAPL options with a strike price of 200.0. By filling in more fields in your request, you are more likely to retrieve a single result if that is your objective.

constructor

(new contract-details-req% 
    [[request-id request-id] 
    [contract-id contract-id] 
    [symbol symbol] 
    [security-type security-type] 
    [expiry expiry] 
    [strike strike] 
    [right right] 
    [multiplier multiplier] 
    [exchange exchange] 
    [primary-exchange primary-exchange] 
    [currency currency] 
    [local-symbol local-symbol] 
    [trading-class trading-class] 
    [security-id-type security-id-type] 
    [security-id security-id]]) 
  (is-a?/c contract-details-req%)
  request-id : integer? = 0
  contract-id : integer? = 0
  symbol : string? = ""
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
   = #f
  expiry : (or/c date? #f) = #f
  strike : rational? = 0
  right : (or/c 'call 'put #f) = #f
  multiplier : (or/c rational? #f) = #f
  exchange : string? = ""
  primary-exchange : string? = ""
  currency : string? = ""
  local-symbol : string? = ""
  trading-class : string? = ""
  security-id-type : (or/c 'cusip 'sedol 'isin 'ric #f) = #f
  security-id : string? = ""

2.4 Executions (otherwise known as trades)🔗ℹ

class

executions-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to receive execution-rsps. As an example,
(send ibkr send-msg (new executions-req%
                         [timestamp (-period (now/moment) (days 7))]))
will retrieve all executions within a week.

constructor

(new executions-req% 
    [[request-id request-id] 
    [client-id client-id] 
    [account account] 
    [timestamp timestamp] 
    [symbol symbol] 
    [security-type security-type] 
    [exchange exchange] 
    [side side]]) 
  (is-a?/c executions-req%)
  request-id : integer? = 0
  client-id : integer? = 0
  account : string? = ""
  timestamp : (or/c moment? #f) = #f
  symbol : string? = ""
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
   = #f
  exchange : string? = ""
  side : (or/c 'buy 'sell 'sshort #f) = #f

2.5 Historical Data🔗ℹ

class

historical-data-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to receive historical-data-rsps. The interesting part of this response are the bars that are sent back and can be used for display in a chart. As an example,
(send ibkr send-msg (new historical-data-req%
                         [request-id 22]
                         [symbol "UPS"]
                         [security-type 'stk]
                         [exchange "SMART"]))
will retrieve 1-hour (bar-size default) open-high-low-close bars from yesterday to today (end-moment and duration defaults) representing trades (what-to-show default).
As of 2020-09-03, the smallest set of data at the finest resolution is to request 1-second bars over a duration of 30 seconds.
You will need to track the relationship between your request-id and your parameters as the returned historical-data-rsps will not have the symbol, security-type, etc. information.

constructor

(new historical-data-req% 
    [[request-id request-id] 
    [contract-id contract-id] 
    [symbol symbol] 
    [security-type security-type] 
    [expiry expiry] 
    [strike strike] 
    [right right] 
    [multiplier multiplier] 
    [exchange exchange] 
    [primary-exchange primary-exchange] 
    [currency currency] 
    [local-symbol local-symbol] 
    [trading-class trading-class] 
    [include-expired include-expired] 
    [end-moment end-moment] 
    [bar-size bar-size] 
    [duration duration] 
    [use-rth use-rth] 
    [what-to-show what-to-show] 
    [combo-legs combo-legs] 
    [keep-up-to-date keep-up-to-date] 
    [chart-options chart-options]]) 
  (is-a?/c historical-data-req%)
  request-id : integer? = 0
  contract-id : integer? = 0
  symbol : string? = ""
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
   = #f
  expiry : (or/c date? #f) = #f
  strike : rational? = 0
  right : (or/c 'call 'put #f) = #f
  multiplier : (or/c rational? #f) = #f
  exchange : string? = ""
  primary-exchange : string? = ""
  currency : string? = ""
  local-symbol : string? = ""
  trading-class : string? = ""
  include-expired : boolean? = #f
  end-moment : moment? = (now/moment)
  bar-size : 
(or/c '1-secs '5-secs '15-secs '30-secs '1-min
      '2-mins '3-mins '5-mins '15-mins
      '30-mins '1-hour '2-hours '3-hours
      '4-hours '8-hours '1-day '1W '1M)
   = '1-hour
  duration : period? = (days 1)
  use-rth : boolean? = #f
  what-to-show : 
(or/c 'trades 'midpoint 'bid 'ask 'bid-ask
      'historical-volatility 'option-implied-volatility
      'fee-rate 'rebate-rate)
   = 'trades
  combo-legs : (listof combo-leg?) = (list)
  keep-up-to-date : boolean? = #f
  chart-options : string? = ""

class

cancel-historical-data-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to stop receiving historical-data-rsps.

constructor

(new cancel-historical-data-req% [[request-id request-id]])

  (is-a?/c cancel-historical-data-req%)
  request-id : integer? = 0

2.6 Market Data🔗ℹ

class

market-data-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to receive streaming market-data-rsps. As an example,
(send ibkr send-msg (new market-data-req%
                         [request-id 23]
                         [symbol "UPS"]
                         [security-type 'stk]
                         [exchange "SMART"]))
will subscribe to (at least) bid/ask price and size updates.
You will need to track the relationship between your request-id and your parameters as the returned market-data-rsps will not have the symbol, security-type, etc. information.

constructor

(new market-data-req% 
    [[request-id request-id] 
    [contract-id contract-id] 
    [symbol symbol] 
    [security-type security-type] 
    [expiry expiry] 
    [strike strike] 
    [right right] 
    [multiplier multiplier] 
    [exchange exchange] 
    [primary-exchange primary-exchange] 
    [currency currency] 
    [local-symbol local-symbol] 
    [trading-class trading-class] 
    [combo-legs combo-legs] 
    [delta-neutral-contract-id delta-neutral-contract-id] 
    [delta-neutral-delta delta-neutral-delta] 
    [delta-neutral-price delta-neutral-price] 
    [generic-tick-list generic-tick-list] 
    [snapshot snapshot] 
    [regulatory-snapshot regulatory-snapshot] 
    [market-data-options market-data-options]]) 
  (is-a?/c market-data-req%)
  request-id : integer? = 0
  contract-id : integer? = 0
  symbol : string? = ""
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
   = #f
  expiry : (or/c date? #f) = #f
  strike : rational? = 0
  right : (or/c 'call 'put #f) = #f
  multiplier : (or/c rational? #f) = #f
  exchange : string? = ""
  primary-exchange : string? = ""
  currency : string? = ""
  local-symbol : string? = ""
  trading-class : string? = ""
  combo-legs : (listof combo-leg?) = (list)
  delta-neutral-contract-id : (or/c integer? #f) = #f
  delta-neutral-delta : (or/c rational? #f) = #f
  delta-neutral-price : (or/c rational? #f) = #f
  generic-tick-list : string? = ""
  snapshot : boolean? = #f
  regulatory-snapshot : boolean? = #f
  market-data-options : string? = ""

class

cancel-market-data-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to stop receiving market-data-rsps.

constructor

(new cancel-market-data-req% [[request-id request-id]])

  (is-a?/c cancel-market-data-req%)
  request-id : integer? = 0

class

market-data-type-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to change the type of market data received using calls to market-data-req%. As an example,
(send ibkr send-msg (new market-data-type-req%
                         [market-data-type 'delayed-frozen]))
will allow subsequent market-data-req% calls to first retrieve real-time market data if available; if not, delayed market data will be retrieved; if delayed data is unavailable, delayed frozen (last available market data) data will be retrieved.
Using market-data-type-req% is useful when subscribing to market data using a demo account where real-time data may not be supported.

constructor

(new market-data-type-req% [[market-data-type market-data-type]])

  (is-a?/c market-data-type-req%)
  market-data-type : (or/c 'real-time 'frozen 'delayed 'delayed-frozen)
   = 'real-time

2.7 Orders🔗ℹ

class

open-orders-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to receive all open-order-rsps. There are no fields to provide here to filter for particular open orders.

class

place-order-req% : class?

  superclass: ibkr-msg%

  extends: req-msg<%>
Request message to place an order. As you can see below, there are tons of different fields to produce an order that is as complex as you desire. Certain fields might interfere with others or be required by others. Despite this class’ many fields, it is likely that you will just be doing something simple like the following:
(send ibkr send-msg
      (new place-order-req% [symbol "AAPL"]
                            [security-type 'stk]
                            [exchange "SMART"]
                            [currency "USD"]
                            [action 'buy]
                            [total-quantity 100]
                            [limit-price 200.0]))
Any questions related to which fields do what should first consult the IBKR docs or IBKR themselves. The fields of this class are intended to exactly match those in the Java client library.
Be sure to add a handler for next-valid-id-rsp in ibkr-session% so that you don’t run into any errors as a result of reusing an order ID. Order IDs are unique integers over the life of an account.

constructor

(new place-order-req% 
    [[order-id order-id] 
    [contract-id contract-id] 
    [symbol symbol] 
    [security-type security-type] 
    [expiry expiry] 
    [strike strike] 
    [right right] 
    [multiplier multiplier] 
    [exchange exchange] 
    [primary-exchange primary-exchange] 
    [currency currency] 
    [local-symbol local-symbol] 
    [trading-class trading-class] 
    [security-id-type security-id-type] 
    [security-id security-id] 
    [action action] 
    [total-quantity total-quantity] 
    [order-type order-type] 
    [limit-price limit-price] 
    [aux-price aux-price] 
    [time-in-force time-in-force] 
    [oca-group oca-group] 
    [account account] 
    [open-close open-close] 
    [origin origin] 
    [order-ref order-ref] 
    [transmit transmit] 
    [parent-id parent-id] 
    [block-order block-order] 
    [sweep-to-fill sweep-to-fill] 
    [display-size display-size] 
    [trigger-method trigger-method] 
    [outside-rth outside-rth] 
    [hidden hidden] 
    [combo-legs combo-legs] 
    [order-combo-legs order-combo-legs] 
    [smart-combo-routing-params smart-combo-routing-params] 
    [discretionary-amount discretionary-amount] 
    [good-after-time good-after-time] 
    [good-till-date good-till-date] 
    [advisor-group advisor-group] 
    [advisor-method advisor-method] 
    [advisor-percentage advisor-percentage] 
    [advisor-profile advisor-profile] 
    [model-code model-code] 
    [short-sale-slot short-sale-slot] 
    [designated-location designated-location] 
    [exempt-code exempt-code] 
    [oca-type oca-type] 
    [rule-80-a rule-80-a] 
    [settling-firm settling-firm] 
    [all-or-none all-or-none] 
    [minimum-quantity minimum-quantity] 
    [percent-offset percent-offset] 
    [electronic-trade-only electronic-trade-only] 
    [firm-quote-only firm-quote-only] 
    [nbbo-price-cap nbbo-price-cap] 
    [auction-strategy auction-strategy] 
    [starting-price starting-price] 
    [stock-ref-price stock-ref-price] 
    [delta delta] 
    [stock-range-lower stock-range-lower] 
    [stock-range-upper stock-range-upper] 
    [override-percentage-constraints override-percentage-constraints] 
    [volatility volatility] 
    [volatility-type volatility-type] 
    [delta-neutral-order-type delta-neutral-order-type] 
    [delta-neutral-aux-price delta-neutral-aux-price] 
    [continuous-update continuous-update] 
    [reference-price-type reference-price-type] 
    [trailing-stop-price trailing-stop-price] 
    [trailing-percent trailing-percent] 
    [scale-init-level-size scale-init-level-size] 
    [scale-subs-level-size scale-subs-level-size] 
    [scale-price-increment scale-price-increment] 
    [scale-price-adjust-value scale-price-adjust-value] 
    [scale-price-adjust-interval scale-price-adjust-interval] 
    [scale-profit-offset scale-profit-offset] 
    [scale-auto-reset scale-auto-reset] 
    [scale-init-position scale-init-position] 
    [scale-init-fill-quantity scale-init-fill-quantity] 
    [scale-random-percent scale-random-percent] 
    [scale-table scale-table] 
    [active-start-time active-start-time] 
    [active-stop-time active-stop-time] 
    [hedge-type hedge-type] 
    [hedge-param hedge-param] 
    [opt-out-smart-routing opt-out-smart-routing] 
    [clearing-account clearing-account] 
    [clearing-intent clearing-intent] 
    [not-held not-held] 
    [delta-neutral-contract-id delta-neutral-contract-id] 
    [delta-neutral-delta delta-neutral-delta] 
    [delta-neutral-price delta-neutral-price] 
    [algo-strategy algo-strategy] 
    [algo-strategy-params algo-strategy-params] 
    [algo-id algo-id] 
    [what-if what-if] 
    [order-misc-options order-misc-options] 
    [solicited solicited] 
    [randomize-size randomize-size] 
    [randomize-price randomize-price] 
    [reference-contract-id reference-contract-id] 
    [is-pegged-change-amount-decrease is-pegged-change-amount-decrease] 
    [pegged-change-amount pegged-change-amount] 
    [reference-change-amount reference-change-amount] 
    [reference-exchange-id reference-exchange-id] 
    [conditions conditions] 
    [conditions-ignore-rth conditions-ignore-rth] 
    [conditions-cancel-order conditions-cancel-order] 
    [adjusted-order-type adjusted-order-type] 
    [trigger-price trigger-price] 
    [limit-price-offset limit-price-offset] 
    [adjusted-stop-price adjusted-stop-price] 
    [adjusted-stop-limit-price adjusted-stop-limit-price] 
    [adjusted-trailing-amount adjusted-trailing-amount] 
    [adjusted-trailing-unit adjusted-trailing-unit] 
    [ext-operator ext-operator] 
    [soft-dollar-tier-name soft-dollar-tier-name] 
    [soft-dollar-tier-value soft-dollar-tier-value] 
    [cash-quantity cash-quantity] 
    [mifid2-decision-maker mifid2-decision-maker] 
    [mifid2-decision-algo mifid2-decision-algo] 
    [mifid2-execution-trader mifid2-execution-trader] 
    [mifid2-execution-algo mifid2-execution-algo] 
    [dont-use-auto-price-for-hedge dont-use-auto-price-for-hedge] 
    [is-oms-container is-oms-container] 
    [discretionary-up-to-limit-price discretionary-up-to-limit-price] 
    [use-price-management-algo use-price-management-algo]]) 
  (is-a?/c place-order-req%)
  order-id : integer? = 0
  contract-id : integer? = 0
  symbol : string? = ""
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
   = #f
  expiry : (or/c date? #f) = #f
  strike : rational? = 0
  right : (or/c 'call 'put #f) = #f
  multiplier : (or/c rational? #f) = #f
  exchange : string? = ""
  primary-exchange : string? = ""
  currency : string? = ""
  local-symbol : string? = ""
  trading-class : string? = ""
  security-id-type : (or/c 'cusip 'sedol 'isin 'ric #f) = #f
  security-id : string? = ""
  action : (or/c 'buy 'sell 'sshort) = 'buy
  total-quantity : rational? = 0
  order-type : string? = "LMT"
  limit-price : (or/c rational? #f) = #f
  aux-price : (or/c rational? #f) = #f
  time-in-force : 
(or/c 'day 'gtc 'opg 'ioc 'gtd 'gtt
      'auc 'fok 'gtx 'dtc)
 = 'day
  oca-group : string? = ""
  account : string? = ""
  open-close : (or/c 'open 'close) = 'open
  origin : (or/c 'customer 'firm) = 'customer
  order-ref : string? = ""
  transmit : boolean? = #t
  parent-id : integer? = 0
  block-order : boolean? = #f
  sweep-to-fill : boolean? = #f
  display-size : integer? = 0
  trigger-method : integer? = 0
  outside-rth : boolean? = #f
  hidden : boolean? = #f
  combo-legs : (listof combo-leg?) = (list)
  order-combo-legs : (listof rational?) = (list)
  smart-combo-routing-params : hash? = (hash)
  discretionary-amount : (or/c rational? #f) = #f
  good-after-time : (or/c moment? #f) = #f
  good-till-date : (or/c date? #f) = #f
  advisor-group : string? = ""
  advisor-method : string? = ""
  advisor-percentage : string? = ""
  advisor-profile : string? = ""
  model-code : string? = ""
  short-sale-slot : (or/c 0 1 2) = 0
  designated-location : string? = ""
  exempt-code : integer? = -1
  oca-type : integer? = 0
  rule-80-a : string? = ""
  settling-firm : string? = ""
  all-or-none : boolean? = #f
  minimum-quantity : (or/c integer? #f) = #f
  percent-offset : (or/c rational? #f) = #f
  electronic-trade-only : boolean? = #f
  firm-quote-only : boolean? = #f
  nbbo-price-cap : (or/c rational? #f) = #f
  auction-strategy : (or/c 'match 'improvement 'transparent #f)
   = #f
  starting-price : rational? = 0
  stock-ref-price : rational? = 0
  delta : (or/c rational? #f) = #f
  stock-range-lower : rational? = 0
  stock-range-upper : rational? = 0
  override-percentage-constraints : boolean? = #f
  volatility : (or/c rational? #f) = #f
  volatility-type : (or/c integer? #f) = #f
  delta-neutral-order-type : string? = ""
  delta-neutral-aux-price : (or/c rational? #f) = #f
  continuous-update : integer? = 0
  reference-price-type : (or/c integer? #f) = #f
  trailing-stop-price : (or/c rational? #f) = #f
  trailing-percent : (or/c rational? #f) = #f
  scale-init-level-size : (or/c integer? #f) = #f
  scale-subs-level-size : (or/c integer? #f) = #f
  scale-price-increment : (or/c rational? #f) = #f
  scale-price-adjust-value : (or/c rational? #f) = #f
  scale-price-adjust-interval : (or/c integer? #f) = #f
  scale-profit-offset : (or/c rational? #f) = #f
  scale-auto-reset : boolean? = #f
  scale-init-position : (or/c integer? #f) = #f
  scale-init-fill-quantity : (or/c integer? #f) = #f
  scale-random-percent : boolean? = #f
  scale-table : string? = ""
  active-start-time : string? = ""
  active-stop-time : string? = ""
  hedge-type : string? = ""
  hedge-param : string? = ""
  opt-out-smart-routing : boolean? = #f
  clearing-account : string? = ""
  clearing-intent : (or/c 'ib 'away 'pta #f) = #f
  not-held : boolean? = #f
  delta-neutral-contract-id : (or/c integer? #f) = #f
  delta-neutral-delta : (or/c rational? #f) = #f
  delta-neutral-price : (or/c rational? #f) = #f
  algo-strategy : string? = ""
  algo-strategy-params : hash? = (hash)
  algo-id : string? = ""
  what-if : boolean? = #f
  order-misc-options : string? = ""
  solicited : boolean? = #f
  randomize-size : boolean? = #f
  randomize-price : boolean? = #f
  reference-contract-id : integer? = 0
  is-pegged-change-amount-decrease : boolean? = #f
  pegged-change-amount : rational? = 0
  reference-change-amount : rational? = 0
  reference-exchange-id : string? = ""
  conditions : (listof condition?) = (list)
  conditions-ignore-rth : boolean? = #f
  conditions-cancel-order : boolean? = #f
  adjusted-order-type : 
(or/c 'mkt 'lmt 'stp 'stp-limit
      'rel 'trail 'box-top 'fix-pegged
      'lit 'lmt-+-mkt 'loc 'mit
      'mkt-prt 'moc 'mtl 'passv-rel
      'peg-bench 'peg-mid 'peg-mkt 'peg-prim
      'peg-stk 'rel-+-lmt 'rel-+-mkt 'snap-mid
      'snap-mkt 'snap-prim 'stp-prt 'trail-limit
      'trail-lit 'trail-lmt-+-mkt 'trail-mit
      'trail-rel-+-mkt 'vol 'vwap 'quote 'ppv
      'pdv 'pmv 'psv #f)
   = #f
  trigger-price : rational? = 0
  limit-price-offset : rational? = 0
  adjusted-stop-price : rational? = 0
  adjusted-stop-limit-price : rational? = 0
  adjusted-trailing-amount : rational? = 0
  adjusted-trailing-unit : integer? = 0
  ext-operator : string? = ""
  soft-dollar-tier-name : string? = ""
  soft-dollar-tier-value : string? = ""
  cash-quantity : rational? = 0
  mifid2-decision-maker : string? = ""
  mifid2-decision-algo : string? = ""
  mifid2-execution-trader : string? = ""
  mifid2-execution-algo : string? = ""
  dont-use-auto-price-for-hedge : boolean? = #f
  is-oms-container : boolean? = #f
  discretionary-up-to-limit-price : boolean? = #f
  use-price-management-algo : boolean? = #f
Please note that the fields action, order-type, time-in-force, open-close, and origin use defaults that are not the #f, 0, or "" typical defaults. Also note that you need to manage order-id on your own. If you do not supply an order-id, it will use 0 and you will likely get an error stating the order ID has already been used.

3 Response messages🔗ℹ

 (require interactive-brokers-api/response-messages)
  package: interactive-brokers-api

struct

(struct account-value-rsp (key value currency account-name)
    #:extra-constructor-name make-account-value-rsp)
  key : string?
  value : string?
  currency : string?
  account-name : string?
As with the Java API, value here is often numeric, but we leave it as a string because this field is not guaranteed to be numeric.

struct

(struct commission-report-rsp (execution-id
    commission
    currency
    realized-pnl
    yield
    yield-redemption-date)
    #:extra-constructor-name make-commission-report-rsp)
  execution-id : string?
  commission : rational?
  currency : string?
  realized-pnl : (or/c rational? #f)
  yield : (or/c rational? #f)
  yield-redemption-date : (or/c integer? #f)
Commission reports are sent along with executions when calls are made to executions-req%.

struct

(struct contract-details-rsp (request-id
    symbol
    security-type
    expiry
    strike
    right
    exchange
    currency
    local-symbol
    market-name
    trading-class
    contract-id
    minimum-tick-increment
    md-size-multiplier
    multiplier
    order-types
    valid-exchanges
    price-magnifier
    underlying-contract-id
    long-name
    primary-exchange
    contract-month
    industry
    category
    subcategory
    time-zone-id
    trading-hours
    liquid-hours
    ev-rule
    ev-multiplier
    security-ids
    agg-group
    underlying-symbol
    underlying-security-type
    market-rule-ids
    real-expiry)
    #:extra-constructor-name make-contract-details-rsp)
  request-id : integer?
  symbol : string?
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
  expiry : (or/c date? #f)
  strike : (or/c rational? #f)
  right : (or/c 'call 'put #f)
  exchange : string?
  currency : string?
  local-symbol : string?
  market-name : string?
  trading-class : string?
  contract-id : integer?
  minimum-tick-increment : rational?
  md-size-multiplier : integer?
  multiplier : string?
  order-types : (listof string?)
  valid-exchanges : (listof string?)
  price-magnifier : integer?
  underlying-contract-id : integer?
  long-name : string?
  primary-exchange : string?
  contract-month : string?
  industry : string?
  category : string?
  subcategory : string?
  time-zone-id : string?
  trading-hours : (listof string?)
  liquid-hours : (listof string?)
  ev-rule : string?
  ev-multiplier : string?
  security-ids : hash?
  agg-group : integer?
  underlying-symbol : string?
  underlying-security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag
      'ind 'bill 'fund 'fixed 'slb 'news
      'cmdty 'bsk 'icu 'ics #f)
  market-rule-ids : (listof string?)
  real-expiry : (or/c date? #f)
When receiving contract details, it is often nice to use the contract-id for subsequent new order or market data requests as these identifiers are unique.

struct

(struct err-rsp (id error-code error-msg)
    #:extra-constructor-name make-err-rsp)
  id : integer?
  error-code : integer?
  error-msg : string?
Generic error message for incorrectly formed requests. Consult the Java API docs for more information.

struct

(struct execution-rsp (request-id
    order-id
    contract-id
    symbol
    security-type
    expiry
    strike
    right
    multiplier
    exchange
    currency
    local-symbol
    trading-class
    execution-id
    timestamp
    account
    executing-exchange
    side
    shares
    price
    perm-id
    client-id
    liquidation
    cumulative-quantity
    average-price
    order-reference
    ev-rule
    ev-multiplier
    model-code)
    #:extra-constructor-name make-execution-rsp)
  request-id : integer?
  order-id : integer?
  contract-id : integer?
  symbol : string?
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
  expiry : (or/c date? #f)
  strike : (or/c rational? #f)
  right : (or/c 'call 'put #f)
  multiplier : (or/c rational? #f)
  exchange : string?
  currency : string?
  local-symbol : string?
  trading-class : string?
  execution-id : string?
  timestamp : moment?
  account : string?
  executing-exchange : string?
  side : string?
  shares : rational?
  price : rational?
  perm-id : integer?
  client-id : integer?
  liquidation : integer?
  cumulative-quantity : integer?
  average-price : rational?
  order-reference : string?
  ev-rule : string?
  ev-multiplier : (or/c rational? #f)
  model-code : string?
It is recommended to periodically call executions-req% to make sure you receive all of the executions that have occurred.

struct

(struct historical-data-rsp (request-id
    start-moment
    end-moment
    bars)
    #:extra-constructor-name make-historical-data-rsp)
  request-id : integer?
  start-moment : moment?
  end-moment : moment?
  bars : (listof bar?)
Be sure to check for err-rsps if you are not receiving historical data when you expect to.

struct

(struct market-data-rsp (request-id type value)
    #:extra-constructor-name make-market-data-rsp)
  request-id : integer?
  type : symbol?
  value : rational?
More information about tick types can be found in the IBKR Docs.

struct

(struct next-valid-id-rsp (order-id)
    #:extra-constructor-name make-next-valid-id-rsp)
  order-id : integer?
This response should be saved locally so that calls to place-order-req% can include this saved value. It is not recommended to just track order IDs independently of what the API is giving you. As a reminder, it is necessary to provide an order ID to place-order-req%.

struct

(struct open-order-rsp (order-id
    contract-id
    symbol
    security-type
    expiry
    strike
    right
    multiplier
    exchange
    currency
    local-symbol
    trading-class
    action
    total-quantity
    order-type
    limit-price
    aux-price
    time-in-force
    oca-group
    account
    open-close
    origin
    order-ref
    client-id
    perm-id
    outside-rth
    hidden
    discretionary-amount
    good-after-time
    advisor-group
    advisor-method
    advisor-percentage
    advisor-profile
    model-code
    good-till-date
    rule-80-a
    percent-offset
    settling-firm
    short-sale-slot
    designated-location
    exempt-code
    auction-strategy
    starting-price
    stock-ref-price
    delta
    stock-range-lower
    stock-range-upper
    display-size
    block-order
    sweep-to-fill
    all-or-none
    minimum-quantity
    oca-type
    electronic-trade-only
    firm-quote-only
    nbbo-price-cap
    parent-id
    trigger-method
    volatility
    volatility-type
    delta-neutral-order-type
    delta-neutral-aux-price
    delta-neutral-contract-id
    delta-neutral-settling-firm
    delta-neutral-clearing-account
    delta-neutral-clearing-intent
    delta-neutral-open-close
    delta-neutral-short-sale
    delta-neutral-short-sale-slot
    delta-neutral-designated-location
    continuous-update
    reference-price-type
    trailing-stop-price
    trailing-percent
    basis-points
    basis-points-type
    combo-legs-description
    combo-legs
    order-combo-legs
    smart-combo-routing-params
    scale-init-level-size
    scale-subs-level-size
    scale-price-increment
    scale-price-adjust-value
    scale-price-adjust-interval
    scale-profit-offset
    scale-auto-reset
    scale-init-position
    scale-init-fill-quantity
    scale-random-percent
    hedge-type
    hedge-param
    opt-out-smart-routing
    clearing-account
    clearing-intent
    not-held
    delta-neutral-underlying-contract-id
    delta-neutral-underlying-delta
    delta-neutral-underlying-price
    algo-strategy
    algo-strategy-params
    solicited
    what-if
    status
    initial-margin-before
    maintenance-margin-before
    equity-with-loan-before
    initial-margin-change
    maintenance-margin-change
    equity-with-loan-change
    initial-margin-after
    maintenance-margin-after
    equity-with-loan-after
    commission
    minimum-commission
    maximum-commission
    commission-currency
    warning-text
    randomize-size
    randomize-price
    reference-contract-id
    is-pegged-change-amount-decrease
    pegged-change-amount
    reference-change-amount
    reference-exchange-id
    conditions
    adjusted-order-type
    trigger-price
    trail-stop-price
    limit-price-offset
    adjusted-stop-price
    adjusted-stop-limit-price
    adjusted-trailing-amount
    adjusted-trailing-unit
    soft-dollar-tier-name
    soft-dollar-tier-value
    soft-dollar-tier-display-name
    cash-quantity
    dont-use-auto-price-for-hedge
    is-oms-container
    discretionary-up-to-limit-price
    use-price-management-algo)
    #:extra-constructor-name make-open-order-rsp)
  order-id : integer?
  contract-id : integer?
  symbol : string?
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
  expiry : (or/c date? #f)
  strike : (or/c rational? #f)
  right : (or/c 'call 'put #f)
  multiplier : (or/c rational? #f)
  exchange : string?
  currency : string?
  local-symbol : string?
  trading-class : string?
  action : (or/c 'buy 'sell 'sshort)
  total-quantity : rational?
  order-type : string?
  limit-price : (or/c rational? #f)
  aux-price : (or/c rational? #f)
  time-in-force : 
(or/c 'day 'gtc 'opg 'ioc 'gtd 'gtt
      'auc 'fok 'gtx 'dtc)
  oca-group : string?
  account : string?
  open-close : (or/c 'open 'close #f)
  origin : (or/c 'customer 'firm)
  order-ref : string?
  client-id : integer?
  perm-id : integer?
  outside-rth : boolean?
  hidden : boolean?
  discretionary-amount : (or/c rational? #f)
  good-after-time : (or/c moment? #f)
  advisor-group : string?
  advisor-method : string?
  advisor-percentage : string?
  advisor-profile : string?
  model-code : string?
  good-till-date : (or/c date? #f)
  rule-80-a : string?
  percent-offset : (or/c rational? #f)
  settling-firm : string?
  short-sale-slot : (or/c 0 1 2)
  designated-location : string?
  exempt-code : integer?
  auction-strategy : (or/c 'match 'improvement 'transparent #f)
  starting-price : (or/c rational? #f)
  stock-ref-price : (or/c rational? #f)
  delta : (or/c rational? #f)
  stock-range-lower : (or/c rational? #f)
  stock-range-upper : (or/c rational? #f)
  display-size : (or/c integer? #f)
  block-order : boolean?
  sweep-to-fill : boolean?
  all-or-none : boolean?
  minimum-quantity : (or/c integer? #f)
  oca-type : integer?
  electronic-trade-only : boolean?
  firm-quote-only : boolean?
  nbbo-price-cap : (or/c rational? #f)
  parent-id : integer?
  trigger-method : integer?
  volatility : (or/c rational? #f)
  volatility-type : (or/c integer? #f)
  delta-neutral-order-type : string?
  delta-neutral-aux-price : (or/c rational? #f)
  delta-neutral-contract-id : (or/c integer? #f)
  delta-neutral-settling-firm : string?
  delta-neutral-clearing-account : string?
  delta-neutral-clearing-intent : string?
  delta-neutral-open-close : (or/c 'open 'close #f)
  delta-neutral-short-sale : boolean?
  delta-neutral-short-sale-slot : (or/c integer? #f)
  delta-neutral-designated-location : string?
  continuous-update : integer?
  reference-price-type : (or/c integer? #f)
  trailing-stop-price : (or/c rational? #f)
  trailing-percent : (or/c rational? #f)
  basis-points : (or/c rational? #f)
  basis-points-type : (or/c integer? #f)
  combo-legs-description : string?
  combo-legs : (listof combo-leg?)
  order-combo-legs : (listof rational?)
  smart-combo-routing-params : hash?
  scale-init-level-size : (or/c integer? #f)
  scale-subs-level-size : (or/c integer? #f)
  scale-price-increment : (or/c rational? #f)
  scale-price-adjust-value : (or/c rational? #f)
  scale-price-adjust-interval : (or/c integer? #f)
  scale-profit-offset : (or/c rational? #f)
  scale-auto-reset : boolean?
  scale-init-position : (or/c integer? #f)
  scale-init-fill-quantity : (or/c integer? #f)
  scale-random-percent : boolean?
  hedge-type : string?
  hedge-param : string?
  opt-out-smart-routing : boolean?
  clearing-account : string?
  clearing-intent : (or/c 'ib 'away 'pta #f)
  not-held : boolean?
  delta-neutral-underlying-contract-id : (or/c integer? #f)
  delta-neutral-underlying-delta : (or/c rational? #f)
  delta-neutral-underlying-price : (or/c rational? #f)
  algo-strategy : string?
  algo-strategy-params : hash?
  solicited : boolean?
  what-if : boolean?
  status : string?
  initial-margin-before : (or/c rational? #f)
  maintenance-margin-before : (or/c rational? #f)
  equity-with-loan-before : (or/c rational? #f)
  initial-margin-change : (or/c rational? #f)
  maintenance-margin-change : (or/c rational? #f)
  equity-with-loan-change : (or/c rational? #f)
  initial-margin-after : (or/c rational? #f)
  maintenance-margin-after : (or/c rational? #f)
  equity-with-loan-after : (or/c rational? #f)
  commission : (or/c rational? #f)
  minimum-commission : (or/c rational? #f)
  maximum-commission : (or/c rational? #f)
  commission-currency : string?
  warning-text : string?
  randomize-size : boolean?
  randomize-price : boolean?
  reference-contract-id : (or/c integer? #f)
  is-pegged-change-amount-decrease : boolean?
  pegged-change-amount : (or/c rational? #f)
  reference-change-amount : (or/c rational? #f)
  reference-exchange-id : string?
  conditions : (listof condition?)
  adjusted-order-type : 
(or/c 'mkt 'lmt 'stp 'stp-limit
      'rel 'trail 'box-top 'fix-pegged
      'lit 'lmt-+-mkt 'loc 'mit
      'mkt-prt 'moc 'mtl 'passv-rel
      'peg-bench 'peg-mid 'peg-mkt 'peg-prim
      'peg-stk 'rel-+-lmt 'rel-+-mkt 'snap-mid
      'snap-mkt 'snap-prim 'stp-prt 'trail-limit
      'trail-lit 'trail-lmt-+-mkt 'trail-mit
      'trail-rel-+-mkt 'vol 'vwap 'quote 'ppv
      'pdv 'pmv 'psv #f)
  trigger-price : (or/c rational? #f)
  trail-stop-price : (or/c rational? #f)
  limit-price-offset : (or/c rational? #f)
  adjusted-stop-price : (or/c rational? #f)
  adjusted-stop-limit-price : (or/c rational? #f)
  adjusted-trailing-amount : (or/c rational? #f)
  adjusted-trailing-unit : integer?
  soft-dollar-tier-name : string?
  soft-dollar-tier-value : string?
  soft-dollar-tier-display-name : string?
  cash-quantity : rational?
  dont-use-auto-price-for-hedge : boolean?
  is-oms-container : boolean?
  discretionary-up-to-limit-price : boolean?
  use-price-management-algo : boolean?
This response is largely just telling you what you already provided to place-order-req%. The fields of interest here are the generated client-id and perm-id.

struct

(struct order-status-rsp (order-id
    status
    filled
    remaining
    average-fill-price
    perm-id
    parent-id
    last-fill-price
    client-id
    why-held
    market-cap-price)
    #:extra-constructor-name make-order-status-rsp)
  order-id : integer?
  status : 
(or/c 'pending-submit 'pending-cancel 'pre-submitted 'submitted
      'api-cancelled 'cancelled 'filled 'inactive)
  filled : rational?
  remaining : rational?
  average-fill-price : rational?
  perm-id : integer?
  parent-id : integer?
  last-fill-price : rational?
  client-id : integer?
  why-held : string?
  market-cap-price : rational?
This response gives a useful summary of the status of an order as well as the amount filled and amount remaining.

struct

(struct portfolio-value-rsp (contract-id
    symbol
    security-type
    expiry
    strike
    right
    multiplier
    exchange
    currency
    local-symbol
    trading-class
    position
    market-price
    market-value
    average-cost
    unrealized-pnl
    realized-pnl
    account-name)
    #:extra-constructor-name make-portfolio-value-rsp)
  contract-id : integer?
  symbol : string?
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
  expiry : (or/c date? #f)
  strike : (or/c rational? #f)
  right : (or/c 'call 'put #f)
  multiplier : (or/c rational? #f)
  exchange : string?
  currency : string?
  local-symbol : string?
  trading-class : string?
  position : rational?
  market-price : rational?
  market-value : rational?
  average-cost : rational?
  unrealized-pnl : rational?
  realized-pnl : rational?
  account-name : string?
These responses are returned alongside account-value-rsps when account-data-req% messages are sent.

4 Base Structs🔗ℹ

 (require interactive-brokers-api/base-structs)
  package: interactive-brokers-api

struct

(struct bar (moment
    open
    high
    low
    close
    volume
    weighted-average-price
    count)
    #:extra-constructor-name make-bar)
  moment : moment?
  open : rational?
  high : rational?
  low : rational?
  close : rational?
  volume : integer?
  weighted-average-price : rational?
  count : integer?
This struct is returned as part of a historical-data-rsp.

struct

(struct combo-leg (contract-id
    ratio
    action
    exchange
    open-close
    short-sale-slot
    designated-location
    exempt-code)
    #:extra-constructor-name make-combo-leg)
  contract-id : integer?
  ratio : integer?
  action : (or/c 'buy 'sell 'sshort)
  exchange : string?
  open-close : (or/c 'same 'open 'close #f)
  short-sale-slot : (or/c 0 1 2)
  designated-location : string?
  exempt-code : integer?
Use combo-leg within place-order-req% when you want to place a spread. This is commonly done for options and will work for many strategies. Note that you can only provide contract-id, which you can retrieve from contract-details-req%.

struct

(struct condition (type
    boolean-operator
    comparator
    value
    contract-id
    exchange
    trigger-method
    security-type
    symbol)
    #:extra-constructor-name make-condition)
  type : 
(or/c 'price 'time 'margin
      'execution 'volume 'percent-change)
  boolean-operator : (or/c 'and 'or)
  comparator : (or/c 'less-than 'greater-than #f)
  value : (or/c rational? moment? #f)
  contract-id : (or/c integer? #f)
  exchange : (or/c string? #f)
  trigger-method : 
(or/c 'default 'double-bid/ask 'last 'double-last
      'bid/ask 'last-of-bid/ask 'mid-point #f)
  security-type : 
(or/c 'stk 'opt 'fut 'cash 'bond 'cfd
      'fop 'war 'iopt 'fwd 'bag 'ind
      'bill 'fund 'fixed 'slb 'news 'cmdty
      'bsk 'icu 'ics #f)
  symbol : (or/c string? #f)
Use condition within place-order-req% when you want your order to either take effect or be canceled only when certain conditions are met.

Where fields are not required for a given condition type, they are not sent to the server and are effectively ignored.