API Reference

View Source

This reference guide provides detailed information about all modules and functions available in the IbkrApi library.

Core Modules

IbkrApi

IbkrApi module that serves as the entry point to the library.

IbkrApi.Config

IbkrApi.Config module for configuration management.

# Get the base URL for API requests
base_url = IbkrApi.Config.base_url()

IbkrApi.HTTP

IbkrApi.HTTP module for rate-limited HTTP requests to the Interactive Brokers Client Portal API.

# Make a GET request
{:ok, response} = IbkrApi.HTTP.get("https://localhost:5000/v1/api/endpoint")

# Make a POST request with a body
body = %{key: "value"}
{:ok, response} = IbkrApi.HTTP.post("https://localhost:5000/v1/api/endpoint", body)

# Make a PUT request
{:ok, response} = IbkrApi.HTTP.put("https://localhost:5000/v1/api/endpoint", body)

# Make a DELETE request
{:ok, response} = IbkrApi.HTTP.delete("https://localhost:5000/v1/api/endpoint")

IbkrApi.Websocket

IbkrApi.Websocket module for real-time streaming data from the Interactive Brokers Client Portal API.

# Create a WebSocket client module
defmodule MyIbkrClient do
  use IbkrApi.Websocket

  def handle_event({:market_data, data}, state) do
    IO.inspect(data, label: "Market Data")
    {:ok, state}
  end

  def handle_event({:order_update, order}, state) do
    IO.inspect(order, label: "Order Update")
    {:ok, state}
  end

  def handle_event({:pnl_update, pnl}, state) do
    IO.inspect(pnl, label: "P&L Update")
    {:ok, state}
  end

  def handle_event(_event, state) do
    {:ok, state}
  end
end

# Start the WebSocket client
{:ok, pid} = MyIbkrClient.start_link(%{})

# Subscribe to market data
MyIbkrClient.subscribe_to_market_data(pid, [8314], ["31", "83"])

# Subscribe to order updates
MyIbkrClient.subscribe_to_order_updates(pid)

# Subscribe to P&L updates
MyIbkrClient.subscribe_to_pnl(pid)

Functions

FunctionDescriptionParametersReturn Value
start_link/1Starts the WebSocket clientstate (Map){:ok, pid} or {:error, reason}
subscribe_to_market_data/3Subscribes to real-time market datapid, conids (List), fields (List):ok
subscribe_to_order_updates/1Subscribes to order status updatespid:ok
subscribe_to_pnl/1Subscribes to portfolio P&L updatespid:ok
unsubscribe_from_market_data/2Unsubscribes from market datapid, conids (List):ok
unsubscribe_from_order_updates/1Unsubscribes from order updatespid:ok
unsubscribe_from_pnl/1Unsubscribes from P&L updatespid:ok

Client Portal Modules

IbkrApi.ClientPortal.Auth

IbkrApi.ClientPortal.Auth module for authentication and session management.

Functions

FunctionDescriptionParametersReturn Value
ping_server/0Checks server connectivity and authentication statusNone{:ok, %PingServerResponse{}} or {:error, reason}
reauthenticate/0Attempts to reauthenticate an expired sessionNone{:ok, %ReauthenticateResponse{}} or {:error, reason}
end_session/0Ends the current sessionNone{:ok, %EndSessionResponse{}} or {:error, reason}
validate_sso/0Validates Single Sign-On statusNone{:ok, %ValidateSSOResponse{}} or {:error, reason}
check_auth_status/0Checks the current authentication statusNone{:ok, %CheckAuthStatusResponse{}} or {:error, reason}

IbkrApi.ClientPortal.Portfolio

IbkrApi.ClientPortal.Portfolio module for managing account information, positions, and portfolio operations.

Functions

FunctionDescriptionParametersReturn Value
list_accounts/0Lists all portfolio accountsNone{:ok, [%Account{}]} or {:error, reason}
list_sub_accounts/0Lists all sub-accountsNone{:ok, [%SubAccount{}]} or {:error, reason}
account_info/1Gets account metadataaccount_id (String){:ok, %Account{}} or {:error, reason}
account_summary/1Gets account summary with dynamic fieldsaccount_id (String){:ok, %AccountSummary{}} or {:error, reason}
account_ledger/1Gets account ledger by currencyaccount_id (String){:ok, %AccountLedger{}} or {:error, reason}
list_brokerage_accounts/0Lists all brokerage accountsNone{:ok, %BrokerageAccountsResponse{}} or {:error, reason}
switch_account/1Switches the active accountacct_id (String){:ok, %SwitchAccountResponse{}} or {:error, reason}
get_pnl/0Gets profit and loss informationNone{:ok, %PnLResponse{}} or {:error, reason}
account_allocation/1Gets account allocation by groupaccount_id (String){:ok, [%Allocation{}]} or {:error, reason}
all_accounts_allocation/1Gets allocation for all accountsaccount_id (String){:ok, [%Allocation{}]} or {:error, reason}
portfolio_positions/3Gets portfolio positionsaccount_id, page_id, model{:ok, [%Position{}]} or {:error, reason}
position_by_conid/2Gets position by contract IDaccount_id, conid{:ok, [%Position{}]} or {:error, reason}
invalidate_positions_cache/1Invalidates the positions cacheaccount_id{:ok, %{}} or {:error, reason}

