Class: Tastytrade::CLI::Orders

Inherits:
Thor
  • Object
show all
Includes:
Tastytrade::CLIHelpers
Defined in:
lib/tastytrade/cli/orders.rb

Overview

Thor subcommand for order management

Instance Method Summary collapse

Methods included from Tastytrade::CLIHelpers

#authenticated?, #color_value, #config, #current_account_number, #display_trading_status, #error, #format_bp_status, included, #info, #success, #warning

Instance Method Details

#cancel(order_id) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/tastytrade/cli/orders.rb', line 70

def cancel(order_id)
  require_authentication!

   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

  # First, fetch the order to display it
  orders = .get_live_orders(current_session)
  order = orders.find { |o| o.id == order_id }

  unless order
    error "Order #{order_id} not found"
    exit 1
  end

  unless order.cancellable?
    error "Order #{order_id} is not cancellable (status: #{order.status})"
    exit 1
  end

  # Display order details
  puts ""
  puts "Order to cancel:"
  puts "  Order ID: #{order.id}"
  puts "  Symbol: #{order.underlying_symbol}"
  puts "  Type: #{order.order_type}"
  puts "  Status: #{order.status}"
  puts "  Price: #{format_currency(order.price)}" if order.price

  if order.legs.any?
    leg = order.legs.first
    puts "  Action: #{leg.action} #{leg.quantity} shares"
    if leg.partially_filled?
      puts "  Filled: #{leg.filled_quantity} of #{leg.quantity} shares"
    end
  end

  puts ""
  unless prompt.yes?("Are you sure you want to cancel this order?")
    info "Cancellation aborted"
    return
  end

  info "Cancelling order #{order_id}..."

  begin
    .cancel_order(current_session, order_id)
    success "Order #{order_id} cancelled successfully"
  rescue Tastytrade::OrderAlreadyFilledError => e
    error "Cannot cancel: #{e.message}"
    exit 1
  rescue Tastytrade::OrderNotCancellableError => e
    error "Cannot cancel: #{e.message}"
    exit 1
  rescue Tastytrade::Error => e
    error "Failed to cancel order: #{e.message}"
    exit 1
  end
end

#get(order_id) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/tastytrade/cli/orders.rb', line 188

def get(order_id)
  require_authentication!

   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

  info "Fetching order #{order_id}..."

  begin
    order = .get_order(current_session, order_id)

    if options[:format] == "json"
      puts JSON.pretty_generate(order.to_h)
    else
      display_order_details(order)
    end
  rescue Tastytrade::Error => e
    error "Failed to fetch order: #{e.message}"
    exit 1
  end
end

#historyObject



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
# File 'lib/tastytrade/cli/orders.rb', line 143

def history
  require_authentication!

   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

  # Parse date filters
  from_time = Time.parse(options[:from]) if options[:from]
  to_time = Time.parse(options[:to]) if options[:to]
  # Set to end of day if only date was provided
  to_time = to_time + (24 * 60 * 60) - 1 if to_time && to_time.hour == 0 && to_time.min == 0

  info "Fetching order history for account #{.}..."

  orders = .get_order_history(
    current_session,
    status: options[:status],
    underlying_symbol: options[:symbol],
    from_time: from_time,
    to_time: to_time,
    page_limit: options[:limit]
  )

  if orders.empty?
    info "No historical orders found"
    return
  end

  if options[:format] == "json"
    puts JSON.pretty_generate(orders.map(&:to_h))
  else
    # Sort by created_at desc (most recent first)
    orders.sort! { |a, b| (b.created_at || Time.now) <=> (a.created_at || Time.now) }
    display_orders(orders.map { |order| [, order] }, nil, show_account: false)
  end
end

#listObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/tastytrade/cli/orders.rb', line 19

def list
  require_authentication!

  accounts = if options[:all]
    Tastytrade::Models::Account.get_all(current_session)
  else
    [ || ]
  end

  return unless accounts.all?

  all_orders = []
  accounts.each do ||
    next if .closed?

    info "Fetching orders for account #{.}..." if options[:all]
    orders = .get_live_orders(
      current_session,
      status: options[:status],
      underlying_symbol: options[:symbol]
    )
    all_orders.concat(orders.map { |order| [, order] })
  end

  if all_orders.empty?
    info "No orders found"
    return
  end

  # Sort by created_at desc (most recent first)
  all_orders.sort! { |a, b| (b[1].created_at || Time.now) <=> (a[1].created_at || Time.now) }

  if options[:format] == "json"
    # Output as JSON
    output = all_orders.map do |, order|
      order_hash = order.to_h
      order_hash[:account_number] = . if options[:all]
      order_hash
    end
    puts JSON.pretty_generate(output)
  else
    # Fetch market data for unique symbols
    unique_symbols = all_orders.map { |_, order| order.underlying_symbol }.uniq.compact
    market_data = fetch_market_data(unique_symbols) if unique_symbols.any?

    display_orders(all_orders, market_data, show_account: options[:all])
  end
