IBKR 3rd Party Web API

盈透官方API文档写的跟屎一样,在这里重新整理了一下

IBKR 3rd Party Web API

Interactive Brokers Web API for 3rd Party Companies

version: 1.0.0

Host: www.interactivebrokers.com

httpsBasePath: /tradingapi/v1

content-type: application/json

cookieAuth

type : API key

header param name: portal

OAuth

1. Obtain a request token

Obtain a request token. See section 6.1 of the OAuth v1.0a specification for more information. http://oauth.net/core/1.0a/#auth_step1

Note: We do not return an oauth_token_secret in the response as we are using RSA signatures rather than PLAINTEXT authentication

Requests:

​ paths:/oauth/request_token

​ method : POST

Authorizations: cookieAuth

​ content-type : application/json

​ OAuth Parameters:

name type description
oauth_consumer_key string The 25-character hexadecimal string that was obtained from Interactive Brokers during the OAuth consumer registration process
oauth_signature_method string The signature method used to sign the request. Currently only ‘RSA-SHA256’ is supported.
oauth_signature string The signature for the request generated using the method specified in the oauth_signature_method parameter. See section 9 of the OAuth v1.0a specification for more details on signing requests.
oauth_timestamp string Timestamp expressed in seconds since 1/1/1970 00:00:00 GMT. Must be a positive integer and greater than or equal to any timestamp used in previous requests
oauth_nonce string A random string uniquely generated for each request.
oauth_callback type An absolute URL to which IB will redirect the user. This URL is provided by the consumer during registration. This parameter must be set to ‘oob’.

Response:

– 200 status–

content-type : application/json

type:object

{
    "oauth_token":"string",
}

2. Obtain a access token

Obtain an access token using the request token and the verification code you received after the user provided authorization. See section 6.3 of the OAuth v1.0a specification for more details.

Requests:

​ paths:/oauth/access_token

​ method : POST

​ Authorizations: cookieAuth

​ content-type : application/json

​ OAuth Parameters:

name type description
oauth_consumer_key string The 25-character hexadecimal string that was obtained from Interactive Brokers during the OAuth consumer registration process.
oauth_token string The request token obtained from IB via /request_token.
oauth_signature_method string The signature method used to sign the request. Currently only ‘RSA-SHA256’ is supported.
oauth_signature string The signature for the request generated using the method specified in the oauth_signature_method parameter. See section 9 of the OAuth v1.0a specification for more details on signing requests.
oauth_timestamp string Timestamp expressed in seconds since 1/1/1970 00:00:00 GMT. Must be a positive integer and greater than or equal to any timestamp used in previous requests.
oauth_nonce string A random string uniquely generated for each request.
oauth_verifier string The verification code received from IB after the user has granted authorization.

Response:

– 200 status–

content-type : application/json

type:object

{
    "oauth_token": "string",
    "oauth_token_secret":"string",
}

3. Obtain a live session token

In order to access protected IB resources, a live session token is required. This endpoint allows consumers to obtain a live session token to access these resources using an OAuth access token and the Diffie-Hellman prime and generator supplied during the registration process.
Note: this is an additional IB-specific step, and not part of the OAuth v1.0a specification. Please refer to the “OAuth at Interactive Brokers” document for more details. https://www.interactivebrokers.com/webtradingapi/oauth.pdf

Requests:

​ paths:/oauth/live_session_token

​ method : POST

Authorizations: cookieAuth

​ content-type : application/json

​ OAuth Parameters:

name type description
oauth_consumer_key string The 25-character hexadecimal string that was obtained from Interactive Brokers during the OAuth consumer registration process.
oauth_token string The request token obtained from IB via /request_token.
oauth_signature_method string The signature method used to sign the request. Currently only ‘RSA-SHA256’ is supported.
oauth_signature string The signature for the request generated using the method specified in the oauth_signature_method parameter. See section 9 of the OAuth v1.0a specification for more details on signing requests.
oauth_timestamp string Timestamp expressed in seconds since 1/1/1970 00:00:00 GMT. Must be a positive integer and greater than or equal to any timestamp used in previous requests.
oauth_nonce string A random string uniquely generated for each request.
diffie_hellman_challenge string Challenge value calculated using the Diffie-Hellman prime and generated provided during the registration process. See the “OAuth at Interactive Brokers” document for more details.

Response:

– 200 status–

content-type :application/json

type:object

{
  "diffie_hellman_response": "string",
  "live_session_token_signature": "string"
}

Account & Portfolio

1. Brokerage Accounts

Allows the caller to request a list of accounts associated with the session.

Requests:

​ Paths:/accounts

​ Method : GET

​ Authorizations: cookieAuth

​ Path Parameters:

name required type description
account true string Account Number

Response:

– 200 status–

content-type :application/json

type:object

{

    "accounts": 

    [
        "string"
    ]

}

2. Account Positions

Returns a list of positions for the indicated account.

Requests:

​ Paths:/accounts/{account}/positions

​ Method : GET

​ Authorizations: cookieAuth

​ Path Parameters:

name required type description
account true string Account Number

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "Position": 0,
    "AverageCost": 0,
    "ContractId": 0
  }
]

2. Account Values Summary

Returns a list of account and margin balances associated with the account passed in the URL

Requests:

​ Paths:/accounts/{account}/summary

​ Method : GET

​ Authorizations: cookieAuth

​ Path Parameters:

name required type description
account true string Account Number

Response:

– 200 status–

content-type :application/json

type:object

{
  "Ledger": [
    {
      "CashCumQty": 0,
      "ExchangeRate": 0,
      "NetInterest": 0,
      "RealizedPNL": 0,
      "FuturePNL": 0,
      "UnrealizedPNL": 0,
      "OptionMarketValue": 0,
      "StockMarketValue": 0,
      "CashBalance": 0,
      "FutureOptionMarketValue": 0,
      "NetDividend": 0,
      "NetLiquidation": 0,
      "TotalCashBalance": 0,
      "CashBalanceFXSegment": 0
    }
  ],
  "Info": {
    "AccountType": "string",
    "AccountCode": "string",
    "AccountReady": "string",
    "Cushion": "string",
    "DayTradesRemaining": "string",
    "DayTradesRemainingT": "string",
    "DayTradesRemainingT+2": "string",
    "DayTradesRemainingT+3": "string",
    "DayTradesRemainingT+4": "string",
    "HighestSeverity": "string",
    "Leverage-S": "string",
    "LookAheadNextChange": "string",
    "SegmentTitle-C": "string",
    "SegmentTitle-S": "string",
    "TradingType-S": "string",
    "WhatIfPMEnabled": "string"
  },
  "Summary": {
    "AccruedCash": 0,
    "AccruedCash-C": 0,
    "AccruedCash-S": 0,
    "AccruedDividend": 0,
    "AccruedDividend-C": 0,
    "AccruedDividend-S": 0,
    "AvailableFunds": 0,
    "AvailableFunds-C": 0,
    "AvailableFunds-S": 0,
    "Billable": 0,
    "Billable-C": 0,
    "Billable-S": 0,
    "BuyingPower": 0,
    "EquityWithLoanValue": 0,
    "EquityWithLoanValue-C": 0,
    "EquityWithLoanValue-S": 0,
    "ExcessLiquidity": 0,
    "ExcessLiquidity-C": 0,
    "ExcessLiquidity-S": 0,
    "FullAvailableFunds": 0,
    "FullAvailableFunds-C": 0,
    "FullAvailableFunds-S": 0,
    "FullExcessLiquidity": 0,
    "FullExcessLiquidity-C": 0,
    "FullExcessLiquidity-S": 0,
    "FullInitMarginReq": 0,
    "FullInitMarginReq-C": 0,
    "FullInitMarginReq-S": 0,
    "FullMaintMarginReq": 0,
    "FullMaintMarginReq-C": 0,
    "FullMaintMarginReq-S": 0,
    "GrossPositionValue": 0,
    "GrossPositionValue-C": 0,
    "GrossPositionValue-S": 0,
    "IndianStockHaircut": 0,
    "IndianStockHaircut-C": 0,
    "IndianStockHaircut-S": 0,
    "InitMarginReq": 0,
    "InitMarginReq-C": 0,
    "InitMarginReq-S": 0,
    "InsuredDeposit": 0,
    "InsuredDeposit-C": 0,
    "InsuredDeposit-S": 0,
    "LookAheadAvailableFunds": 0,
    "LookAheadAvailableFunds-C": 0,
    "LookAheadAvailableFunds-S": 0,
    "LookAheadExcessLiquidity": 0,
    "LookAheadExcessLiquidity-C": 0,
    "LookAheadExcessLiquidity-S": 0,
    "LookAheadInitMarginReq": 0,
    "LookAheadInitMarginReq-C": 0,
    "LookAheadInitMarginReq-S": 0,
    "LookAheadMaintMarginReq": 0,
    "LookAheadMaintMarginReq-C": 0,
    "LookAheadMaintMarginReq-S": 0,
    "MaintMarginReq": 0,
    "MaintMarginReq-C": 0,
    "MaintMarginReq-S": 0,
    "NetLiquidation": 0,
    "NetLiquidation-C": 0,
    "NetLiquidation-S": 0,
    "NetLiquidationUncertainty": 0,
    "PASharesValue": 0,
    "PASharesValue-C": 0,
    "PASharesValue-S": 0,
    "PostExpirationExcess": 0,
    "PostExpirationExcess-C": 0,
    "PostExpirationExcess-S": 0,
    "PostExpirationMargin": 0,
    "PostExpirationMargin-C": 0,
    "PostExpirationMargin-S": 0,
    "RegTEquity": 0,
    "RegTEquity-S": 0,
    "RegTMargin": 0,
    "RegTMargin-S": 0,
    "SMA": 0,
    "SMA-S": 0,
    "TotalCashValue": 0,
    "TotalCashValue-C": 0,
    "TotalCashValue-S": 0
  }
}

