req_mkt_data: Request Market Data

View source: R/req_mkt_data.R

req_mkt_dataR Documentation

Request Market Data

Description

Fetch live (or 15-minute delayed) market data.

Usage

req_mkt_data(
  contract,
  data_name,
  channel = "async",
  mktDataType = "REALTIME",
  genericTickList = NULL,
  snapshot = FALSE,
  regulatorySnapshot = FALSE
)

Arguments

contract

Named character vector of contract parameter(s). The name of each element identifies the parameter – for example, secType, symbol, exchange... – and each element itself gives the set value (e.g., "STK", "IBM", "SMART").

The 'contract' parameters that may be used with place_order() are:
deltaNeutralContract, secId, conId, comboLegs, secType, tradingClass, symbol, lastTradeDateOrContractMonth, strike, right, multiplier, exchange, primaryExchange, currency, localSymbol, secIdType

See contract for detailed information on all contract parameters.

data_name

Character vector of length 1. If not supplied, req_mkt_data() will use the data name "X_symbol" where X is a simple counting integer and symbol is the value of the symbol parameter in the contract object. If supplied, data_name becomes Your own personal identifier for the market data subscription. Good choices might be the contract's symbol, conId, or description (if combo). All market data received by a mkt_data subscription will be stored in the mkt_data environment under the name data_name. Therefore, no two mkt_data subscriptions may have identical data_names.

channel

One of the following:

  • Not Specified (Default): Opens a new connection to IB, uses it to issue the request and retrieve the response, and closes connection behind itself upon completion.

  • The Name of a Sock: Character vector, length 1. The name of an open, connected socket in the sock_drawer; e.g., "master", "tws", or "sock_123"

  • Numeric Client ID: Numeric, length 1. The client ID for which open orders are to be retrieved; e.g., 0, 874, 123. If a client ID is passed, and no socket in the sock_drawer is connected on that ID, then a new socket will be opened on that ID, and closed upon function exit.

  • A sockconn Connection: An open connection object of class "sockconn", connected to the IB API; e.g., sock_drawer$tws

mktDataType

Either:

  1. String having one of the following values: "REALTIME", "FROZEN", "DELAYED", or "DELAYED_FROZEN".

  2. Integer from 1 to 4, inclusive, corresponding respectively to each of the above choices (e.g., mktDataType = 3 will set the market data type to "DELAYED").

genericTickList

Not yet implemented, stay tuned

snapshot

If set to TRUE, the subscription created by req_mkt_data() will be destroyed after a complete "snapshot" of market data is obtained for the contract. The default is snapshot = FALSE, which will cause the subscription to stay opened until cancelled by the user making a call to cancel_mkt_data().

regulatorySnapshot

Not yet implemented, stay tuned

Details

The attributes canAutoExecute, pastLimit, and preOpen are unnecessary in InteractiveTradeR because you can easily create your own flags that accept market data as input. The aren't that much use anyway, and are mostly holdovers from earlier versions & systems.

No Sync Mode

req_mkt_data() can't be called in Sync Mode. Instead, this function must be implimented as follows:

  1. Create a connection to Interactive Brokers with create_new_connections() if a connection doesn't already exist

  2. Call req_mkt_data() to start a market data subscription

  3. Call read_sock_drawer() to refresh the mkt_data slate. Do this as often as you need to keep mkt_data up-to-date.

  4. Call cancel_mkt_data() when you're finished

If snapshot = TRUE, then the subscription will destroy itself once a full market data snapshot has been obtained by read_sock_drawer(), so there's no need to call cancel_mkt_data().

The mkt_data Slate

Data fetched by req_mkt_data() is stored in the mkt_data slate under the name specified in the data_name argument (or the default data name "X_symbol" if no data_name not supplied).

See Also

Other market data: cancel_mkt_data(), req_market_data_type()

Examples

# --> This example may be run on a paper trading account with no market data
# feed. This will be the case if you start up a new IB account without
# purchasing a subscription. In that case, you'll see a "Market Data not
# subscribed..." message, which means everything is operating normally. If you
# purchase a data subscription, this message will not appear.

# Create a connection to IB
create_new_connections()

#### Snapshot Example: Exxon stock
################################################################################
# Fetch a delayed market data snapshot for Exxon (XOM)
req_mkt_data(
  contract = c(
    symbol   = "XOM",
    secType  = "STK", 
    currency = "USD", 
    exchange = "SMART"
  ),
  snapshot    = TRUE,
  data_name   = "Exxon_delayed",
  mktDataType = "DELAYED"
) 

# Note that a "mkt_data" subscription now appears:
subscriptions$mkt_data

# For the sake of this example, wait 3 seconds or so to be sure that the data
# has time to arrive.
Sys.sleep(3)

# Read the data off the sock and update "mkt_data"
read_sock_drawer()

# Now you have a market data snapshot in your mkt_data slate! You can access it
# with the "$" operator, like this:
mkt_data$Exxon_delayed$TICK_PRICE
mkt_data$Exxon_delayed$TICK_SIZE
mkt_data$Exxon_delayed$`Delayed Last Timestamp`
mkt_data$Exxon_delayed$TICK_REQ_PARAMS
# ...etc

# Note that the mkt_data subscription has been destroyed. This is because you 
# set snapshot to TRUE -- when read_sock_drawer() finds a completed snapshot,
# it automatically updates the subscription.
subscriptions$mkt_data 


#### Subscription Example: Five stocks
################################################################################
# Snapshots are great if you just want to quickly fetch market data for a
# contract and move on. Often, however, you'll want to stay up-to-date on market
# data by creating a persistent subscription, causing the data in the mkt_data
# slate to update every time read_sock_drawer() is called.

# To do this, first create a sock for yourself (if you didn't already):
create_new_connections()

# Now, set up market data subscriptions to Tesla, Apple, Facebook, 3M,
# Interactive Brokers and whatever else you want to follow. Below, the walk()
# function from package "purrr" is used to call req_mkt_data on each stock.
c("TSLA", "AAPL", "FB", "MMM", "IBKR") %>%
  purrr::walk(
    function(stock_symbol){
      req_mkt_data(
        contract = c(
          symbol   = stock_symbol,
          secType  = "STK",
          currency = "USD",
          exchange = "SMART"
        ),
        mktDataType = "DELAYED",
        snapshot    = FALSE,
        channel     = "async"
      ) 
    }
  )

# Note that the mkt_data subscriptions you just created appear in the
# subscriptions variable:
subscriptions$mkt_data

# Wait a bit for the data to come through for example's sake...
Sys.sleep(3)

# Read the sock drawer as many times as you want
read_sock_drawer()

# Access your data:
mkt_data$`1_TSLA`$TICK_PRICE
mkt_data$`4_MMM`$TICK_PRICE
# ...etc

# Because these subscriptions aren't for snapshots, they'll stay active until
# cancelled. When you're ready, cancel any/all of your subscriptions:
cancel_mkt_data()

# Subscriptions are gone! 
subscriptions$mkt_data

JakeVestal/InteractiveTradeR documentation built on June 5, 2024, 2:21 p.m.