Module: IB::Messages::Outgoing

Extended by:
IB::Messages
Defined in:
lib/ib/messages/outgoing.rb,
lib/ib/messages/outgoing/place_order.rb,
lib/ib/messages/outgoing/bar_requests.rb,
lib/ib/messages/outgoing/abstract_message.rb,
lib/ib/messages/outgoing/account_requests.rb,
lib/ib/messages/outgoing/request_tick_data.rb,
lib/ib/messages/outgoing/request_marketdata.rb

Overview

Outgoing IB messages (sent to TWS/Gateway)

Defined Under Namespace

Classes: AbstractMessage, BarRequestMessage, PlaceOrder, RequestHistoricalData, RequestRealTimeBars

Constant Summary collapse

RequestOpenOrders =

Request the open orders that were placed from THIS client. Each open order will be fed back through the OpenOrder and OrderStatus messages ONCE. NB: Client with a client_id of 0 will also receive the TWS-owned open orders. These orders will be associated with the client and a new orderId will be generated. This association will persist over multiple API and TWS sessions.

def_message 5
RequestAllOpenOrders =

Request the open orders placed from all clients and also from TWS. Each open order will be fed back through the OpenOrder and OrderStatus messages ONCE. Note this does not re-bind those Orders to requesting Client! Use RequestAutoOpenOrders to request such re-binding.

def_message 16
RequestAutoOpenOrders =

Request that newly created TWS orders be implicitly associated with this client. When a new TWS order is created, the order will be associated with this client and automatically fed back through the OpenOrder and OrderStatus messages. It is a ‘continuous’ request such that it gets turned ‘on’ when called with a TRUE auto_bind parameter. When it’s called with FALSE auto_bind, new TWS orders will not bind to this client going forward. Note that TWS orders can only be bound to clients with a client_id of 0. TODO: how to properly test this? data = { :auto_bind => boolean }

def_message 15, :auto_bind
RequestScannerParameters =

Requests an XML document that describes the valid parameters that a scanner subscription can have (for outgoing RequestScannerSubscription message).

def_message 24
RequestNewsArticle =
def_message 84,
:request_id , # autogenerated
:provider_code,
:article_id,
:options
RequestNewsProviders =

no further parameters

def_message 85
RequestHistoricalNews =
def_message 86,
:request_id , # autogenerated
:con_id,
:provider_code,
:start,      # date
:total_results,
:options
CancelNewsBulletins =
def_message 13
RequestCurrentTime =
def_message 49
RequestGlobalCancel =
def_message 58
CancelMarketData =

Data format is: @data = { :id => ticker_id}

def_message [2, 2]
CancelMarketDepth =
def_message 11
CancelScannerSubscription =
def_message 23
CancelHistoricalData =
def_message 25
CancelRealTimeBars =
def_message 51
CancelFundamentalData =

Data format is: @data = { :id => request_id }

def_message 53
CancelCalculateImpliedVolatility =
CancelImpliedVolatility = def_message 56
CancelCalculateOptionPrice =
CancelOptionPrice = def_message 57
CancelOrder =

Data format is: @data ={ :id => local_id of order to cancel }

def_message 4
RequestIds =

Request the next valid ID that can be used when placing an order. Responds with NextValidId message, and the id returned is that next valid Id for orders. That ID will reflect any autobinding that has occurred (which generates new IDs and increments the next valid ID therein).

def_message 8, [:number, 1]
RequestNewsBulletins =

data = { :all_messages => boolean }

def_message 12, :all_messages
SetServerLoglevel =

data = { :log_level => int }

def_message 14, :log_level
RequestFA =

data = { :fa_data_type => int } 1 -> groups, 2 -> Profiles, 3 -> Account Aliases

def_message 18, :fa_data_type
ReplaceFA =

data = { :fa_data_type => int, :xml => String }

def_message 19, :fa_data_type, :xml
RequestContractDetails =

data => { :id => request_id (int), :contract => Contract }

Special case for options: “wildcards” in the Contract fields retrieve Option chains

