Sha256: 0e6b926f86ea181bf008522fa7c2160e89c30a1d03dcf75490bb9c61ef555e10

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

#!/usr/bin/env ruby
#
# This script connects to IB API and subscribes to market data for specific symbols

require 'pathname'
LIB_DIR = (Pathname.new(__FILE__).dirname + '../lib/').realpath.to_s
$LOAD_PATH.unshift LIB_DIR unless $LOAD_PATH.include?(LIB_DIR)

require 'rubygems'
require 'bundler/setup'
require 'ib-ruby'

# Definition of what we want market data for.  We have to keep track of what ticker id
# corresponds to what symbol ourselves, because the ticks don't include any other
# identifying information. The choice of ticker ids is, as far as I can tell, arbitrary.
@market = {123 => IB::Symbols::Forex[:gbpusd],
           456 => IB::Symbols::Forex[:eurusd],
           789 => IB::Symbols::Forex[:usdcad]}

# First, connect to IB TWS.
ib = IB::Connection.new

## Subscribe to TWS alerts/errors
ib.subscribe(:Alert) { |msg| puts msg.to_human }

# Subscribe to TickerPrice and TickerSize events.  The code passed in the block will
# be executed when a message of that type is received, with the received message as its
# argument. In this case, we just print out the tick.
#
# Note that we have to look the ticker id of each incoming message
# up in local memory to figure out what it's for.
#
# (N.B. The description field is not from IB TWS. It is defined
#  locally in forex.rb, and is just arbitrary text.)
ib.subscribe(:TickPrice, :TickSize) do |msg|
  puts @market[msg.data[:id]].description + ": " + msg.to_human
end

# Now we actually request market data for the symbols we're interested in.
@market.each_pair do |id, contract|
  ib.send_message :RequestMarketData, :id => id, :contract => contract
end

puts "\nSubscribed to market data"
puts "\n******** Press <Enter> to cancel... *********\n\n"
gets
puts "Cancelling market data subscription.."

@market.each_pair { |id, _| ib.send_message :CancelMarketData, :id => id }

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ib-ruby-0.5.0 bin/market_data