end

#placeObject



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
# File 'lib/tastytrade/cli/orders.rb', line 225

def place
  require_authentication!

   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

  # Map user-friendly action names to API constants
  action_map = {
    "buy_to_open" => Tastytrade::OrderAction::BUY_TO_OPEN,
    "bto" => Tastytrade::OrderAction::BUY_TO_OPEN,
    "sell_to_close" => Tastytrade::OrderAction::SELL_TO_CLOSE,
    "stc" => Tastytrade::OrderAction::SELL_TO_CLOSE,
    "sell_to_open" => Tastytrade::OrderAction::SELL_TO_OPEN,
    "sto" => Tastytrade::OrderAction::SELL_TO_OPEN,
    "buy_to_close" => Tastytrade::OrderAction::BUY_TO_CLOSE,
    "btc" => Tastytrade::OrderAction::BUY_TO_CLOSE
  }

  action = action_map[options[:action].downcase]
  unless action
    error "Invalid action. Must be one of: #{action_map.keys.join(", ")}"
    exit 1
  end

  # Map order type
  order_type = case options[:type].downcase
               when "market", "mkt"
                 Tastytrade::OrderType::MARKET
               when "limit", "lmt"
                 Tastytrade::OrderType::LIMIT
               when "stop", "stp"
                 Tastytrade::OrderType::STOP
               else
                 error "Invalid order type. Must be: market, limit, or stop"
    exit 1
  end

  # Validate price for limit orders
  if order_type == Tastytrade::OrderType::LIMIT && options[:price].nil?
    error "Price is required for limit orders"
    exit 1
  end

  # Map time in force
  time_in_force = case options[:time_in_force].downcase
                  when "day", "d"
                    Tastytrade::OrderTimeInForce::DAY
                  when "gtc", "g", "good_till_cancelled"
                    Tastytrade::OrderTimeInForce::GTC
                  else
                    error "Invalid time in force. Must be: day or gtc"
                    exit 1
  end

  # Create the order
  leg = Tastytrade::OrderLeg.new(
    action: action,
    symbol: options[:symbol].upcase,
    quantity: options[:quantity].to_i
  )

  order = Tastytrade::Order.new(
    type: order_type,
    time_in_force: time_in_force,
    legs: leg,
    price: options[:price] ? BigDecimal(options[:price].to_s) : nil
  )

  # Display order summary
  puts ""
  puts "Order Summary:"
  puts "  Account: #{.}"
  puts "  Symbol: #{options[:symbol].upcase}"
  puts "  Action: #{action}"
  puts "  Quantity: #{options[:quantity]}"
  puts "  Type: #{order_type}"
  puts "  Time in Force: #{time_in_force}"
  puts "  Price: #{options[:price] ? format_currency(options[:price]) : "Market"}"
  puts ""

  # Perform dry-run validation first
  info "Validating order..."
  begin
    validator = Tastytrade::OrderValidator.new(current_session, , order)

    # Always do a dry-run to get buying power effect
    dry_run_response = validator.dry_run_validate!

    if dry_run_response && dry_run_response.buying_power_effect
      effect = dry_run_response.buying_power_effect
      puts "Buying Power Impact:"
      puts "  Current BP: #{format_currency(effect.current_buying_power)}"
      puts "  Order Impact: #{format_currency(effect.buying_power_change_amount)}"
      puts "  New BP: #{format_currency(effect.new_buying_power)}"
      puts "  BP Usage: #{effect.buying_power_usage_percentage}%"
      puts ""
    end

    # Display any warnings
    if validator.warnings.any?
      puts "Warnings:"
      validator.warnings.each { |w| warning "  - #{w}" }
      puts ""
    end

    # Check for validation errors
    if validator.errors.any?
      error "Validation failed:"
      validator.errors.each { |e| error "  - #{e}" }
      exit 1
    end

  rescue Tastytrade::OrderValidationError => e
    error "Order validation failed:"
    e.errors.each { |err| error "  - #{err}" }
    exit 1
  rescue StandardError => e
    error "Validation error: #{e.message}"
    exit 1
  end

  # If dry-run only, stop here
  if options[:dry_run]
    success "Dry-run validation passed! Order is valid but was not placed."
    return
  end

  # Confirmation prompt
  unless options[:skip_confirmation]
    prompt = TTY::Prompt.new
    unless prompt.yes?("Place this order?")
      info "Order cancelled by user"
      return
    end
  end

  # Place the order
  info "Placing order..."
  begin
    response = .place_order(current_session, order, skip_validation: true)

    success "Order placed successfully!"
    puts ""
    puts "Order Details:"
    puts "  Order ID: #{response.order_id}"
    puts "  Status: #{response.status}"

    if response.buying_power_effect
      puts "  Buying Power Effect: #{format_currency(response.buying_power_effect)}"
    end

  rescue Tastytrade::OrderValidationError => e
    error "Order validation failed:"
    e.errors.each { |err| error "  - #{err}" }
    exit 1
  rescue Tastytrade::InsufficientFundsError => e
    error "Insufficient funds: #{e.message}"
    exit 1
  rescue Tastytrade::MarketClosedError => e
    error "Market closed: #{e.message}"
    exit 1
  rescue Tastytrade::Error => e
    error "Failed to place order: #{e.message}"
    exit 1
  end
