Class: Tastytrade::Session

Inherits:
Object
  • Object
show all
Defined in:
lib/tastytrade/session.rb

Overview

Manages authentication and session state for Tastytrade API

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(username:, password: nil, remember_me: false, remember_token: nil, is_test: false, timeout: Client::DEFAULT_TIMEOUT) ⇒ Session

Initialize a new session

Parameters:

  • username (String)

    Tastytrade username

  • password (String) (defaults to: nil)

    Tastytrade password (optional if remember_token provided)

  • remember_me (Boolean) (defaults to: false)

    Whether to save remember token

  • remember_token (String) (defaults to: nil)

    Existing remember token for re-authentication

  • is_test (Boolean) (defaults to: false)

    Use test environment



37
38
39
40
41
42
43
44
# File 'lib/tastytrade/session.rb', line 37

def initialize(username:, password: nil, remember_me: false, remember_token: nil, is_test: false, timeout: Client::DEFAULT_TIMEOUT)
  @username = username
  @password = password
  @remember_me = remember_me
  @remember_token = remember_token
  @is_test = is_test
  @client = Client.new(base_url: api_url, timeout: timeout)
end

Instance Attribute Details

#is_testObject (readonly)

Returns the value of attribute is_test.



8
9
10
# File 'lib/tastytrade/session.rb', line 8

def is_test
  @is_test
end

#remember_tokenObject (readonly)

Returns the value of attribute remember_token.



8
9
10
# File 'lib/tastytrade/session.rb', line 8

def remember_token
  @remember_token
end

#session_expirationObject (readonly)

Returns the value of attribute session_expiration.



8
9
10
# File 'lib/tastytrade/session.rb', line 8

def session_expiration
  @session_expiration
end

#session_tokenObject (readonly)

Returns the value of attribute session_token.



8
9
10
# File 'lib/tastytrade/session.rb', line 8

def session_token
  @session_token
end

#userObject (readonly)

Returns the value of attribute user.



8
9
10
# File 'lib/tastytrade/session.rb', line 8

def user
  @user
end

Class Method Details

.from_environmentSession?

Create a session from environment variables

Returns:

  • (Session, nil)

    Session instance or nil if environment variables not set



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/tastytrade/session.rb', line 13

def self.from_environment
  username = ENV["TASTYTRADE_USERNAME"] || ENV["TT_USERNAME"]
  password = ENV["TASTYTRADE_PASSWORD"] || ENV["TT_PASSWORD"]

  return nil unless username && password

  remember = ENV["TASTYTRADE_REMEMBER"]&.downcase == "true" || ENV["TT_REMEMBER"]&.downcase == "true"
  is_test = ENV["TASTYTRADE_ENVIRONMENT"]&.downcase == "sandbox" || ENV["TT_ENVIRONMENT"]&.downcase == "sandbox"

  new(
    username: username,
    password: password,
    remember_me: remember,
    is_test: is_test
  )
end

Instance Method Details

#authenticated?Boolean

Check if authenticated

Returns:

  • (Boolean)

    True if session has token



129
130
131
# File 'lib/tastytrade/session.rb', line 129

def authenticated?
  !@session_token.nil?
end

#delete(path) ⇒ Hash

Make authenticated DELETE request

Parameters:

  • path (String)

    API endpoint path

Returns:

  • (Hash)

    Parsed response



122
123
124
# File 'lib/tastytrade/session.rb', line 122

def delete(path)
  @client.delete(path, auth_headers)
end

#destroynil

Destroy current session

Returns:

  • (nil)


84
85
86
87
88
89
# File 'lib/tastytrade/session.rb', line 84

def destroy
  delete("/sessions") if @session_token
  @session_token = nil
  @remember_token = nil
  @user = nil
end

#expired?Boolean

Check if session is expired

Returns:

  • (Boolean)

    True if session is expired



136
137
138
139
# File 'lib/tastytrade/session.rb', line 136

def expired?
  return false unless @session_expiration
  Time.now >= @session_expiration
end

#get(path, params = {}) ⇒ Hash

Make authenticated GET request

Parameters:

  • path (String)

    API endpoint path

  • params (Hash) (defaults to: {})

    Query parameters

Returns:

  • (Hash)

    Parsed response



96
97
98
# File 'lib/tastytrade/session.rb', line 96

def get(path, params = {})
  @client.get(path, params, auth_headers)
end

#loginSession

Authenticate with Tastytrade API

Returns:

  • (Session)

    Self for method chaining

Raises:



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/tastytrade/session.rb', line 50

def 
  response = @client.post("/sessions", )
  data = response["data"]

  @user = Models::User.new(data["user"])
  @session_token = data["session-token"]
  @remember_token = data["remember-token"] if @remember_me

  # Track session expiration if provided
  if data["session-expiration"]
    @session_expiration = Time.parse(data["session-expiration"])
  end

  self
end

#post(path, body = {}) ⇒ Hash

Make authenticated POST request

Parameters:

  • path (String)

    API endpoint path

  • body (Hash) (defaults to: {})

    Request body

Returns:

  • (Hash)

    Parsed response



105
106
107
# File 'lib/tastytrade/session.rb', line 105

def post(path, body = {})
  @client.post(path, body, auth_headers)
end

#put(path, body = {}) ⇒ Hash

Make authenticated PUT request

Parameters:

  • path (String)

    API endpoint path

  • body (Hash) (defaults to: {})

    Request body

Returns:

  • (Hash)

    Parsed response



114
115
116
# File 'lib/tastytrade/session.rb', line 114

def put(path, body = {})
  @client.put(path, body, auth_headers)
end

#refresh_sessionSession

Refresh session using remember token

Returns:

Raises:



153
154
155
156
157
158
159
# File 'lib/tastytrade/session.rb', line 153

def refresh_session
  raise Tastytrade::Error, "No remember token available" unless @remember_token

  # Clear password and re-login with remember token
  @password = nil
  
end

#time_until_expiryFloat?

Time remaining until session expires

Returns:

  • (Float, nil)

    Seconds until expiration



144
145
146
147
# File 'lib/tastytrade/session.rb', line 144

def time_until_expiry
  return nil unless @session_expiration
  @session_expiration - Time.now
end

#validateBoolean

Validate current session

Returns:

  • (Boolean)

    True if session is valid



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/tastytrade/session.rb', line 69

def validate
  warn "DEBUG: Validating session, user=#{@user&.email}" if ENV["DEBUG_SESSION"]
  response = get("/sessions/validate")
  if ENV["DEBUG_SESSION"]
    warn "DEBUG: Validate response email=#{response["data"]["email"]}, user email=#{@user&.email}"
  end
  response["data"]["email"] == @user.email
rescue Tastytrade::Error => e
  warn "DEBUG: Validate error: #{e.message}" if ENV["DEBUG_SESSION"]
  false
end