IbkrApi.ClientPortal.Contract

IbkrApi.ClientPortal.Contract module for managing financial instruments and contracts.

Functions

FunctionParametersDescriptionReturn
get_contract_info/2conid, optsGet detailed contract information{:ok, [SecdefInfo.t()]}
get_trading_schedule/3asset_class, symbol, optsGet trading schedule for symbol{:ok, TradingSchedule.t()}
security_stocks_by_symbol/1symbolGet stock security definition{:ok, StockSecurityDefinition.t()}
get_exchange_rate/2source, targetGet currency exchange rate{:ok, float()}
get_available_currency_pairs/1currencyGet available currency pairs{:ok, [CurrencyPair.t()]}
search_contracts/2symbol, optsSearch contracts by symbol{:ok, [SearchContract.t()]}
get_strikes/4contract_id, sec_type, month, optsGet option strikes for contract{:ok, StrikesResponse.t()}
get_strikes/1symbolGet strikes for symbol (convenience){:ok, StrikesResponse.t()}
contract_details/1conidGet contract details{:ok, map()}
get_stock_security_definition/1symbolGet stock security definition{:ok, map()}
get_options_for_symbol/2symbol, optsGet options for symbol{:ok, map()}

IbkrApi.ClientPortal.MarketData

Real-time and historical market data.

FunctionParametersDescriptionReturn
get_market_data_snapshot/2conids, optsGet live market data snapshots{:ok, [MarketDataSnapshot.t()]}
get_historical_data/4conid, period, bar, optsGet historical market data{:ok, [HistoricalBar.t()]}

MarketDataSnapshot Fields:

  • Price fields: last_price, bid_price, ask_price, high, low, open, close
  • Volume fields: volume, bid_size, ask_size, last_size, average_volume
  • Change fields: change, change_percent, change_since_open
  • P&L fields: market_value, unrealized_pnl, daily_pnl, realized_pnl
  • Greeks (options): delta, gamma, theta, vega
  • Company info: company_name, symbol, industry, category
  • Financial metrics: market_cap, pe_ratio, eps, beta

IbkrApi.ClientPortal.Order

IbkrApi.ClientPortal.Order module for managing order placement and monitoring.

Functions

FunctionParametersDescriptionReturn
get_live_orders/0-Get all live orders{:ok, OrderResponse.t()}
get_order_status/1order_idGet order status{:ok, OrderStatusResponse.t()}
place_orders/2account_id, ordersPlace new orders{:ok, [OrderPlacementResponse.t()]}
place_orders_for_fa/2fa_group, ordersPlace orders for FA group{:ok, [OrderPlacementResponse.t()]}
modify_order/3account_id, order_id, requestModify existing order{:ok, ModifyOrderResponse.t()}
cancel_order/2account_id, order_idCancel order{:ok, CancelOrderResponse.t()}
preview_order/2account_id, ordersPreview order before placement{:ok, OrderPreviewResponse.t()}
reply_to_order_query/2reply_id, confirmedReply to order confirmation query{:ok, OrderReplyResponse.t()}

Order Types Supported:

  • Market orders (MKT)
  • Limit orders (LMT)
  • Stop orders (STP)
  • Stop-limit orders (STP LMT)
  • Trailing stop orders with amount or percentage
  • Adaptive orders for better execution

IbkrApi.ClientPortal.Trade

Trade execution history and details.

FunctionParametersDescriptionReturn
list_trades/0-Get all trade executions{:ok, [Trade.t()]}

Trade Fields:

  • Execution info: execution_id, trade_time, size, price
  • Order info: order_description, order_ref, side
  • Contract info: symbol, conid, sec_type, company_name
  • Financial info: commission, net_amount, position
  • Account info: account, account_code, clearing_id

IbkrApi.ClientPortal.Profile

IbkrApi.ClientPortal.Profile module for managing user profile information.

Functions

FunctionDescriptionParametersReturn Value
get_profile/0Gets user profile informationNone{:ok, %Profile{}} or {:error, reason}
update_profile/1Updates user profileprofile_params (Map){:ok, %UpdateProfileResponse{}} or {:error, reason}

IbkrApi.ClientPortal.Trade

IbkrApi.ClientPortal.Trade module for managing trade executions and history.

Functions

FunctionDescriptionParametersReturn Value
get_executions/1Gets trade executions for an accountaccount_id (String){:ok, [%Execution{}]} or {:error, reason}

Error Handling

All API functions return {:ok, result} on success and {:error, reason} on failure. The error reason is typically an ErrorMessage struct with the following fields:

%ErrorMessage{
  code: "1234",       # Error code
  message: "Error message description",
  description: "Detailed error description"
}

Common Error Codes

CodeDescription
"1015"Account not found or not authorized
"1021"Session expired, please reauthenticate
"1022"Invalid contract ID
"1100"Invalid order parameters
"1101"Insufficient funds
"2000"Server error