strike = 0 means all strikes
right = "" meanns both call and put
expiry = "" means all expiries
expiry = "2013" means all expiries in 2013
expiry = "201311" means all expiries in Nov 2013

You’ll get several ContractData (10) messages back if there is more than one match. When all the matches are delivered you’ll get ContractDataEnd (52) message.

RequestContractData =
          def_message([9, 8], :request_id , # autogenerated
[:contract, :serialize_long, [:sec_id_type]])
RequestSecurityDefinitionOptionParameters =
ReqSecDefOptParams  = RequestOptionChainDefinition = def_message [78,0],
:request_id,   # autogenerated if not specified
:symbol,				# underlyingSymbol
[:exchange, ""],			# futOptExchange
:sec_type,			# underlyingSecType
:con_id
RequestMarketDepthExchanges =

returns MarketDepthExchanges-Message

def_message 82
RequestMarketDepth =

actual Version supported is: 137 changes: MIN_SERVER_VER_SMART_DEPTH: 146 –> insert ‘is_smarth_depth’ after ‘num_rows’

then: 'is_smart_depth' (bool) has to be specified in  CancelMarketDepth, too
def_message([10, 5],
						:request_id,   # autogenerated if not specified
                            [:contract, :serialize_supershort ],
                            :num_rows, 
"")
RequestExecutions =