Orders

1. Open Orders

Returns a list of orders for the account passed in the URL

Requests:

​ Paths:/accounts/{account}/orders

​ Method : GET

​ Authorizations: cookieAuth

​ Path Parameters:

name required type description
account true string Account Number

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "CustomerOrderId": 0,
    "ContractId": 0,
    "Ticker": "string",
    "ListingExchange": "string",
    "RemainingQuantity": 0,
    "FilledQuantity": 0,
    "OrderType": 1,
    "TimeInForce": 0,
    "OutsideRTH": "string",
    "Side": 1,
    "Price": 0,
    "Status": "-1",
    "Warning": "string",
    "TransactionTime": "string"
  }
]

2. Place Order

Requests:

​ Paths:/accounts/{account}/orders

​ Method : POST

Authorizations: cookieAuth

Path Parameters:

name required type description
account true string Account Number

content-type : application/json

Order Parameters:

name type description
CustomerOrderId string The order ID assigned by the customer.
Ticker string The symbol that identifies the trading product
ListingExchange string The exchange on which the trading product is listed (only for InstrumentType=STK)
Currency string The currency in which the FX pair trades (only for InstrumentType=CASH)
InstrumentType string The instrument type of the contract
ContractId number The internal IB identifier for the trading product specified as an integer (can be obtained in response to /secdef request)
Quantity number The number of units in the order; contracts or shares
Price number The order price
Order Type number Enum: [0, 1, 2 , 3, 7 ](1 Market ,2 Limit 3 Stop ,4 StopLimit )
Aux Price number Required Price to support Stop and Stop Limit orders
Time in Force number Enum: [0, 1, 2 , 3, 7 ](Defines order’s active lifetime. Day = ‘0’ GTC (Good till Cancel) = ‘1’ IOC (Immediate or Cancel) = ‘3’ Open = ‘2’ Close = ‘7’)
Outside RTH number Indicates if order is active outside regular trading hours,where defined. 0 = no (default), 1 = yes
Side number Enum: [1, 2 ](‘Buy = ‘‘1’’, Sell = ‘‘2’’’)
OrderRestrictions number MultiValueString representing the restrictions associated with an order. If more than one restriction is applicable to an order, this field can contain multiple instructions separated by space.
‘1’ Program Trade
‘2’ Index Arbitrage
‘3’ Non-Index Arbitrage
GermanHftAlgo boolean By setting this bool to false the customer attests that theorder is not subject to German HFT Act, was not generated using any automated algorithm, and no algorithm determined or changed financial instrument, side, quantity, order type,limit or other price, trading venue or timing of this order.
Currently we cannot accept orders where this flag is set to true. Such orders will be rejected.
Mifid2DecisionMaker string This field permits specification of the user’s preregistered (via account management) MiFID II short code for decision makers.
Mifid2Algo string This field permits specification of the user’s preregistered (via account management) MiFID II short code for algos that are responsible for investment decisions
Mifid2ExecutionTrader string This field permits specification of the user’s preregistered (via account management) MiFID II person responsible for handling/routing of the order
Mifid2ExecutionAlgo string This field permits specification of the user’s preregistered (via account management) MiFID II short code for algos that are responsible for handling/routing of the order.

