To use the features described, include the ib-extensions Gem in the Gemfile and use
 
require 'ib-api' 
require 'ib/symbols' 
require 'ib/order-prototypes' 
require 'ib/gateway' 
in your scripts.

The IB::Gateway aims to provide an intuitive interface for order-placement and -management

Step 1: Create an order-object

> G =  IB::Gateway.new                      # initialize with default parameter 
                                            # omit this step in the interactive gateway-console
> the_contract =  IB::Symbols::Stocks.msft  # Microsoft
> the_order = Limit.order size: 100, price: the_contract.market_price - 1 ,
> the_order.to_human
 => "<Order: LMT GTC buy 100  @ 201.33 New #/ from >" 

notice: The fetched (and modified) market price is included. The account to deal with is missing.

Step 2: Select an account and get the margin requirements

> the_account  =  G.clients.first

> z= the_account.preview order: the_order, contract: the_contract
  => {:init_margin=>0.1344327e5, :maint_margin=>0.1168288e5, :equity_with_loan=>0.118936284e7, :commission=>nil, :commission_currency=>"USD", :warning=>""} 

> z[:init_margin].to_f                        => 13443.27 
> # compare to available net liquidity
> the_account.account_data_scan( /^NetLiquidation$/).value.first.to_f - 
      the_account.account_data_scan(/InitMarginReq$/).value.first.to_f
 => 1180035.98

see also Preview Orders

IB::Account.preview transmits a What-if message. To determine if its possible to place the order, just subtract the margin impact from NetLiquidation.

Step 3: Place and modify the order

After an order is previewed or placed, the contract is associated and does not have to be specified anymore.

> the_account.place order: the_order            => 19  #  local_id, identifies the order
> the_order.to_human
 => "<Order: LMT GTC buy 100  @ 201.33 New #19/ from 2000/DU167348>" 

> the_account.orders.to_human
 => ["<Order: LMT GTC buy 100.0  @ 201.33 PreSubmitted #18/1729171645 from 0/DU167348>",    # preview
     "<Order: LMT GTC buy 100.0  @ 201.33 PreSubmitted #19/1729171646 from 2000/DU167348>"] # placed

> the_order.limit_price = 198                   # set a new price
> the_account.modify order: the_order           => 19 
> the_account.orders.to_human
 => ["<Order: LMT GTC buy 100.0  @ 201.33 PreSubmitted #18/1729171645 from 0/DU167348>", 
     "<Order: LMT GTC buy 100.0  @ 198.0 PreSubmitted #19/1729171646 from 2000/DU167348>"]  # modified

Step 4: Cancel the order

> the_account.cancel  the_order
> the_account.orders.to_human
 => ["<Order: LMT GTC buy 100.0  @ 201.33 PreSubmitted #18/1729171645 from 0/DU167348>", 
     "<Order: LMT GTC buy 100.0  @ 198.0 Cancelled #19/1729171646 from 2000/DU167348>"]         # cancelled

Notice: The order-object is updated in the process. It’s OK to use the same order-object for each step. Then the history is kept in OrderState-Objects. But never use the same order object for different users.

Tags: