my-ib-api 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. checksums.yaml +7 -0
  2. data/lib/ib-api.rb +10 -0
  3. data/lib/ib/base.rb +99 -0
  4. data/lib/ib/base_properties.rb +154 -0
  5. data/lib/ib/connection.rb +327 -0
  6. data/lib/ib/constants.rb +334 -0
  7. data/lib/ib/db.rb +29 -0
  8. data/lib/ib/engine.rb +35 -0
  9. data/lib/ib/errors.rb +40 -0
  10. data/lib/ib/extensions.rb +72 -0
  11. data/lib/ib/flex.rb +106 -0
  12. data/lib/ib/logger.rb +25 -0
  13. data/lib/ib/messages.rb +88 -0
  14. data/lib/ib/messages/abstract_message.rb +89 -0
  15. data/lib/ib/messages/incoming.rb +134 -0
  16. data/lib/ib/messages/incoming/abstract_message.rb +99 -0
  17. data/lib/ib/messages/incoming/alert.rb +34 -0
  18. data/lib/ib/messages/incoming/contract_data.rb +102 -0
  19. data/lib/ib/messages/incoming/delta_neutral_validation.rb +23 -0
  20. data/lib/ib/messages/incoming/execution_data.rb +54 -0
  21. data/lib/ib/messages/incoming/historical_data.rb +55 -0
  22. data/lib/ib/messages/incoming/market_depths.rb +44 -0
  23. data/lib/ib/messages/incoming/next_valid_id.rb +18 -0
  24. data/lib/ib/messages/incoming/open_order.rb +232 -0
  25. data/lib/ib/messages/incoming/order_status.rb +81 -0
  26. data/lib/ib/messages/incoming/portfolio_value.rb +39 -0
  27. data/lib/ib/messages/incoming/real_time_bar.rb +32 -0
  28. data/lib/ib/messages/incoming/scanner_data.rb +53 -0
  29. data/lib/ib/messages/incoming/ticks.rb +131 -0
  30. data/lib/ib/messages/outgoing.rb +331 -0
  31. data/lib/ib/messages/outgoing/abstract_message.rb +73 -0
  32. data/lib/ib/messages/outgoing/bar_requests.rb +189 -0
  33. data/lib/ib/messages/outgoing/place_order.rb +141 -0
  34. data/lib/ib/model.rb +6 -0
  35. data/lib/ib/models.rb +10 -0
  36. data/lib/ib/requires.rb +9 -0
  37. data/lib/ib/socket.rb +81 -0
  38. data/lib/ib/symbols.rb +35 -0
  39. data/lib/ib/symbols/bonds.rb +28 -0
  40. data/lib/ib/symbols/forex.rb +41 -0
  41. data/lib/ib/symbols/futures.rb +117 -0
  42. data/lib/ib/symbols/options.rb +39 -0
  43. data/lib/ib/symbols/stocks.rb +37 -0
  44. data/lib/ib/version.rb +6 -0
  45. data/lib/models/ib/bag.rb +51 -0
  46. data/lib/models/ib/bar.rb +45 -0
  47. data/lib/models/ib/combo_leg.rb +103 -0
  48. data/lib/models/ib/contract.rb +292 -0
  49. data/lib/models/ib/contract_detail.rb +89 -0
  50. data/lib/models/ib/execution.rb +65 -0
  51. data/lib/models/ib/option.rb +60 -0
  52. data/lib/models/ib/order.rb +391 -0
  53. data/lib/models/ib/order_state.rb +128 -0
  54. data/lib/models/ib/underlying.rb +34 -0
  55. metadata +96 -0
