Class: MyTradeWizard::InteractiveBrokers

Inherits:
Object
  • Object
show all
Defined in:
lib/mytradewizard/interactive_brokers.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#accountsObject (readonly)

Returns the value of attribute accounts.



6
7
8
# File 'lib/mytradewizard/interactive_brokers.rb', line 6

def accounts
  @accounts
end

Instance Method Details

#buying_power(account) ⇒ Object



101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/mytradewizard/interactive_brokers.rb', line 101

def buying_power()
  buying_power = nil
  @ib_ruby.subscribe(:Alert, :AccountValue, :PortfolioValue, :AccountUpdateTime, :AccountDownloadEnd) do |msg|
    if msg.message_type == :AccountValue
      if msg.data[:key] == "BuyingPower"
        buying_power = msg.data[:value]
      end
    end
  end
  @ib_ruby.send_message :RequestAccountData, :subscribe => true, :account_code => 
  @ib_ruby.wait_for :AccountDownloadEnd
  @ib_ruby.send_message :RequestAccountData, :subscribe => false, :account_code => 
  @ib_ruby.received[:AccountDownloadEnd].clear
  buying_power.to_f
end

#connect(timeout = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/mytradewizard/interactive_brokers.rb', line 8

def connect(timeout = nil)
  puts "Connecting to IB..."
  start_time = Time.now
  exception = nil
  while (timeout.nil? || Time.now - start_time <= timeout)
    begin
      @ib_ruby = IB::Connection.new :host => MyTradeWizard::Configuration::InteractiveBrokers::HOST, :port => MyTradeWizard::Configuration::InteractiveBrokers::PORT
      subscribe_to_alerts
      sleep 0.1
      fetch_accounts
      return @ib_ruby
    rescue Exception => exception
      puts exception
      sleep 10
    end
  end
  raise exception
end

#daily_bars(contract, days, confirm = true) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/mytradewizard/interactive_brokers.rb', line 27

def daily_bars(contract, days, confirm = true)
  puts "Fetching daily bars..."
  bars = nil   
  @ib_ruby.subscribe(IB::Messages::Incoming::HistoricalData) { |msg| bars = msg.results }
  @ib_ruby.send_message IB::Messages::Outgoing::RequestHistoricalData.new(
                            :request_id => 123,
                            :contract => contract,
                            :end_date_time => Time.now.utc.to_ib,
                            :duration => "#{days} D",
                            :bar_size => '1 day',
                            :what_to_show => :trades,
                            :use_rth => 1,
                            :format_date => 1)
  while bars.nil?
    sleep 1
  end
  if confirm && bars.size < days
    raise "Invalid Data!  (#{bars.size}/#{days} valid bars.)"
  else
    bars.reverse!
    puts bars
    return bars
  end
end

#front_month(symbol) ⇒ Object



198
199
200
201
202
203
204
205
206
207
# File 'lib/mytradewizard/interactive_brokers.rb', line 198

def front_month(symbol)
  expiry = MyTradeWizard::CME.first_month(symbol)
  if invalid contract(symbol, expiry)
    expiry = MyTradeWizard::CME.second_month(symbol)
    if invalid contract(symbol, expiry)
      raise 'ErrorDeterminingFrontMonth'
    end
  end
  contract(symbol, expiry)
end

#hourly_bars(contract, hourly_range, confirm = true) ⇒ Object



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/mytradewizard/interactive_brokers.rb', line 52

def hourly_bars(contract, hourly_range, confirm = true)
  range_size = hourly_range.last - hourly_range.first
  puts "Fetching hourly bars..."
  bars = nil
  @ib_ruby.subscribe(IB::Messages::Incoming::HistoricalData) { |msg| bars = msg.results }
  @ib_ruby.send_message IB::Messages::Outgoing::RequestHistoricalData.new(
                        :request_id => 123,
                        :contract => contract,
                        :end_date_time => Time.now.utc.to_ib,
                        :duration => "#{60*60*range_size} S",
                        :bar_size => '1 hour',
                        :what_to_show => :trades,
                        :use_rth => 0,
                        :format_date => 1)
  while bars.nil?
    sleep 1
  end
  if confirm
    bars.keep_if { |bar| Time.parse(bar.time).wday == Time.now.utc.wday && hourly_range.include?(Time.parse(bar.time).hour) }
    if bars.size == range_size
      puts bars
      return bars
    else
      raise "Invalid Data!  (#{bars.size}/#{range_size} valid bars.)"
    end
  else
    puts bars
    return bars
  end   
end

#place_market_order(account, action, quantity, contract) ⇒ Object



117
118
119
120
121
122
123
124
125
126
# File 'lib/mytradewizard/interactive_brokers.rb', line 117