To specify the contract, you provide a value for the ContractId field, OR Ticker/ListingExchange/InstrumentType=STK for stocks OR Ticker/Currency/InstrumentType=CASH for FX.

Required Fields For Security Resolution

Asset Class Instrument Type Required Fields Example
Stocks STK ContractId
or
InstrumentType
Ticker
ListingExchange
8314
or
STK
IBM
NYSE
FX CASH ContractId
or
InstrumentType
Ticker
Currency
12087795
or
CASH
EUR
USD

Transmits an order tagged with the specified CustomerOrderId for the account passed in the URL.

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "CustomerOrderId": 0,
    "ContractId": 0,
    "Ticker": "string",
    "ListingExchange": "string",
    "RemainingQuantity": 0,
    "FilledQuantity": 0,
    "OrderType": 1,
    "TimeInForce": 0,
    "OutsideRTH": "string",
    "Side": 1,
    "Price": 0,
    "Status": "-1", //Status of the order InvalidOrderStatus = '-1' New = '0' PartiallyFilled = '1' Filled = '2' DoneForTheDay = '3' Canceled = '4' Replaced = '5' PendingCancelReplace = '6' Stopped = '7' Rejected = '8' Suspended = '9' PendingNew = 'A' Calculated = 'B' Expired = 'C' AcceptedForBidding = 'D' PendingReplace = 'E'
    "Warning": "string",
    "TransactionTime": "string"
  }
]

3. Return specific order info

Returns the order with the referenced Customer Order ID for the account passed in the URL.

Requests:

​ Paths:/accounts/{account}/orders/{CustomerOrderId}

​ Method : GET

Authorizations: cookieAuth

Path Parameters:

name required type description
account true string Account Number
CustomerOrderId true string CustomerOrderId

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "CustomerOrderId": 0,
    "ContractId": 0,
    "Ticker": "string",
    "ListingExchange": "string",
    "RemainingQuantity": 0,
    "FilledQuantity": 0,
    "OrderType": 1,
    "TimeInForce": 0,
    "OutsideRTH": "string",
    "Side": 1,
    "Price": 0,
    "Status": "-1",
    "Warning": "string",
    "TransactionTime": "string"
  }
]

4. Cancel Order

Cancels the order with the referenced Customer Order ID for the account passed in the URL.

Requests:

​ Paths:/accounts/{account}/orders/{CustomerOrderId}

​ Method : DELETE

Authorizations: cookieAuth

Path Parameters:

name required type description
account true string Account Number
CustomerOrderId true string CustomerOrderId

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "CustomerOrderId": "string",
    "Symbol": 0,
    "OrderQty": 0,
    "Price": "string",
    "Side": 1,
    "Status": "-1",
    "Warning": "string",
    "OrderType": 1
  }
]

5. Modify Order

Allows the caller to modify the order with the referenced Customer Order ID specified in the URL. A separate Customer Order ID must be provided in the request body for the modification.

Requests:

​ Paths:/accounts/{account}/orders/{CustomerOrderId}

​ Method : PUT

Authorizations: cookieAuth

Path Parameters:

name required type description
account true string Account Number
CustomerOrderId true string CustomerOrderId

content-type : application/json

Order Parameters:

name type description
OrigCustomerOrderId string he order ID assigned by the customer
CustomerOrderId string The new order ID assigned by the customer for the modification.
Quantity number The number of units in the order; contracts or shares
Price number The order price
Order Type number Enum: [0, 1, 2 , 3, 7 ](1 Market ,2 Limit 3 Stop ,4 StopLimit )
Aux Price number Required Price to support Stop and Stop Limit orders
Time in Force number Enum: [0, 1, 2 , 3, 7 ](Defines order’s active lifetime. Day = ‘0’ GTC (Good till Cancel) = ‘1’ IOC (Immediate or Cancel) = ‘3’ Open = ‘2’ Close = ‘7’)
Outside RTH number Indicates if order is active outside regular trading hours,where defined. 0 = no (default), 1 = yes
Side number Enum: [1, 2 ](‘Buy = ‘‘1’’, Sell = ‘‘2’’’)
GermanHftAlgo boolean By setting this bool to false the customer attests that theorder is not subject to German HFT Act, was not generated using any automated algorithm, and no algorithm determined or changed financial instrument, side, quantity, order type,limit or other price, trading venue or timing of this order.
Currently we cannot accept orders where this flag is set to true. Such orders will be rejected.
Mifid2DecisionMaker string This field permits specification of the user’s preregistered (via account management) MiFID II short code for decision makers.
Mifid2Algo string This field permits specification of the user’s preregistered (via account management) MiFID II short code for algos that are responsible for investment decisions
Mifid2ExecutionTrader string This field permits specification of the user’s preregistered (via account management) MiFID II person responsible for handling/routing of the order
Mifid2ExecutionAlgo string This field permits specification of the user’s preregistered (via account management) MiFID II short code for algos that are responsible for handling/routing of the order.

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "CustomerOrderId": "string",
    "Symbol": 0,
    "OrderQty": 0,
    "Price": "string",
    "Side": 1,
    "Status": "-1",
    "Warning": "string",
    "OrderType": 1
  }
]

Order Margin Requirements

1.Return margin impact info

This endpoint allows the consumer to check the impact that an order would have on the account, including margin, NLV and estimated commission costs. To specify the contract, you provide a value for the ContractId field, OR Ticker/ListingExchange/InstrumentType=STK for stocks OR Ticker/Currency/InstrumentType=CASH for FX.

Requests:

​ Paths:/accounts/{account}/order_impact

​ Method : POST

Authorizations: cookieAuth

Path Parameters:

name required type description
account true string Account Number

content-type : application/json

Order Parameters:

name type description
CustomerOrderId string The order ID assigned by the customer.
Ticker string The symbol that identifies the trading product
ListingExchange string The exchange on which the trading product is listed (only for InstrumentType=STK)
Currency string The currency in which the FX pair trades (only for InstrumentType=CASH)
InstrumentType string The instrument type of the contract
ContractId number The internal IB identifier for the trading product specified as an integer (can be obtained in response to /secdef request)
Quantity number The number of units in the order; contracts or shares
Price number The order price
Order Type number Enum: [0, 1, 2 , 3, 4 ](1 Market ,2 Limit 3 Stop ,4 StopLimit )
Aux Price number Required Price to support Stop and Stop Limit orders
Time in Force number Enum: [0, 1, 2 , 3, 7 ](Defines order’s active lifetime. Day = ‘0’ GTC (Good till Cancel) = ‘1’ IOC (Immediate or Cancel) = ‘3’ Open = ‘2’ Close = ‘7’)
Outside RTH number Indicates if order is active outside regular trading hours,where defined. 0 = no (default), 1 = yes
Side number Enum: [1, 2 ](‘Buy = ‘‘1’’, Sell = ‘‘2’’’)

Response:

– 200 status–

content-type :application/json

type:object

{
  "EquityWithLoan": 0,
  "InitMargin": 0,
  "InitMarginBefore": 0,
  "MaintMargin": 0,
  "MaintMarginBefore": 0,
  "MarginCurrency": "string",
  "Commission": 0,
  "MinCommissions": 0,
  "MaxCommissions": 0,
  "CommissionsCurrency": "string"
}

Trades

1. Returns trades in account

Returns a list of trades for the account starting at the given ‘since’ date to the current time (now()). Timezone is UTC. Any request with a future since date or going further than one week will result in an HTTP 400 bad request response. Calling /trades without since will return all trades for the past 24 hours.

