Class: Tda::Option

Inherits:
Object
  • Object
show all
Includes:
HTTParty
Defined in:
app/models/tda/option.rb

Overview

class Schwab

include HTTParty
debug_output $stdout
base_uri 'https://api.schwabapi.com/marketdata/v1'

end

Class Method Summary collapse

Class Method Details

.close_credit_callObject



257
258
# File 'app/models/tda/option.rb', line 257

def self.close_credit_call
end

.close_long_debit_call_spreadObject



259
260
# File 'app/models/tda/option.rb', line 259

def self.close_long_debit_call_spread
end

.close_short_debit_put_spreadObject



261
262
# File 'app/models/tda/option.rb', line 261

def self.close_short_debit_put_spread
end

.create_credit_call(outer:, inner:, q:, price:) ⇒ Object



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
# File 'app/models/tda/option.rb', line 272

def self.create_credit_call outer:, inner:, q:, price:
  query = {
    orderType: "NET_DEBIT",
    session: "NORMAL",
    price: price,
    duration: "DAY",
    orderStrategyType: "SINGLE",
    orderLegCollection: [
      {
        instruction: "BUY_TO_OPEN",
        quantity: q,
        instrument: {
          symbol: outer.symbol,
          assetType: "OPTION",
        },
      },
      {
        instruction: "SELL_TO_OPEN",
        quantity: q,
        instrument: {
          symbol: inner.symbol,
          assetType: "OPTION",
        },
      },
    ],
  }
  File.write('tmp/query.json', JSON.pretty_generate( query ))
  puts! query, 'query'

  return

  headers = {
    Authorize: "Bearer #{::TD_AMERITRADE[:access_token]}",
  }

  path = "/v1/accounts/#{::TD_AMERITRADE[:accountId]}/orders"
  puts! path, 'path'
  out = self.post path, { query: query, headers: headers }
  timestamp = DateTime.parse out.headers['date']
  out = out.parsed_response.deep_symbolize_keys
  puts! out, 'created credit call?'
end

.create_long_debit_call_spreadObject



314
315
# File 'app/models/tda/option.rb', line 314

def self.create_long_debit_call_spread
end

.create_short_debit_put_spreadObject



316
317
# File 'app/models/tda/option.rb', line 316

def self.create_short_debit_put_spread
end

.get_chains(params) ⇒ Object

Get entire chains for a ticker params: { ticker, force }

2024-08-09

Continue

2024-08-21

Continue : )



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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'app/models/tda/option.rb', line 26

def self.get_chains params
  filename = "./data/schwab/#{Time.now.to_date.to_s}-#{params[:ticker]}-chains.json"
  if !params[:force] && File.exists?(filename)
    return JSON.parse File.read filename

  else
    profile = Wco::Profile.find_by email: 'piousbox@gmail.com'
    query = { symbol: params[:ticker] } ## use 'GME' as symbol here even though a symbol is eg 'GME_021023P2.5'
    # puts! query, 'query'

    headers = {
      accept:        'application/json',
      Authorization: "Bearer #{profile[:schwab_access_token]}",
    }
    path = "/chains"
    out = self.get path, {
      headers: headers,
      query: query }
    timestamp = DateTime.parse out.headers['date']
    out = out.parsed_response
    puts! out, 'outs'

    outs = []
    %w| put call |.each do |contractType|
      _out = out["#{contractType}ExpDateMap"]
      _out.each do |date, vs| ## date="2023-02-10:5"
        vs.each do |strike, _v| ## strike="18.5"
          _v = _v[0] ## weird, keep
          # puts! _v, '_v'

          v = {
            putCall: _v['putCall'],
            symbol:  _v['symbol'],
            bid: _v['bid'],
            ask: _v['ask'],
            last: _v['last'],
            totalVolume: _v['totalVolume'],
            openInterest: _v['openInterest'],
            strikePrice: _v['strikePrice'],
            expirationDate: _v['expirationDate'],
          }
          v.each do |k, i|
            if i == 'NaN'
              v[k] = nil
            end
          end

          v[:timestamp] = timestamp
          v[:ticker] = params[:ticker]
          outs.push( v )
        end
      end
    end

    outs.each do |out|
      opi = ::Iro::Priceitem.create( out )
      if !opi.persisted?
        puts! opi.errors.full_messages, "Cannot create PriceItem"
      end
    end

    File.write filename, out.to_json
    return out
  end
end

.get_quote(params) ⇒ Object

2023-03-18 This is what I should be using to check if a position should be rolled. 2026-02-23 Used a lot but @deprecated, use get_quote_h



96
97
98
# File 'app/models/tda/option.rb', line 96

def self.get_quote params
  OpenStruct.new ::Tda::Option.get_quotes(params)[0]
end

.get_quotes(params) ⇒ Object

params: contractType, strike, expirationDate, ticker

params = { contractType: ‘PUT’, ticker: ‘GME’, expirationDate: ‘2026-02-20’ } outs = Tda::Option.get_quotes params

params = { contractType: ‘PUT’, ticker: ‘GME’, fromDate: ‘2026-02-20’, toDate: ‘2026-02-20’ }

2023-02-04 vp

Too specific, but I want the entire chain, every 1-min

2023-02-06 vp

Continue.



111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
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
# File 'app/models/tda/option.rb', line 111

