IB::Connection is part of ib-api. Include
 
require 'ib-api' 
in your scripts.

IB::Connection

ib-api provides IB::Connection.new to connect to the TWS/Gateway.

def initialize host: '127.0.0.1',
               port: '4002', # IB Gateway connection  4001:  production
                             # TWS                    7496:  production
               connect: true,         # Connect at initialization
               received:  true,       # Keep all received messages in a @received Hash
               logger: default_logger,
               client_id:  rand( 1001 .. 9999 ) 

If called without arguments, it connects through port 4002 to a locally running gateway, prints messages to the screen and saves the communication in a received-hash.

public interface

connect connected? disconnect
subscribe unsubscribe  
send_message    
received received? clear_received
wait_for    
place_order modify_order cancel_order

Its usage is demonstrated by this small demonstration

 require 'bundler/setup'
 require 'ib-api'
 
 ib = IB::Connection.new( port: 7497 ) do | gw |
      gw.subscribe(:Alert, :AccountValue) { |msg| puts msg.to_human }
      gw.subscribe(:OpenOrder) { |msg| puts "Placed: #{msg.order}!" }
      gw.subscribe(:ExecutionData) { |msg| puts "Filled: #{msg.execution}!" }
    end

 ib.send_message :RequestAccountData, account_code: 'U123456'
 ib.wait_for :AccountDownloadEnd

 contract = IB::Stock.new symbol: 'WFC'
 buy_order = IB::Limit.order size: 100, price: 21.00, action: :buy,
                                tif: :good_till_cancelled, account_code: 'U123456'

 ib.place_order buy_order, contract
 ib.wait_for :ExecutionData

The main purpose of IB::Connection is connect to the tws/gateway, to submit IB::Messages to the TWS-Api and to receive the response. Thus the centerpiece is its send_message method.

> c =  IB::Connection.current
> c.send_message {message symbol }, [ optional arguments ]

Visit this page for an overview of available messages and their arguments.

Tags: