Class: Tastytrade::CLI

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

Overview

Main CLI class for Tastytrade gem

Defined Under Namespace

Classes: Orders

Instance Method Summary collapse

Methods included from CLIHelpers

#authenticated?, #color_value, #config, #current_account, #current_account_number, #current_session, #display_trading_status, #error, #format_bp_status, #format_currency, included, #info, #pastel, #prompt, #require_authentication!, #success, #warning

Instance Method Details

#accountsObject



206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
# File 'lib/tastytrade/cli.rb', line 206

def accounts
  require_authentication!
  info "Fetching accounts..."

  accounts = fetch_accounts
  return if accounts.nil? || accounts.empty?

  display_accounts_table(accounts)
  (accounts)
rescue Tastytrade::Error => e
  error "Failed to fetch accounts: #{e.message}"
  exit 1
rescue StandardError => e
  error "Unexpected error: #{e.message}"
  exit 1
end

#balanceObject



359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/tastytrade/cli.rb', line 359

def balance
  require_authentication!

  if options[:all]
    
  else
     = 
    unless 
       = 
      return unless 
    end
    ()
  end
rescue => e
  error "Failed to fetch balance: #{e.message}"
  exit 1
end

#buying_powerObject

Display buying power status and usage

Examples:

Display buying power status

tastytrade buying_power

Display buying power for specific account

tastytrade buying_power --account 5WX12345


540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/tastytrade/cli.rb', line 540

def buying_power
  require_authentication!

  # Get the account to use
   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

  info "Fetching buying power status for account #{.}..."

  balance = .get_balances(current_session)

  # Create buying power status table
  headers = ["Buying Power Type", "Available", "Usage %", "Status"]
  rows = [
    [
      "Equity Buying Power",
      format_currency(balance.equity_buying_power),
      "#{balance.buying_power_usage_percentage.to_s("F")}%",
      format_bp_status(balance.buying_power_usage_percentage)
    ],
    [
      "Derivative Buying Power",
      format_currency(balance.derivative_buying_power),
      "#{balance.derivative_buying_power_usage_percentage.to_s("F")}%",
      format_bp_status(balance.derivative_buying_power_usage_percentage)
    ],
    [
      "Day Trading Buying Power",
      format_currency(balance.day_trading_buying_power),
      "-",
      balance.day_trading_buying_power > 0 ? pastel.green("Available") : pastel.yellow("N/A")
    ]
  ]

  table = TTY::Table.new(headers, rows)

  puts
  begin
    puts table.render(:unicode, padding: [0, 1])
  rescue StandardError
    # Fallback for testing or non-TTY environments
    puts headers.join(" | ")
    puts "-" * 80
    rows.each { |row| puts row.join(" | ") }
  end

  # Display additional metrics
  puts
  puts "Additional Information:"
  puts "  Available Trading Funds: #{format_currency(balance.available_trading_funds)}"
  puts "  Cash Balance: #{format_currency(balance.cash_balance)}"
  puts "  Net Liquidating Value: #{format_currency(balance.net_liquidating_value)}"

  # Display warnings if needed
  if balance.high_buying_power_usage?
    puts
    warning "High buying power usage detected! Consider reducing positions."
  end
rescue Tastytrade::Error => e
  error "Failed to fetch buying power status: #{e.message}"
  exit 1
rescue StandardError => e
  error "Unexpected error: #{e.message}"
  exit 1
end

#historyObject

Display transaction history with optional filtering and grouping

Examples:

Display all transactions

tastytrade history

Display transactions for a specific symbol

tastytrade history --symbol AAPL

Display transactions for a date range

tastytrade history --start-date 2024-01-01 --end-date 2024-12-31

Group transactions by symbol

tastytrade history --group-by symbol

Filter by transaction type

tastytrade history --type Trade


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

def history
  require_authentication!

  # Get the account to use
   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

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

  # Build filter options
  filter_options = {}
  filter_options[:start_date] = Date.parse(options[:start_date]) if options[:start_date]
  filter_options[:end_date] = Date.parse(options[:end_date]) if options[:end_date]
  filter_options[:symbol] = options[:symbol].upcase if options[:symbol]
  filter_options[:transaction_types] = [options[:type]] if options[:type]
  filter_options[:per_page] = options[:limit] if options[:limit]

  # Fetch transactions
  transactions = .get_transactions(current_session, **filter_options)

  if transactions.empty?
    warning "No transactions found"
    return
  end

  # Display transactions using formatter
  formatter = Tastytrade::HistoryFormatter.new(pastel: pastel)
  group_by = options[:group_by]&.to_sym
  formatter.format_table(transactions, group_by: group_by)
rescue Date::Error => e
  error "Invalid date format: #{e.message}. Use YYYY-MM-DD format."
  exit 1
rescue Tastytrade::Error => e
  error "Failed to fetch transaction history: #{e.message}"
  exit 1
rescue StandardError => e
  error "Unexpected error: #{e.message}"
  exit 1
end

#interactiveObject



676
677
678
679
# File 'lib/tastytrade/cli.rb', line 676

def interactive
  require_authentication!
  interactive_mode
end

#loginObject



50
51
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/tastytrade/cli.rb', line 50

def 
  # Try environment variables first
  if (session = Session.from_environment)
    environment = session.instance_variable_get(:@is_test) ? "sandbox" : "production"
    info "Using credentials from environment variables..."
    info "Logging in to #{environment} environment..."

    begin
      session.
      success "Successfully logged in as #{session.user.email}"

      save_user_session(session, {
                          username: session.user.email,
                          remember: session.remember_token ? true : false
                        }, environment)

      @current_session = session
      interactive_mode unless options[:no_interactive]
      return
    rescue Tastytrade::Error => e
      error "Environment variable login failed: #{e.message}"
      info "Falling back to interactive login..."
    end
  end

  # Fall back to interactive login
  environment = options[:test] ? "sandbox" : "production"
  credentials = 
  info "Logging in to #{environment} environment..."
  session = authenticate_user(credentials)

  # Update credentials with actual email from session
  credentials_with_email = credentials.merge(username: session.user.email)
  save_user_session(session, credentials_with_email, environment)

  # Enter interactive mode after successful login (unless --no-interactive)
  @current_session = session
  interactive_mode unless options[:no_interactive]
rescue Tastytrade::InvalidCredentialsError => e
  error "Invalid credentials: #{e.message}"
  exit 1
rescue Tastytrade::SessionExpiredError => e
  error "Session expired: #{e.message}"
  info "Please login again"
  exit 1
rescue Tastytrade::NetworkTimeoutError => e
  error "Network timeout: #{e.message}"
  info "Check your internet connection and try again"
  exit 1
rescue Tastytrade::Error => e
  error e.message
  exit 1
rescue StandardError => e
  error "Login failed: #{e.message}"
  exit 1
end

#logoutObject



163
164
165
166
167
168
# File 'lib/tastytrade/cli.rb', line 163

def logout
  session_info = current_session_info
  return warning("No active session found") unless session_info

  clear_user_session(session_info)
end

#place(symbol, quantity) ⇒ Object

Place an order for equities

Examples:

Place a market buy order

tastytrade place AAPL 100

Place a limit buy order

tastytrade place AAPL 100 --type limit --price 150.50

Place a sell order

tastytrade place AAPL 100 --action sell

Dry run an order

tastytrade place AAPL 100 --dry-run


705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
# File 'lib/tastytrade/cli.rb', line 705

def place(symbol, quantity)
  require_authentication!

  # Get the account to use
   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

  # Create the order leg
  action = case options[:action].downcase
           when "buy"
             Tastytrade::OrderAction::BUY_TO_OPEN
           when "sell"
             Tastytrade::OrderAction::SELL_TO_CLOSE
           else
             error "Invalid action: #{options[:action]}. Must be 'buy' or 'sell'"
             exit 1
  end

  leg = Tastytrade::OrderLeg.new(
    action: action,
    symbol: symbol.upcase,
    quantity: quantity
  )

  # Create the order
  order_type = case options[:type].downcase
               when "market"
                 Tastytrade::OrderType::MARKET
               when "limit"
                 Tastytrade::OrderType::LIMIT
               else
                 error "Invalid order type: #{options[:type]}. Must be 'market' or 'limit'"
                 exit 1
  end

  begin
    order = Tastytrade::Order.new(
      type: order_type,
      legs: leg,
      price: options[:price]
    )
  rescue ArgumentError => e
    error e.message
    exit 1
  end

  # Place the order
  order_desc = "#{options[:type]} #{options[:action]} order for #{quantity} shares of #{symbol}"
  info "Placing #{options[:dry_run] ? "simulated " : ""}#{order_desc}..."

  begin
    # First do a dry run to check buying power impact
    dry_run_response = .place_order(current_session, order, dry_run: true)

    # Check if this is a BuyingPowerEffect object
    if dry_run_response.buying_power_effect.is_a?(Tastytrade::Models::BuyingPowerEffect)
      bp_effect = dry_run_response.buying_power_effect
      bp_usage = bp_effect.buying_power_usage_percentage

      if bp_usage > 80
        warning "This order will use #{bp_usage.to_s("F")}% of your buying power!"

        # Fetch current balance for more context
        balance = .get_balances(current_session)
        puts ""
        puts "Current Buying Power Status:"
        puts "  Available Trading Funds: #{format_currency(balance.available_trading_funds)}"
        puts "  Equity Buying Power: #{format_currency(balance.equity_buying_power)}"
        puts "  Current BP Usage: #{balance.buying_power_usage_percentage.to_s("F")}%"
        puts ""

        unless options[:dry_run]
          unless prompt.yes?("Are you sure you want to proceed with this order?")
            info "Order cancelled"
            return
          end
        end
      end
    end

    # Place the actual order if not dry run
    if options[:dry_run]
      response = dry_run_response
      success "Dry run successful!"
    else
      response = .place_order(current_session, order, dry_run: false)
      success "Order placed successfully!"
    end

    puts ""
    puts "Order Details:"
    if response.order_id && !response.order_id.empty?
      puts "  Order ID: #{response.order_id}"
    end
    if response.status && !response.status.empty?
      puts "  Status: #{response.status}"
    end
    if response. && !response..empty?
      puts "  Account: #{response.}"
    end

    # Handle both BigDecimal and BuyingPowerEffect
    if response.buying_power_effect
      if response.buying_power_effect.is_a?(Tastytrade::Models::BuyingPowerEffect)
        bp_effect = response.buying_power_effect
        puts "  Buying Power Impact: #{format_currency(bp_effect.buying_power_change_amount)}"
        puts "  BP Usage: #{bp_effect.buying_power_usage_percentage.to_s("F")}%"
      else
        puts "  Buying Power Effect: #{format_currency(response.buying_power_effect)}"
      end
    end

    if response.warnings.any?
      puts ""
      warning "Warnings:"
      response.warnings.each do |w|
        if w.is_a?(Hash)
          puts "  - #{w["message"] || w["code"]}"
        else
          puts "  - #{w}"
        end
      end
    end
  rescue Tastytrade::Error => e
    error "Failed to place order: #{e.message}"
    exit 1
  end
end

#positionsObject

Display account positions with optional filtering

Examples:

Display all open positions

tastytrade positions

Display positions for a specific symbol

tastytrade positions --symbol AAPL

Display option positions for an underlying symbol

tastytrade positions --underlying-symbol SPY

Include closed positions

tastytrade positions --include-closed

Display positions for a specific account

tastytrade positions --account 5WX12345


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

def positions
  require_authentication!

  # Get the account to use
   = if options[:account]
    Tastytrade::Models::Account.get(current_session, options[:account])
  else
     || 
  end

  return unless 

  info "Fetching positions for account #{.}..."

  # Fetch positions with filters
  positions = .get_positions(
    current_session,
    symbol: options[:symbol],
    underlying_symbol: options[:underlying_symbol],
    include_closed: options[:include_closed]
  )

  if positions.empty?
    warning "No positions found"
    return
  end

  # Display positions using formatter
  formatter = Tastytrade::PositionsFormatter.new(pastel: pastel)
  formatter.format_table(positions)
rescue Tastytrade::Error => e
  error "Failed to fetch positions: #{e.message}"
  exit 1
rescue StandardError => e
  error "Unexpected error: #{e.message}"
  exit 1
end

#refreshObject



642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/tastytrade/cli.rb', line 642

def refresh
  session = current_session
  unless session
    error "No active session to refresh"
    exit 1
  end

  unless session.remember_token
    error "No remember token available for refresh"
    info "Login with --remember flag to enable session refresh"
    exit 1
  end

  info "Refreshing session..."

  begin
    session.refresh_session

    # Save refreshed session
    manager = SessionManager.new(
      username: session.user.email,
      environment: config.get("environment") || "production"
    )
    manager.save_session(session)

    success "Session refreshed successfully"
    info "Session expires in #{format_time_remaining(session.time_until_expiry)}" if session.time_until_expiry
  rescue Tastytrade::TokenRefreshError => e
    error "Failed to refresh session: #{e.message}"
    exit 1
  end
end

#selectObject



281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'lib/tastytrade/cli.rb', line 281

def select
  require_authentication!

  accounts = fetch_accounts
  return if accounts.nil? || accounts.empty?

  (accounts) || (accounts)
rescue Tastytrade::Error => e
  error "Failed to fetch accounts: #{e.message}"
  exit 1
rescue StandardError => e
  error "Unexpected error: #{e.message}"
  exit 1
end

#statusObject



612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
# File 'lib/tastytrade/cli.rb', line 612

def status
  session = current_session
  unless session
    warning "No active session"
    info "Run 'tastytrade login' to authenticate"
    return
  end

  puts "Session Status:"
  puts "  User: #{session.user.email}"
  puts "  Environment: #{config.get("environment") || "production"}"

  if session.session_expiration
    if session.expired?
      puts "  Status: #{pastel.red("Expired")}"
    else
      time_left = format_time_remaining(session.time_until_expiry)
      puts "  Status: #{pastel.green("Active")}"
      puts "  Expires in: #{time_left}"
    end
  else
    puts "  Status: #{pastel.green("Active")}"
    puts "  Expires in: Unknown"
  end

  puts "  Remember token: #{session.remember_token ? pastel.green("Available") : pastel.red("Not available")}"
  puts "  Auto-refresh: #{session.remember_token ? pastel.green("Enabled") : pastel.yellow("Disabled")}"
end

#trading_statusObject



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/tastytrade/cli.rb', line 439

def trading_status
  require_authentication!

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

  return unless 

  trading_status = .get_trading_status(current_session)
  display_trading_status(trading_status)
rescue Tastytrade::Error => e
  error "Failed to fetch trading status: #{e.message}"
  exit 1
rescue StandardError => e
  error "Unexpected error: #{e.message}"
  exit 1
end

#versionObject



24
25
26
# File 'lib/tastytrade/cli.rb', line 24

def version
  puts "Tastytrade CLI v#{Tastytrade::VERSION}"
end