@@ -0,0 +1,391 @@
1
+ require 'models/ib/order_state'
2
+
3
+ module IB
4
+ class Order < IB::Model
5
+ include BaseProperties
6
+
7
+ # General Notes:
8
+ # 1. Placing Orders by con_id - When you place an order by con_id, you must
9
+ # provide the con_id AND the exchange. If you provide extra fields when placing
10
+ # an order by conid, the order may not work.
11
+
12
+ # 2. Order IDs - Each order you place must have a unique Order ID. Increment
13
+ # your own Order IDs to avoid conflicts between orders placed from your API application.
14
+
15
+ # Main order fields
16
+ prop :local_id, # int: Order id associated with client (volatile).
17
+ :client_id, # int: The id of the client that placed this order.
18
+ :perm_id, # int: TWS permanent id, remains the same over TWS sessions.
19
+ [:quantity, :total_quantity], # int: The order quantity.
20
+
21
+ :order_type, # String: Order type.
22
+ # Limit Risk: MTL / MKT PRT / QUOTE / STP / STP LMT / TRAIL / TRAIL LIMIT / TRAIL LIT / TRAIL MIT
23
+ # Speed of Execution: MKT / MIT / MOC / MOO / PEG MKT / REL
24
+ # Price Improvement: BOX TOP / LOC / LOO / LIT / PEG MID / VWAP
25
+ # Advanced Trading: OCA / VOL / SCALE
26
+ # Other (no abbreviation): Bracket, Auction, Discretionary, Sweep-to-Fill,
27
+ # Price Improvement Auction, Block, Hidden, Iceberg/Reserve, All-or-None, Fill-or-Kill
28
+ # See 'ib/constants.rb' ORDER_TYPES for a complete list of valid values.
29
+
30
+ :limit_price, # double: LIMIT price, used for limit, stop-limit and relative
31
+ # orders. In all other cases specify zero. For relative
32
+ # orders with no limit price, also specify zero.
33
+
34
+ :aux_price, # double: STOP price for stop-limit orders, and the OFFSET amount
35
+ # for relative orders. In all other cases, specify zero.
36
+
37
+ :oca_group, # String: Identifies a member of a one-cancels-all group.
38
+ :oca_type, # int: Tells how to handle remaining orders in an OCA group
39
+ # when one order or part of an order executes. Valid values:
40
+ # - 1 = Cancel all remaining orders with block
41
+ # - 2 = Remaining orders are reduced in size with block
42
+ # - 3 = Remaining orders are reduced in size with no block
43
+ # If you use a value "with block" your order has
44
+ # overfill protection. This means that only one order in
45
+ # the group will be routed at a time to remove the
46
+ # possibility of an overfill.
47
+ :parent_id, # int: The order ID of the parent (original) order, used
48
+ # for bracket (STP) and auto trailing stop (TRAIL) orders.
49
+ :display_size, # int: publicly disclosed order size for Iceberg orders.
50
+
51
+ :trigger_method, # Specifies how Simulated Stop, Stop-Limit and Trailing
52
+ # Stop orders are triggered. Valid values are:
53
+ # 0 - Default, "double bid/ask" for OTC/US options, "last" otherswise.
54
+ # 1 - "double bid/ask" method, stop orders are triggered based on
55
+ # two consecutive bid or ask prices.
56
+ # 2 - "last" method, stops are triggered based on the last price.
57
+ # 3 - double last method.
58
+ # 4 - bid/ask method. For a buy order, a single occurrence of the
59
+ # bid price must be at or above the trigger price. For a sell
60
+ # order, a single occurrence of the ask price must be at or
61
+ # below the trigger price.
62
+ # 7 - last or bid/ask method. For a buy order, a single bid price
63
+ # or the last price must be at or above the trigger price.
64
+ # For a sell order, a single ask price or the last price
65
+ # must be at or below the trigger price.
66
+ # 8 - mid-point method, where the midpoint must be at or above
67
+ # (for a buy) or at or below (for a sell) the trigger price,
68
+ # and the spread between the bid and ask must be less than
69
+ # 0.1% of the midpoint
70
+
71
+ :good_after_time, # Indicates that the trade should be submitted after the
72
+ # time and date set, format YYYYMMDD HH:MM:SS (seconds are optional).
73
+ :good_till_date, # Indicates that the trade should remain working until the
74
+ # time and date set, format YYYYMMDD HH:MM:SS (seconds are optional).
75
+ # You must set the :tif to GTD when using this string.
76
+ # Use an empty String if not applicable.
77
+
78
+ :rule_80a, # Individual = 'I', Agency = 'A', AgentOtherMember = 'W',
79
+ # IndividualPTIA = 'J', AgencyPTIA = 'U', AgentOtherMemberPTIA = 'M',
80
+ # IndividualPT = 'K', AgencyPT = 'Y', AgentOtherMemberPT = 'N'
81
+ :min_quantity, # int: Identifies a minimum quantity order type.
82
+ :percent_offset, # double: percent offset amount for relative (REL)orders only
83
+ :trail_stop_price, # double: for TRAILLIMIT orders only
84
+ # As of client v.56, we receive trailing_percent in openOrder
85
+ :trailing_percent,
86
+
87
+ # Financial advisors only - use an empty String if not applicable.
88
+ :fa_group, :fa_profile, :fa_method, :fa_percentage,
89
+
90
+ # Institutional orders only!
91
+ :origin, # 0=Customer, 1=Firm
92
+ :order_ref, # String: Order reference. Customer defined order ID tag.
93
+ :short_sale_slot, # 1 - you hold the shares,
94
+ # 2 - they will be delivered from elsewhere.
95
+ # Only for Action="SSHORT
96
+ :designated_location, # String: set when slot==2 only
97
+ :exempt_code, # int
98
+
99
+ # Clearing info
100
+ :account, # String: The account. For institutional customers only.
101
+ :settling_firm, # String: Institutional only
102
+ :clearing_account, # String: For IBExecution customers: Specifies the
103
+ # true beneficiary of the order. This value is required
104
+ # for FUT/FOP orders for reporting to the exchange.
105
+ :clearing_intent, # IBExecution customers: "", IB, Away, PTA (post trade allocation).
106
+
107
+ # SMART routing only
108
+ :discretionary_amount, # double: The amount off the limit price
109
+ # allowed for discretionary orders.
110
+ :nbbo_price_cap, # double: Maximum Smart order distance from the NBBO.
111
+
112
+ # BOX or VOL ORDERS ONLY
113
+ :auction_strategy, # For BOX exchange only. Valid values:
114
+ # 1=AUCTION_MATCH, 2=AUCTION_IMPROVEMENT, 3=AUCTION_TRANSPARENT
115
+ :starting_price, # double: Starting price. Valid on BOX orders only.
116
+ :stock_ref_price, # double: The stock reference price, used for VOL
117
+ # orders to compute the limit price sent to an exchange (whether or not
118
+ # Continuous Update is selected), and for price range monitoring.
119
+ :delta, # double: Stock delta. Valid on BOX orders only.
120
+
121
+ # Pegged to stock or VOL orders. For price improvement option orders
122
+ # on BOX and VOL orders with dynamic management:
123
+ :stock_range_lower, # double: The lower value for the acceptable
124
+ # underlying stock price range.
125
+ :stock_range_upper, # double The upper value for the acceptable
126
+ # underlying stock price range.
127
+
128
+ # VOLATILITY ORDERS ONLY:
129
+ # http://www.interactivebrokers.com/en/general/education/pdfnotes/PDF-VolTrader.php
130
+ :volatility, # double: What the price is, computed via TWSs Options
131
+ # Analytics. For VOL orders, the limit price sent to an
132
+ # exchange is not editable, as it is the output of a
133
+ # function. Volatility is expressed as a percentage.
134
+ :volatility_type, # int: How the volatility is calculated: 1=daily, 2=annual
135
+ :reference_price_type, # int: For dynamic management of volatility orders:
136
+ # - 1 = Average of National Best Bid or Ask,
137
+ # - 2 = National Best Bid when buying a call or selling a put;
138
+ # and National Best Ask when selling a call or buying a put.
139
+ :continuous_update, # int: Used for dynamic management of volatility orders.
140
+ # Determines whether TWS is supposed to update the order price as the underlying
141
+ # moves. If selected, the limit price sent to an exchange is modified by TWS
142
+ # if the computed price of the option changes enough to warrant doing so. This
143
+ # is helpful in keeping the limit price up to date as the underlying price changes.
144
+ :delta_neutral_order_type, # String: Enter an order type to instruct TWS
145
+ # to submit a delta neutral trade on full or partial execution of the
146
+ # VOL order. For no hedge delta order to be sent, specify NONE.
147
+ # Valid values - LMT, MKT, MTL, REL, MOC
148
+ :delta_neutral_aux_price, # double: Use this field to enter a value if
149
+ # the value in the deltaNeutralOrderType field is an order
150
+ # type that requires an Aux price, such as a REL order.
151
+
152
+ # As of client v.52, we also receive delta... params in openOrder
153
+ :delta_neutral_con_id,
154
+ :delta_neutral_settling_firm,
155
+ :delta_neutral_clearing_account,
156
+ :delta_neutral_clearing_intent,
157
+
158
+ # HEDGE ORDERS ONLY:
159
+ # As of client v.49/50, we can now add hedge orders using the API.
160
+ # Hedge orders are child orders that take additional fields. There are four
161
+ # types of hedging orders supported by the API: Delta, Beta, FX, Pair.
162
+ # All hedge orders must have a parent order submitted first. The hedge order
163
+ # should set its :parent_id. If the hedgeType is Beta, the beta sent in the
164
+ # hedgeParm can be zero, which means it is not used. Delta is only valid
165
+ # if the parent order is an option and the child order is a stock.
166
+
167
+ :hedge_type, # String: D = Delta, B = Beta, F = FX or P = Pair
168
+ :hedge_param, # String; value depends on the hedgeType; sent from the API
169
+ # only if hedge_type is NOT null. It is required for Pair hedge order,
170
+ # optional for Beta hedge orders, and ignored for Delta and FX hedge orders.
171
+
172
+ # COMBO ORDERS ONLY:
173
+ :basis_points, # double: EFP orders only
174
+ :basis_points_type, # double: EFP orders only
175
+
176
+ # ALGO ORDERS ONLY:
177
+ :algo_strategy, # String
178
+ :algo_params, # public Vector<TagValue> m_algoParams; ?!
179
+
180
+ # SCALE ORDERS ONLY:
181
+ :scale_init_level_size, # int: Size of the first (initial) order component.
182
+ :scale_subs_level_size, # int: Order size of the subsequent scale order
183
+ # components. Used in conjunction with scaleInitLevelSize().
184
+ :scale_price_increment, # double: Price increment between scale components.
185
+ # This field is required for Scale orders.
186
+
187
+ # As of client v.54, we can receive additional scale order fields:
188
+ :scale_price_adjust_value,
189
+ :scale_price_adjust_interval,
190
+ :scale_profit_offset,
191
+ :scale_init_position,
192
+ :scale_init_fill_qty,
193
+ :scale_auto_reset => :bool,
194
+ :scale_random_percent => :bool
195
+
196
+ # Properties with complex processing logics
197
+ prop :tif, # String: Time in Force (time to market): DAY/GAT/GTD/GTC/IOC
198
+ :what_if => :bool, # Only return pre-trade commissions and margin info, do not place
199
+ :not_held => :bool, # Not Held
200
+ :outside_rth => :bool, # Order may trigger or fill outside of regular hours. (WAS: ignore_rth)
201
+ :hidden => :bool, # Order will not be visible in market depth. ISLAND only.
202
+ :transmit => :bool, # If false, order will be created but not transmitted.
203
+ :block_order => :bool, # This is an ISE Block order.
204
+ :sweep_to_fill => :bool, # This is a Sweep-to-Fill order.
205
+ :override_percentage_constraints => :bool,
206
+ # TWS Presets page constraints ensure that your price and size order values
207
+ # are reasonable. Orders sent from the API are also validated against these
208
+ # safety constraints, unless this parameter is set to True.
209
+ :all_or_none => :bool, # AON
210
+ :etrade_only => :bool, # Trade with electronic quotes.
211
+ :firm_quote_only => :bool, # Trade with firm quotes.
212
+ :opt_out_smart_routing => :bool, # Australian exchange only, default false
213
+ :open_close => PROPS[:open_close], # Originally String: O=Open, C=Close ()
214
+ # for ComboLeg compatibility: SAME = 0; OPEN = 1; CLOSE = 2; UNKNOWN = 3;
215
+ [:side, :action] => PROPS[:side] # String: Action/side: BUY/SELL/SSHORT/SSHORTX
216
+
217
+ prop :placed_at,
218
+ :modified_at,
219
+ :leg_prices,
220
+ :algo_params,
221
+ :combo_params
222
+
223
+ alias order_combo_legs leg_prices
224
+ alias smart_combo_routing_params combo_params
225
+
226
+ serialize :leg_prices
227
+ serialize :algo_params, HashWithIndifferentAccess
228
+ serialize :combo_params, HashWithIndifferentAccess
229
+
230
+ # Order is always placed for a contract. Here, we explicitly set this link.
231
+ belongs_to :contract
232
+
233
+ # Order has a collection of Executions if it was filled
234
+ has_many :executions
235
+
236
+ # Order has a collection of OrderStates, last one is always current
237
+ has_many :order_states
238
+
239
+ def order_state
240
+ order_states.last
241
+ end
242
+
243
+ def order_state= state
244
+ self.order_states.push case state
245
+ when IB::OrderState
246
+ state
247
+ when Symbol, String
248
+ IB::OrderState.new :status => state
249
+ end
250
+ end
251
+
252
+ # Some properties received from IB are separated into OrderState object,
253
+ # but they are still readable as Order properties through delegation:
254
+ # Properties arriving via OpenOrder message:
255
+ [:commission, # double: Shows the commission amount on the order.
256
+ :commission_currency, # String: Shows the currency of the commission.
257
+ :min_commission, # The possible min range of the actual order commission.
258
+ :max_commission, # The possible max range of the actual order commission.
259
+ :warning_text, # String: Displays a warning message if warranted.
260
+ :init_margin, # Float: The impact the order would have on your initial margin.
261
+ :maint_margin, # Float: The impact the order would have on your maintenance margin.
262
+ :equity_with_loan, # Float: The impact the order would have on your equity
263
+ :status, # String: Displays the order status. See OrderState for values
264
+ # Properties arriving via OrderStatus message:
265
+ :filled, # int
266
+ :remaining, # int
267
+ :price, # double
268
+ :last_fill_price, # double
269
+ :average_price, # double
270
+ :average_fill_price, # double
271
+ :why_held, # String: comma-separated list of reasons for order to be held.
272
+ # Testing Order state:
273
+ :new?,
274
+ :submitted?,
275
+ :pending?,
276
+ :active?,
277
+ :inactive?,
278
+ :complete_fill?
279
+ ].each { |property| define_method(property) { order_state.send(property) } }
280
+
281
+ # Order is not valid without correct :local_id
282
+ validates_numericality_of :local_id, :perm_id, :client_id, :parent_id,
283
+ :quantity, :min_quantity, :display_size,
284
+ :only_integer => true, :allow_nil => true
285
+
286
+ validates_numericality_of :limit_price, :aux_price, :allow_nil => true
287
+
288
+
289
+ def default_attributes
290
+ super.merge :aux_price => 0.0,
291
+ :discretionary_amount => 0.0,
292
+ :parent_id => 0,
293
+ :tif => :day,
294
+ :order_type => :limit,
295
+ :open_close => :open,
296
+ :origin => :customer,
297
+ :short_sale_slot => :default,
298
+ :trigger_method => :default,
299
+ :oca_type => :none,
300
+ :auction_strategy => :none,
301
+ :designated_location => '',
302
+ :exempt_code => -1,
303
+ :display_size => 0,
304
+ :continuous_update => 0,
305
+ :delta_neutral_con_id => 0,
306
+ :algo_strategy => '',
307
+ :transmit => true,
308
+ :what_if => false,
309
+ :leg_prices => [],
310
+ :algo_params => HashWithIndifferentAccess.new, #{},
311
+ :combo_params => HashWithIndifferentAccess.new, #{},
312
+ :order_state => IB::OrderState.new(:status => 'New',
313
+ :filled => 0,
314
+ :remaining => 0,
315
+ :price => 0,
316
+ :average_price => 0)
317
+ end
318
+
319
+ def serialize_algo
320
+ if algo_strategy.nil? || algo_strategy.empty?
321
+ ''
322
+ else
323
+ [algo_strategy,
324
+ algo_params.size,
325
+ algo_params.to_a]
326
+ end
327
+ end
328
+
329
+ # Placement
330
+ def place contract, connection
331
+ error "Unable to place order, next_local_id not known" unless connection.next_local_id
332
+ self.client_id = connection.client_id
333
+ self.local_id = connection.next_local_id
334
+ connection.next_local_id += 1
335
+ self.placed_at = Time.now
336
+ modify contract, connection, self.placed_at
337
+ end
338
+
339
+ # Modify Order (convenience wrapper for send_message :PlaceOrder). Returns local_id.
340
+ def modify contract, connection, time=Time.now
341
+ self.modified_at = time
342
+ connection.send_message :PlaceOrder,
343
+ :order => self,
344
+ :contract => contract,
345
+ :local_id => local_id
346
+ local_id
347
+ end
348
+
349
+ # Order comparison
350
+ def == other
351
+ super(other) ||
352
+ other.is_a?(self.class) &&
353
+ (perm_id && other.perm_id && perm_id == other.perm_id ||
354
+ local_id == other.local_id && # ((p __LINE__)||true) &&
355
+ (client_id == other.client_id || client_id == 0 || other.client_id == 0) &&
356
+ parent_id == other.parent_id &&
357
+ tif == other.tif &&
358
+ action == other.action &&
359
+ order_type == other.order_type &&
360
+ quantity == other.quantity &&
361
+ (limit_price == other.limit_price || # TODO Floats should be Decimals!
362
+ (limit_price - other.limit_price).abs < 0.00001) &&
363
+ aux_price == other.aux_price &&
364
+ origin == other.origin &&
365
+ designated_location == other.designated_location &&
366
+ exempt_code == other.exempt_code &&
367
+ what_if == other.what_if &&
368
+ algo_strategy == other.algo_strategy &&
369
+ algo_params == other.algo_params)
370
+
371
+ # TODO: compare more attributes!
372
+ end
373
+
374
+ def to_s #human
375
+ "<Order:" + instance_variables.map do |key|
376
+ value = instance_variable_get(key)
377
+ " #{key}=#{value}" unless value.nil? || value == '' || value == 0
378
+ end.compact.join(',') + " >"
379
+ end
380
+
381
+ def to_human
382
+ "<Order: " + ((order_ref && order_ref != '') ? "#{order_ref} " : '') +
383
+ "#{self[:order_type]} #{self[:tif]} #{side} #{quantity} " +
384
+ (limit_price ? "#{limit_price} " : '') + "#{status} " +
385
+ ((aux_price && aux_price != 0) ? "/#{aux_price}" : '') +
386
+ "##{local_id}/#{perm_id} from #{client_id}" +
387
+ (account ? "/#{account}" : '') +
388
+ (commission ? " fee #{commission}" : '') + ">"
389
+ end
390
+ end # class Order
391
+ end # module IB
@@ -0,0 +1,128 @@
1
+ module IB
2
+
3
+ # OrderState represents dynamic (changeable) info about a single Order,
4
+ # isolating these changes and making Order essentially immutable
5
+ class OrderState < IB::Model
6
+ include BaseProperties
7
+
8
+ #p column_names
9
+ belongs_to :order
10
+
11
+ # Properties arriving via OpenOrder message
12
+ prop :init_margin, # Float: The impact the order would have on your initial margin.
13
+ :maint_margin, # Float: The impact the order would have on your maintenance margin.
14
+ :equity_with_loan, # Float: The impact the order would have on your equity
15
+ :commission, # double: Shows the commission amount on the order.
16
+ :min_commission, # The possible min range of the actual order commission.
17
+ :max_commission, # The possible max range of the actual order commission.
18
+ :commission_currency, # String: Shows the currency of the commission.
19
+ :warning_text # String: Displays a warning message if warranted.
20
+
21
+ # Properties arriving via OrderStatus message:
22
+ prop :filled, # int
23
+ :remaining, # int
24
+ [:price, :last_fill_price,], # double
25
+ [:average_price, :average_fill_price], # double
26
+ :why_held # String: comma-separated list of reasons for order to be held.
27
+
28
+ # Properties arriving in both messages:
29
+ prop :local_id, # int: Order id associated with client (volatile).
30
+ :perm_id, # int: TWS permanent id, remains the same over TWS sessions.
31
+ :client_id, # int: The id of the client that placed this order.
32
+ :parent_id, # int: The order ID of the parent (original) order, used
33
+ :status => :s # String: Displays the order status. Possible values include:
34
+ # - PendingSubmit - indicates that you have transmitted the order, but
35
+ # have not yet received confirmation that it has been accepted by the
36
+ # order destination. NOTE: This order status is NOT sent back by TWS
37
+ # and should be explicitly set by YOU when an order is submitted.
38
+ # - PendingCancel - indicates that you have sent a request to cancel
39
+ # the order but have not yet received cancel confirmation from the
40
+ # order destination. At this point, your order cancel is not confirmed.
41
+ # You may still receive an execution while your cancellation request
42
+ # is pending. NOTE: This order status is not sent back by TWS and
43
+ # should be explicitly set by YOU when an order is canceled.
44
+ # - PreSubmitted - indicates that a simulated order type has been
45
+ # accepted by the IB system and that this order has yet to be elected.
46
+ # The order is held in the IB system until the election criteria are
47
+ # met. At that time the order is transmitted to the order destination
48
+ # as specified.
49
+ # - Submitted - indicates that your order has been accepted at the order
50
+ # destination and is working.
51
+ # - Cancelled - indicates that the balance of your order has been
52
+ # confirmed canceled by the IB system. This could occur unexpectedly
53
+ # when IB or the destination has rejected your order.
54
+ # - ApiCancelled - canceled via API
55
+ # - Filled - indicates that the order has been completely filled.
56
+ # - Inactive - indicates that the order has been accepted by the system
57
+ # (simulated orders) or an exchange (native orders) but that currently
58
+ # the order is inactive due to system, exchange or other issues.
59
+
60
+ validates_format_of :status, :without => /\A\z/, :message => 'must not be empty'
61
+ validates_numericality_of :price, :average_price, :allow_nil => true
62
+ validates_numericality_of :local_id, :perm_id, :client_id, :parent_id, :filled,
63
+ :remaining, :only_integer => true, :allow_nil => true
64
+
65
+ ## Testing Order state:
66
+
67
+ def new?
68
+ status.empty? || status == 'New'
69
+ end
70
+
71
+ # Order is in a valid, working state on TWS side
72
+ def submitted?
73
+ status == 'PreSubmitted' || status == 'Submitted'
74
+ end
75
+
76
+ # Order is in a valid, working state on TWS side
77
+ def pending?
78
+ submitted? || status == 'PendingSubmit'
79
+ end
80
+
81
+ # Order is in invalid state
82
+ def active?
83
+ new? || pending?
84
+ end
85
+
86
+ # Order is in invalid state
87
+ def inactive?
88
+ !active? # status == 'Inactive'
89
+ end
90
+
91
+ def complete_fill?
92
+ status == 'Filled' && remaining == 0 # filled >= total_quantity # Manually corrected
93
+ end
94
+
95
+ # Comparison
96
+ def == other
97
+
98
+ super(other) ||
99
+ other.is_a?(self.class) &&
100
+ status == other.status &&
101
+ local_id == other.local_id &&
102
+ perm_id == other.perm_id &&
103
+ client_id == other.client_id &&
104
+ filled == other.filled &&
105
+ remaining == other.remaining &&
106
+ last_fill_price == other.last_fill_price &&
107
+ init_margin == other.init_margin &&
108
+ maint_margin == other.maint_margin &&
109
+ equity_with_loan == other.equity_with_loan &&
110
+ why_held == other.why_held &&
111
+ warning_text == other.warning_text &&
112
+ commission == other.commission
113
+ end
114
+
115
+ def to_human
116
+ "<OrderState: #{status} ##{local_id}/#{perm_id} from #{client_id}" +
117
+ (filled ? " filled #{filled}/#{remaining}" : '') +
118
+ (last_fill_price ? " at #{last_fill_price}/#{average_fill_price}" : '') +
119
+ (init_margin ? " margin #{init_margin}/#{maint_margin}" : '') +
120
+ (equity_with_loan ? " equity #{equity_with_loan}" : '') +
121
+ (commission && commission > 0 ? " fee #{commission}" : "") +
122
+ (why_held ? " why_held #{why_held}" : '') +
123
+ ((warning_text && warning_text != '') ? " warning #{warning_text}" : '') + ">"
124
+ end
125
+
126
+ alias to_s to_human
127
+ end # class Order
128
+ end # module IB