end

#replace(order_id) ⇒ Object



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/tastytrade/cli/orders.rb', line 401

def replace(order_id)
  require_authentication!

   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

  # Fetch the order to modify
  orders = .get_live_orders(current_session)
  order = orders.find { |o| o.id == order_id }

  unless order
    error "Order #{order_id} not found"
    exit 1
  end

  unless order.editable?
    error "Order #{order_id} is not editable (status: #{order.status})"
    exit 1
  end

  # Display current order details
  puts ""
  puts "Current order:"
  puts "  Order ID: #{order.id}"
  puts "  Symbol: #{order.underlying_symbol}"
  puts "  Type: #{order.order_type}"
  puts "  Status: #{order.status}"
  puts "  Current Price: #{format_currency(order.price)}" if order.price

  leg = order.legs.first if order.legs.any?
  if leg
    puts "  Action: #{leg.action} #{leg.quantity} shares"
    puts "  Remaining: #{leg.remaining_quantity} shares"
    if leg.partially_filled?
      puts "  Filled: #{leg.filled_quantity} shares"
    end
  end

  # Interactive prompts for new values if not provided
  new_price = if options[:price]
    BigDecimal(options[:price].to_s)
  elsif order.order_type == "Limit"
    puts ""
    current_price_str = order.price ? order.price.to_s("F") : "N/A"
    price_input = prompt.ask("New price (current: #{current_price_str}):",
                              default: current_price_str,
                              convert: :float)
    BigDecimal(price_input.to_s) if price_input
  else
    order.price
  end

  new_quantity = if options[:quantity]
    options[:quantity].to_i
  elsif leg
    puts ""
    max_qty = leg.remaining_quantity
    quantity_input = prompt.ask("New quantity (current: #{max_qty}, max: #{max_qty}):",
                                 default: max_qty,
                                 convert: :int) do |q|
      q.in("1-#{leg.remaining_quantity}")
      q.messages[:range?] = "Quantity must be between 1 and #{leg.remaining_quantity}"
    end
    quantity_input
  else
    nil
  end

  # Show summary of changes
  puts ""
  puts "Order modifications:"
  if new_price && order.price != new_price
    puts "  Price: #{format_currency(order.price)}#{format_currency(new_price)}"
  end
  if new_quantity && leg && leg.remaining_quantity != new_quantity
    puts "  Quantity: #{leg.remaining_quantity}#{new_quantity}"
  end

  puts ""
  unless prompt.yes?("Proceed with these changes?")
    info "Replacement cancelled"
    return
  end

  # Create new order with modifications
  begin
    # Recreate the order with new parameters
    action = if leg
      case leg.action.downcase
      when "buy", "buy to open"
        Tastytrade::OrderAction::BUY_TO_OPEN
      when "sell", "sell to close"
        Tastytrade::OrderAction::SELL_TO_CLOSE
      else
        leg.action
      end
    end

    new_leg = Tastytrade::OrderLeg.new(
      action: action,
      symbol: leg.symbol,
      quantity: new_quantity || leg.remaining_quantity
    )

    order_type = case order.order_type.downcase
                 when "market"
                   Tastytrade::OrderType::MARKET
                 when "limit"
                   Tastytrade::OrderType::LIMIT
                 else
                   order.order_type
    end

    new_order = Tastytrade::Order.new(
      type: order_type,
      legs: new_leg,
      price: new_price
    )

    info "Replacing order #{order_id}..."
    response = .replace_order(current_session, order_id, new_order)

    success "Order replaced successfully!"
    puts ""
    puts "New Order Details:"
    puts "  Order ID: #{response.order_id}"
    puts "  Status: #{response.status}"
    puts "  Price: #{format_currency(new_price)}" if new_price

  rescue Tastytrade::OrderNotEditableError => e
    error "Cannot replace: #{e.message}"
    exit 1
  rescue Tastytrade::InsufficientQuantityError => e
    error "Cannot replace: #{e.message}"
    exit 1
  rescue Tastytrade::Error => e
    error "Failed to replace order: #{e.message}"
    exit 1
  end
end