def self.get_quotes params
  puts! params, 'core Tda::Option#get_quotes...'

  profile = Wco::Profile.find_by email: 'piousbox@gmail.com'
  opts = {}

  #
  # Validate input ???
  #
  validOpts = %i| contractType |
  validOpts.each do |s|
    if params[s]
      opts[s] = params[s]
    else
      raise Iro::InputError.new("Invalid input z1, missing '#{s}'.")
    end
  end
  if params[:expirationDate]
    opts[:fromDate] = opts[:toDate] = params[:expirationDate].to_s[0...10]
  elsif params[:fromDate] && params[:toDate]
    opts[:fromDate] = params[:fromDate].to_s[0...10]
    opts[:toDate]   = params[:toDate].to_s[0...10]
  else
    raise Iro::InputError.new("Invalid input z2, missing 'expirationDate' or both fromDate,toDate .")
  end
  if params[:ticker]
    opts[:symbol] = params[:ticker].upcase
  else
    raise Iro::InputError.new("Invalid input z3, missing 'ticker'.")
  end

  if params[:strike]
    opts[:strike] = params[:strike]
  end

  ## query = { contractType: "PUT", toDate: "2026-02-26", fromDate: "2026-02-26", symbol: "TSLA", strike: 395.0}
  query = { }.merge opts
  # puts! query, 'query'

  out = self.get( "/chains", {
    headers: {
      accept:        'application/json',
      Authorization: "Bearer #{profile[:schwab_access_token]}",
    },
    query: query,
  })
  # puts! out, '/chains --'
  timestamp = DateTime.parse out.headers['date']
  out = out.parsed_response.deep_symbolize_keys


  tmp_sym = "#{opts[:contractType].to_s.downcase}ExpDateMap".to_sym
  outs = []
  out = out[tmp_sym]
  out.each do |date, vs|
    vs.each do |strike, _v|
      v = _v[0]
      v = v.except( :lastSize, :optionDeliverablesList, :settlementType,
        :deliverableNote, :pennyPilot, :mini )
      v[:timestamp] = timestamp
      outs.push( v )
    end
  end

  # puts! outs, 'Tda::Option.get_quotes out'
  return outs
end

.get_quotes_h(params) ⇒ Object

2026-02-23 use this instead.



180
181
182
183
184
185
186
187
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
214
215
216
217
218
219
220
221
222
223
224
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
# File 'app/models/tda/option.rb', line 180

def self.get_quotes_h params
  puts! params, 'Tda::Option#get_quotes_h ...'

  profile = Wco::Profile.find_by email: 'piousbox@gmail.com'
  opts = {}

  #
  # Validate input ???
  #
  validOpts = %i| contractType |
  validOpts.each do |s|
    if params[s]
      opts[s] = params[s]
    else
      raise Iro::InputError.new("Invalid input z1, missing '#{s}'.")
    end
  end
  if params[:expirationDate]
    opts[:fromDate] = opts[:toDate] = params[:expirationDate].to_s[0...10]
  elsif params[:fromDate] && params[:toDate]
    opts[:fromDate] = params[:fromDate].to_s[0...10]
    opts[:toDate]   = params[:toDate].to_s[0...10]
  else
    raise Iro::InputError.new("Invalid input z2, missing 'expirationDate' or both fromDate,toDate .")
  end
  if params[:ticker]
    opts[:symbol] = params[:ticker].upcase
  else
    raise Iro::InputError.new("Invalid input z3, missing 'ticker'.")
  end

  if params[:strike]
    opts[:strike] = params[:strike]
  end

  ## query = { contractType: "PUT", toDate: "2026-02-26", fromDate: "2026-02-26", symbol: "TSLA", strike: 395.0}
  query = { }.merge opts
  puts! query, 'query'

  results = self.get( "/chains", {
    headers: {
      accept:        'application/json',
      Authorization: "Bearer #{profile[:schwab_access_token]}",
    },
    query: query,
  })
  # puts! results, '/chains --'
  timestamp = DateTime.parse results.headers['date']
  results = results.parsed_response.deep_symbolize_keys

  ## expdate, putcall, strike, price -and-
  ## expdate, putcall, strike, delta ...
  outs = {}
  [ 'PUT', 'CALL' ].each do |contract_type|
    tmp_sym     = "#{contract_type.to_s.downcase}ExpDateMap".to_sym
    if results[tmp_sym]
      tmp_results = results[tmp_sym]
      tmp_results.each do |date, vs|
        vs.each do |strike, _v|
          v = _v[0]
          v = v.except( :lastSize, :optionDeliverablesList, :settlementType,
            :deliverableNote, :pennyPilot, :mini )
          v[:timestamp] = timestamp
          v[:price] = ( v[:bid]+v[:ask] )/2

          outs[date[0...10]] ||= {}
          outs[date[0...10]][contract_type] ||= {}
          outs[date[0...10]][contract_type][v[:strikePrice]] = v
        end
      end
    end
  end

  # puts! outs, 'Tda::Option.get_quotes_h:'
  return outs
end

.get_tokenObject



264
265
266
267
268
269
270
# File 'app/models/tda/option.rb', line 264

def self.get_token
  opts = {
    grant_type: 'authorization_code',
    access_type: 'offline',
    code: ::TD_AMERITRADE[:code],
  }
end