def place_market_order(, action, quantity, contract)
  order = IB::Order.new :total_quantity => quantity,
                        :action => action.to_s,
                        :order_type => 'MKT',
                        :tif => 'OPG',
                        :account => 
  @ib_ruby.wait_for :NextValidId
  @ib_ruby.place_order order, contract
  #puts "#{action} #{quantity} #{contract.symbol}"
end

#place_market_order_between(account, action, quantity, contract, good_after, good_till) ⇒ Object



128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/mytradewizard/interactive_brokers.rb', line 128

def place_market_order_between(, action, quantity, contract, good_after, good_till)
  order = IB::Order.new :total_quantity => quantity,
                        :action => action.to_s,
                        :order_type => 'MKT',
                        :good_after_time => good_after,
                        :good_till_date => good_till,
                        :tif => 'GTD',
                        :account => 
  @ib_ruby.wait_for :NextValidId
  @ib_ruby.place_order order, contract
  puts "#{action} #{quantity} #{contract.symbol} @ #{good_after}"
end

#place_market_orders(account, action, quantity, contract, open_time, close_time) ⇒ Object



141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
# File 'lib/mytradewizard/interactive_brokers.rb', line 141

def place_market_orders(, action, quantity, contract, open_time, close_time)
  good_after_open = Time.parse(open_time).strftime("%Y%m%d %H:%M:%S %Z")
  good_till_open = (Time.parse(open_time) + 60).strftime("%Y%m%d %H:%M:%S %Z")
  good_after_close = Time.parse(close_time).strftime("%Y%m%d %H:%M:%S %Z")
  good_till_close = (Time.parse(close_time) + 60).strftime("%Y%m%d %H:%M:%S %Z")
  if quantity.is_a? Fixnum
    place_market_order_between(, action, quantity, contract, good_after_open, good_till_open)
    @ib_ruby.subscribe(:OrderStatus, :OpenOrderEnd) do |msg|
      if msg.message_type == :OrderStatus
        if msg.status == 'Submitted'
          place_market_order_between(, action.reverse, quantity, contract, good_after_close, good_till_close)
        elsif msg.status == 'Cancelled'
          puts "CANCELLED: #{action} #{quantity} #{contract.symbol} @ #{open_time}"
        end
      end
    end
    @ib_ruby.send_message :RequestAllOpenOrders
    @ib_ruby.wait_for :OrderStatus
  elsif quantity.is_a? Range
    quantity.each do |q|
      if q == quantity.first
        place_market_order_between(, action, q, contract, good_after_open, good_till_open)
        @ib_ruby.subscribe(:OrderStatus, :OpenOrderEnd) do |msg|
          if msg.message_type == :OrderStatus
            if msg.status == 'Submitted'
              place_market_order_between(, action.reverse, q, contract, good_after_close, good_till_close)
            elsif msg.status == 'Cancelled'
              puts "CANCELLED: #{action} #{q} #{contract.symbol} @ #{open_time}"
              break
            end
          end
        end
        @ib_ruby.send_message :RequestAllOpenOrders, :subscribe => true, :account_code => 
        @ib_ruby.wait_for :OrderStatus
        @ib_ruby.send_message :RequestAllOpenOrders, :subscribe => false, :account_code => 
        @ib_ruby.received[:OrderStatus].clear
      else
        place_market_order_between(, action, 1, contract, good_after_open, good_till_open)
        @ib_ruby.subscribe(:OrderStatus, :OpenOrderEnd) do |msg|
          if msg.message_type == :OrderStatus
            if msg.status == 'Submitted'
              place_market_order_between(, action.reverse, 1, contract, good_after_close, good_till_close)
            elsif msg.status == 'Cancelled'
              puts "CANCELLED: #{action} 1 #{contract.symbol} @ #{open_time}"
              break
            end
          end
        end
        @ib_ruby.send_message :RequestAllOpenOrders, :subscribe => true, :account_code => 
        @ib_ruby.wait_for :OrderStatus
        @ib_ruby.send_message :RequestAllOpenOrders, :subscribe => false, :account_code => 
        @ib_ruby.received[:OrderStatus].clear
      end
    end
  end
end

#positions(account) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/mytradewizard/interactive_brokers.rb', line 83

def positions()
  p = Array.new
  @ib_ruby.subscribe(:Alert, :AccountValue, :PortfolioValue, :AccountUpdateTime, :AccountDownloadEnd) do |msg|
    if msg.message_type == :PortfolioValue
      if msg.contract.sec_type == :stock
        stock = MyTradeWizard::Stock.new(msg.contract.symbol)
        size = msg.position
        p << MyTradeWizard::Position.new(stock, size)
      end
    end
  end
  @ib_ruby.send_message :RequestAccountData, :subscribe => true, :account_code => 
  @ib_ruby.wait_for :AccountDownloadEnd
  @ib_ruby.send_message :RequestAccountData, :subscribe => false, :account_code => 
  @ib_ruby.received[:AccountDownloadEnd].clear
  p
end