Requests:

​ Paths:/accounts/{account}/trades

​ Method : GET

​ Authorizations: cookieAuth

​ Path Parameters:

name required type description
account true string Account Number

​ Body Parameters:

name required type description
since false string Start time specified in UTC. Allowed formats are “yyyy-MM-dd” or “yyyy-MM-dd’T’HH:mm:ss”. Time is optional and is set to midnight if omitted, e.g. “00:00:00 hh:mm:ss”.

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "CustomerOrderId": 0,
    "ContractId": 0,
    "OrderId": "string",
    "Ticker": "string",
    "ListingExchange": "string",
    "Currency": "string",
    "Side": 1,
    "OrderType": 1,
    "FilledQuantity": 0,
    "RemainingQuantity": 0,
    "Quantity": 0,
    "TradePrice": 0,
    "TradeSize": 0,
    "AvgPrice": 0,
    "ExecutionTime": "string",
    "ExecId": "string",
    "Commission": 0,
    "CommissionCurrency": "string",
    "LastMarket": "string"
  }
]

Financial Instrument Definitions

1. Get security definition

Fields that compose security definition. Allowed combinations, (1) type and symbol and currency, or (2) type, symbol, exchange, and currency, or (3) conid

Requests:

​ Paths:/secdef

​ Method : GET

​ Authorizations: cookieAuth

​ content-type : application/json

​ Order Parameters:

Allowed combinations are [type and symbol and currency], or [type, symbol, exchange, and currency], or [conid].

name type description
type string The instrument type of the contract (CASH).
symbol string The symbol that identifies the trading product.
currency string The currency in which the given pair trades.
exchange string The exchange on which the trading product is listed (required for type=STK).
conid number The internal IB identifier for the trading product specified as an integer.

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "ContractId": 0,
    "Ticker": "string",
    "SecurityType": "string",
    "Exchange": "string",
    "CompanyName": "string",
    "Currency": "string"
  }
]

Market Data

1. Market Data Snapshot

This endpoint allows the consumer to request a market data snapshot for one or more trading products.Consumers need to provide unique identifiers (conids) for the products in the IB product database (retrievable using the /secdef endpoint).

The ‘market’ values are integers whose bits indicate the exchange(s) making up the quote. The mapping of bit to exchange is obtained from the marketdata/exchange_component endpoint.

For example, if a bid has a ‘market’ value of 5 and the exchange_component result has the map

0 => NYSE
1 => ISLAND
2 => ARCA
						

then the exchanges contributing to the bid size are NYSE and ARCA. Similarly, if market=2, then only ISLAND is contributing.

Requests:

​ Paths:/marketdata/snapshot

​ Method : GET

​ Authorizations: cookieAuth

​ content-type : application/json

​ Order Parameters:

Contract. Allowed combinations are [type and symbol and currency], or [type, symbol, exchange, and currency], or [conid].

name type description
type string The instrument type of the contract (CASH).
symbol string The symbol that identifies the trading product.
currency string The currency in which the given pair trades.
exchange string The exchange on which the trading product is listed (required for type=STK).
conid number The internal IB identifier for the trading product specified as an integer.

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "Conid": "string",
    "Temporality": 0, //0 = Real time data 1 = Delayed data
    "Complete": true,
    "Trade": {
      "market": 0,
      "price": 0,
      "size": 0,
      "time": 0
    },
    "Closing": {
      "price": 0
    },
    "Bid": {
      "market": 0,
      "price": 0,
      "size": 0
    },
    "Offer": {
      "market": 0,
      "price": 0,
      "size": 0
    }
  }
]

2. Exchange Components

This endpoint provides a bit mapping for the bid/ask/last ‘market’ values in the snapshot response.

Requests:

​ Paths:/marketdata/exchange_components

​ Method : GET

​ Authorizations: cookieAuth

Response:

– 200 status–

content-type :application/json

type:object

[
  {
    "ConId": 0,
    "Complete": true,
    "mapping": [
      {
        "bit": 0,
        "code": "string",
        "exchange": "string"
      }
    ]
  }
]

你可能感兴趣的:(IBKR 3rd Party Web API)