-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtests_schwab_api.py
330 lines (275 loc) · 9.43 KB
/
tests_schwab_api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
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
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
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
178
179
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
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
# Adapted from the work of Alex Reed https://github.com/areed1192
#
# All the snippets in this file have been sucessfuly tested
# For those that require an account number,
# it must be Schwabs hash value for that account
#
rom schwab.option_chain import OptionChain
from pyrobot.robot import PyRobot
from pprint import pprint
from configparser import ConfigParser
# Grab configuration values.
config = ConfigParser()
config.read("./config/config.ini")
#
CLIENT_ID = config.get("main", "CLIENT_ID")
CLIENT_SECRET = config.get("main", "CLIENT_SECRET")
REDIRECT_URI = config.get("main", "REDIRECT_URI")
CREDENTIALS_PATH = config.get("main", "JSON_PATH")
# Uncomment once you have a hash value to use:
# ACCOUNT_NUMBER = config.get("main", "ACCOUNT_NUMBER")
# Create a new session, credentials path is required.
trading_robot = PyRobot(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
credentials_path=CREDENTIALS_PATH,
# trading_account=ACCOUNT_NUMBER,
)
"""##########################
Get Account Number(s) hash value(s)
Returns ALL accounts for the logged in user
Usage:
trading_robot = PyRobot(
client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
redirect_uri=REDIRECT_URI,
credentials_path=CREDENTIALS_PATH,
)
account_number_hash_values = list(trading_robot.session.get_account_number_hash_values())
pprint(account_number_hash_values)
print(f"First account number hash value: {account_number_hash_values[0]['hashValue']}")
"""
account_number_hash_values = list(
trading_robot.session.get_account_number_hash_values()
)
pprint(account_number_hash_values)
print(f"First account number hash value: {account_number_hash_values[0]['hashValue']}")
"""##########################
Get accounts
Without account number, returns all linked accounts, with or without positions
"""
# account = trading_robot.session.get_accounts(
# account="",
# fields="positions",
# )
# pprint(account)
"""##########################
Get account, specific account, with or without positions
"""
# fields = "positions"
# account = trading_robot.session.get_accounts(
# account=ACCOUNT_NUMBER,
# fields=fields,
# )
# pprint(account)
"""##########################
Get orders
Works with or without an account number
Valid ISO-8601 format for times is : yyyy-MM-dd'T'HH:mm:ss.SSSZ
if to and from entered times are not given, defaults are "now", and "now - 60 days"
"""
# status = "FILLED"
# order = trading_robot.session.get_orders_path(
# account=ACCOUNT_NUMBER,
# # from_entered_time=from_entered_time,
# # to_entered_time=to_entered_time,
# status=status,
# )
# pprint(order)
"""##########################
Get orders
Without an account number, returns orders for all linked acounts
Valid ISO-8601 format for times is : yyyy-MM-dd'T'HH:mm:ss.SSSZ
if to and from entered times are not given, defaults are "now", and "now - 60 days"
"""
# status = "FILLED"
# order = trading_robot.session.get_orders_path(
# #from_entered_time=from_entered_time,
# # to_entered_time=to_entered_time,
# status=status,
# )
# pprint(order)
"""##########################
Get specific order by order_id
"""
# order_id = 1000411469472
# order = trading_robot.session.get_order(
# account=ACCOUNT_NUMBER,
# order_id=order_id,
# )
# pprint(order)
"""##########################
Cancel order
"""
# order_id = 1000411469472
# order = trading_robot.session.cancel_order(account=ACCOUNT_NUMBER, order_id=order_id)
# pprint(order)
"""##########################
Get quote(s)
works with a single or multiple symbols
fields can be quote, fundamental, extended, reference, regular, or 'empty'
indicative: default = False, see Schwab docs
"""
# stock = ["uvix", "C"]
# fields = []
# # indicative = True # default false
# quotes = trading_robot.session.get_quotes(
# instruments=stock,
# fields=fields,
# # indicative=indicative
# )
# pprint(quotes)
"""##########################
Get Transactions
"""
# transaction_type = "TRADE" # required
# transactions = trading_robot.session.get_transactions(
# account=ACCOUNT_NUMBER,
# # start_date,
# # end_date="2024-03-27",
# transaction_type=transaction_type,
# # symbol="SQQQ",
# )
# pprint(transactions)
"""##########################
Get Transaction by id number
"""
# transaction_id = "80777088001"
# transactions = trading_robot.session.get_transactions(
# account=ACCOUNT_NUMBER, transaction_id=transaction_id
# )
# pprint(transactions)
"""##########################
Get Preferences
"""
# preferences = trading_robot.session.get_preferences()
# pprint(preferences)
"""##########################
Search Instruments
Available projection values : symbol-search, symbol-regex, desc-search, desc-regex, search, fundamental default is "symbol-search".
"""
# symbol = "F"
# projection = "symbol-search"
# instrument = trading_robot.session.search_instruments(
# symbol=symbol, projection=projection
# )
# pprint(instrument)
"""##########################
Get Instrument by cusip
"""
# cusip_id = "345370860"
# instrument_by_cusip = trading_robot.session.get_instruments(cusip_id)
# pprint(instrument_by_cusip)
"""##########################
Get Market Hours
"""
# markets = ["equity", "option"] # equity, option, bond, future, forex
# date = "2024-04-19" # Valid date range is from currentdate to 1 year from today. It will default to current day if not entered. Date format:YYYY-MM-DD
# hours = trading_robot.session.get_market_hours(markets=markets, date=date)
# pprint(hours)
"""##########################
Get Movers
"""
# symbol_id = "NYSE" # Available values : $DJI, $COMPX, $SPX, NYSE, NASDAQ, OTCBB, INDEX_ALL, EQUITY_ALL, OPTION_ALL, OPTION_PUT, OPTION_CALL
# sort = "PERCENT_CHANGE_UP" # Available values : VOLUME, TRADES, PERCENT_CHANGE_UP, PERCENT_CHANGE_DOWN
# frequency = 30 # Available values : 0, 1, 5, 10, 30, 60
# movers = trading_robot.session.get_movers(symbol_id, sort, frequency=frequency)
# pprint(movers)
"""##########################
Get price history
"""
# symbol = "F"
# period_type = "day"
# """ Available values : day, month, year, ytd"""
# period = None
# """ For period type day - valid values are 1, 2, 3, 4, 5, 10 - if not specified defaults to 10
# For period type month - valid values are 1, 2, 3, 6 - if not specified defaults to 1
# For period type year - valid values are 1, 2, 3, 5, 10, 15, 20 - if not specified defaults to 1
# For period type ytd valid value is 1 - if not specified defaults to 1
# """
# frequency_type = None
# """ # Available values : minute, daily, weekly, monthly
# If the periodType is day valid value is minute - if not specified defaults to minute
# If the periodType is month valid values are daily, weekly - if not specified defaults to weekly
# If the periodType is year valid values are daily, weekly, monthly - if not specified defaults to month
# If the periodType is ytd valid values are daily, weekly - if not specified defaults to weekly
# """
# frequency = None
# """ If the frequencyType is minute - valid values are 1, 5, 10, 15, 30 - If frequency is not specified, defaults to 1
# If the frequencyType is daily - valid value is 1 - If frequency is not specified, defaults to 1
# If the frequencyType is weekly - valid value is 1 - If frequency is not specified, defaults to 1
# If the frequencyType is monthly - valid value is 1 - If frequency is not specified, defaults to 1
# """
# start_date = None
# """ The start date, Time in milliseconds since the UNIX epoch eg 1451624400000
# If not specified, startDate will be (endDate - period) excluding weekends and holidays.
# """
# end_date = None
# """ The end date, Time in milliseconds since the UNIX epoch eg 1451624400000
# If not specified, the endDate will default to the market close of previous business day.
# """
# need_extended_hours_data = True
# need_previous_close = True
# history = trading_robot.session.get_price_history(
# symbol=symbol,
# period_type=period_type,
# period=period,
# frequency_type=frequency_type,
# frequency=frequency,
# start_date=start_date,
# end_date=end_date,
# need_extended_hours_data=need_extended_hours_data,
# need_previous_close=need_previous_close,
# )
# pprint(history)
"""##########################
Get option chain
"""
# # this works as class OptionChain object:
today = date.today()
chain = OptionChain(
symbol="SPY",
contract_type="ALL", ## "ALL",
strike_count=3, # 16,
include_quotes=True,
strategy="ANALYTICAL",
interval=None,
strike=None,
opt_range="ALL",
from_date=f"{today}", # "2024-04-30", # f"{today}",
to_date=f"{today}", # "2024-04-30", # f"{today}",
volatility=None,
underlying_price=None,
interest_rate=None,
days_to_expiration=None,
exp_month="ALL",
option_type="S",
entitlement=None, # "NP",
)
opt_chain = trading_robot.session.get_options_chain(chain)
pprint(opt_chain)
##
## or this works as 'raw' dict (around 1308 in client.py)
##
today = date.today()
symbol = "SPY"
opt_chain = {
"symbol": f"{symbol}",
"contractType": "ALL",
"optionType": "S",
"fromDate": f"{today}",
"toDate": f"{today}",
"strikeCount": 3,
"includeUnderlyingQuote": True,
# "includeQuotes": True,
"range": "ALL",
"strategy": "ANALYTICAL",
}
opt_chain = trading_robot.session.get_options_chain(opt_chain)
pprint(opt_chain)
"""##########################
Get expiration chain
"""
exp_chain = trading_robot.session.get_expiration_chain(symbol="TSLA")
pprint(exp_chain)