When this message is sent, TWS responds with ExecutionData messages, each containing the execution report that meets the specified criteria. @data={:id => int: :request_id,

:client_id => int: Filter the results based on the clientId.
:account => Filter the results based on based on account code.
              Note: this is only relevant for Financial Advisor accts.
:sec_type =>  Filter the results based on the order security type.
:time =>      Filter the results based on execution reports received
              after the specified time - format "yyyymmdd-hh:mm:ss"
:symbol   =>  Filter the results based on the order symbol.
:exchange =>  Filter the results based on the order exchange
:side =>  Filter the results based on the order action: BUY/SELL/SSHORT
def_message([7, 3],
																			 :request_id,  # autogenerated if not specified
:client_id,
:account,
:time, # Format "yyyymmdd-hh:mm:ss"
:symbol,
:sec_type,
:exchange,
:side)
ExerciseOptions =

data = { :id => ticker_id (int),

:contract => IB::Contract,
:exercise_action => int, 1 = exercise, 2 = lapse
:exercise_quantity => int, The number of contracts to be exercised
:account => string,
:override => int: Specifies whether your setting will override the
             system's natural action. For example, if your action
             is "exercise" and the option is not in-the-money, by
             natural action the option would not exercise. If you
             have override set to "yes" the natural action would be
             overridden and the out-of-the money option would be
             exercised. Values are:
                    - 0 = do not override
                    - 1 = override
def_message([ 21, 2 ],  
																	#		:request_id, # id -> required  # todo : TEST
[:contract, :serialize_short],
:exercise_action,
:exercise_quantity,
:account,
:override)
RequestMarketDataType =

3 (:delayed) for delayed streaming , 4 (:frozen_delayed) for frozen delayed

def_message 59, [:market_data_type,
lambda { |type| MARKET_DATA_TYPES.invert[type] || type }, []]
RequestFundamentalData =

ReportsFinSummary Financial summary ReportsOwnership Company’s ownership (Can be large in size) ReportSnapshot Company’s financial overview ReportsFinStatements Financial Statements RESC Analyst Estimates CalendarReport Company’s calendar

def_message([52,2],
          :request_id, # autogenerated if not specified
 [:contract, :serialize, :primary_exchange],
           :report_type,
""  )
RequestHeadTimeStamp =

:what_to_show: type of data for head timestamp - “BID”, “ASK”, “TRADES”, etc

:use_rth     : use regular trading hours only, 1 for yes or 0 for no 
format_data	: set to 2 to obtain it like system time format in second ---> don't change
def_message( [87,0], 	:request_id, # autogenerated
[:contract, :serialize_short, [:primary_exchange,:include_expired] ],
[:use_rth, 1 ],
[:what_to_show, 'Trades' ],
[:format_date, 2 ]  )
CancelHeadTimeStamp =
def_message [90,0 ]
RequestHistogramData =
def_message( [88, 0],  :request_id, #  autogenerated
[:contract, :serialize_short, [:primary_exchange,:include_expired] ],
[:use_rth, 1 ],
[:time_period ]   )
CancelHistogramData =
def_message [89,0 ]
RequestCalculateImpliedVolatility =

Attention: If not reasonable data are used, simply nothing is returned. There is no error message either.

CalculateImpliedVolatility =
          RequestImpliedVolatility =
def_message([ 54,3 ],:request_id,  # autogenerated
        [:contract, :serialize_short],
            :option_price,
            :under_price,
													[:implied_volatility_options_count, 0],
[:implied_volatility_options_conditions, ''])
RequestCalculateOptionPrice =

data = { :request_id => int, :contract => Contract,

:volatility => double, :under_price => double }
CalculateOptionPrice = RequestOptionPrice =
          def_message([ 55, 3], :request_id, #autogenerated if not specified
        [:contract, :serialize_short],
        :volatility,
        :under_price,
													[:implied_volatility_options_count, 0],
[:implied_volatility_options_conditions, ''])
RequestScannerSubscription =

Start receiving market scanner results through the ScannerData messages.


To learn all valid parameter values that a scanner subscription can have, first subscribe to ScannerParameters and send RequestScannerParameters message. Available scanner parameters values will be listed in received XML document.

def_message([22, 3], :request_id , 
[:number_of_rows, -1], # was: EOL,
:instrument,
:location_code,
:scan_code,
:above_price,
:below_price,
:above_volume,
:market_cap_above,
:market_cap_below,
:moody_rating_above,
:moody_rating_below,
:sp_rating_above,
:sp_rating_below,
:maturity_date_above,
:maturity_date_below,
:coupon_rate_above,
:coupon_rate_below,
:exclude_convertible,
:average_option_volume_above, # ?
:scanner_setting_pairs,
:stock_type_filter)
Classes =

Container for specific message classes, keyed by their message_ids

{}
RequestManagedAccounts =
def_message 17
RequestAccountUpdates =
RequestAccountData = def_message([6, 2], 
[:subscribe, true],
:account_code)
RequestAccountSummary =

Call this method to request and keep up to date the data that appears

on the TWS Account Window Summary tab. The data is returned by
accountSummary().

Note:   This request is designed for an FA managed account but can be
used for any multi-account structure.

reqId:int - The ID of the data request. Ensures that responses are matched
    to requests If several requests are in process.
groupName:str - Set to All to returnrn account summary data for all
    accounts, or set to a specific Advisor Account Group name that has
    already been created in TWS Global Configuration.
tags:str - A comma-separated list of account tags.  Available tags are:
    accountountType
    NetLiquidation,
    TotalCashValue - Total cash including futures pnl
    SettledCash - For cash accounts, this is the same as
    TotalCashValue
    AccruedCash - Net accrued interest
    BuyingPower - The maximum amount of marginable US stocks the
        account can buy
    EquityWithLoanValue - Cash + stocks + bonds + mutual funds
    PreviousDayEquityWithLoanValue,
    GrossPositionValue - The sum of the absolute value of all stock
        and equity option positions
    RegTEquity,
    RegTMargin,
    SMA - Special Memorandum Account
    InitMarginReq,
    MaintMarginReq,
    AvailableFunds,
    ExcessLiquidity,
    Cushion - Excess liquidity as a percentage of net liquidation value
    FullInitMarginReq,
    FullMaintMarginReq,
    FullAvailableFunds,
    FullExcessLiquidity,
    LookAheadNextChange - Time when look-ahead values take effect
    LookAheadInitMarginReq,
    LookAheadMaintMarginReq,
    LookAheadAvailableFunds,
    LookAheadExcessLiquidity,
    HighestSeverity - A measure of how close the account is to liquidation
    DayTradesRemaining - The Number of Open/Close trades a user
        could put on before Pattern Day Trading is detected. A value of "-1"
        means that the user can put on unlimited day trades.
    Leverage - GrossPositionValue / NetLiquidation
    $LEDGER - Single flag to relay all cash balance tags*, only in base
        currency.
    $LEDGER:CURRENCY - Single flag to relay all cash balance tags*, only in
        the specified currency.
    $LEDGER:ALL - Single flag to relay all cash balance tags* in all
    currencies.
def_message( 62,
					  :request_id, # autogenerated if not specified
[:group, 'All'],
:tags )
CancelAccountSummary =

:request_id required

def_message 63
RequestPositions =

Note: The reqPositions function is not available in Introducing Broker or Financial Advisor master accounts that have very large numbers of subaccounts (> 50) to optimize the performance of TWS/IB Gateway v973+. Instead the function reqPositionsMulti can be used to subscribe to updates from individual subaccounts. Also not available with IBroker accounts configured for on-demand account lookup.

def_message 61
CancelPositions =
def_message 64
RequestPositionsMulti =

The function reqPositionsMulti can be used with any account structure to subscribe to positions updates for multiple accounts and/or models. The account and model parameters are optional if there are not multiple accounts or models available.

def_message( 74,  :request_id, # autogenerated
[ :account, 'ALL' ],
[:model_code, nil ] )
CancelPositionsMulti =

required

def_message( 75, :request_id )
RequestAccountUpdatesMulti =

autogenerated

def_message( 76, :request_id, # autogenerated
[ :account, 'ALL'],													# account or account-group	
[:model_code, nil],
[:leger_and_nlv, nil ])
CancelAccountUpdatesMulti =

required

def_message 77, :request_id
RequestTickByTickData =
def_message [0, 97], :request_id,			# autogenerated if not specified
           [:contract, :serialize_short, :primary_exchange],  # include primary exchange in request
:tick_type,  # a string  supported: "Last", "AllLast", "BidAsk" or "MidPoint".
# Server_version >= 140
 :number_of_ticks,  # int
:ignore_size
CancelTickByTickData =

bool

def_message [0, 98], :request_id
RequestMarketData =

459 - RTCLOSE

  460 - Bond Factor Multiplier
  499 - Fee and Rebate Ratge
  506 - midptiv

  511(hvolrt10 (per-underlying)),
  512(hvolrt30 (per-underlying)),
  513(hvolrt50 (per-underlying)),
  514(hvolrt75 (per-underlying)),
  515(hvolrt100 (per-underlying)),
  516(hvolrt150 (per-underlying)),
  517(hvolrt200 (per-underlying)),
  521(fzmidptiv),
  545(vsiv),
  576(EtfNavBidAsk(navbidask)),
  577(EtfNavLast(navlast)),
  578(EtfNavClose(navclose)),
  584(Average Opening Vol.),
  585(Average Closing Vol.),
  587(Pl Price Delayed),
  588(Futures Open Interest),
  595(Short-Term Volume X Mins),
  608(EMA N),
  614(EtfNavMisc(hight/low)),
  619(Creditman Slow Mark Price),
  623(EtfFrozenNavLast(fznavlast)	      ## updated 2018/1/21

:snapshot => bool: Check to return a single snapshot of market data and
             have the market data subscription canceled. Do not enter any
             :tick_list values if you use snapshot. 

:regulatory_snapshot => bool - With the US Value Snapshot Bundle for stocks,
             regulatory snapshots are available for 0.01 USD each. (applies on demo accounts as well)
:mktDataOptions => (TagValueList)  For internal use only.
              Use default value XYZ.
def_message [1, 11], :request_id,
              [:contract, :serialize_short, :primary_exchange],  # include primary exchange in request
              [:contract, :serialize_legs, []],
              [:contract, :serialize_under_comp, []],
              [:tick_list, ->(tick_list){ tick_list.is_a?(Array) ? tick_list.join(',') : (tick_list || '')}, []],
              [:snapshot, false],
[:regulatory_snapshot, false],
[:mkt_data_options, ""]

Constants included from IB::Messages

CLIENT_VERSION, SERVER_VERSION

Method Summary

Methods included from IB::Messages

def_message