-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathwealthsimple_v2.py
More file actions
2681 lines (2346 loc) · 90.4 KB
/
wealthsimple_v2.py
File metadata and controls
2681 lines (2346 loc) · 90.4 KB
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
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
396
397
398
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
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
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
610
611
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
640
641
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
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
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Wealthsimple API v2 - Unofficial GraphQL-based API Client
This module provides an unofficial Python client for the Wealthsimple platform
using their GraphQL API. It supports authentication, security search, trading,
options trading, account management, and real-time WebSocket subscriptions.
Based on network traffic analysis from the Wealthsimple web application.
Features:
- Secure token storage using keyring (OS credential storage)
- Automatic token refresh and persistence
- Real-time WebSocket subscriptions
- Full trading support (stocks and options)
- Comprehensive account management
Dependencies:
- requests (required)
- keyring (optional but recommended - for secure token storage)
- websockets (optional - for real-time subscriptions)
Usage:
from wealthsimple_v2 import WealthsimpleV2, OrderStatus, OrderType
# Authenticate (tokens automatically saved to keyring)
ws = WealthsimpleV2(username='your@email.com', password='yourpassword')
# Later sessions - tokens automatically loaded from keyring
ws = WealthsimpleV2() # No credentials needed!
# Search for a security
results = ws.search_securities('AAPL')
# Get security details
security = ws.get_security(security_id)
# Place an order
order = ws.create_order(
account_id='tfsa-xxxxx',
security_id='sec-s-xxxxx',
quantity=1,
limit_price=150.00,
order_type=OrderType.BUY_QUANTITY
)
# Get pending orders
pending = ws.get_pending_orders(account_ids=['tfsa-xxxxx'])
# Cancel an order
ws.cancel_order(order['externalCanonicalId'])
# Filter activities by status
activities = ws.get_activities(
statuses=[OrderStatus.FILLED],
types=[OrderType.DIY_BUY]
)
# Logout and clear all tokens
ws.logout()
# Real-time subscriptions (requires 'websockets' package)
import asyncio
async def stream_quotes():
async with ws.subscribe() as sub:
async for msg in sub.stream_quotes(['sec-s-xxxxx']):
quote = msg['payload']['data']['securityQuoteUpdates']['quoteV2']
print(f"Price: {quote['price']}")
asyncio.run(stream_quotes())
"""
import requests
import json
import os
import time
import base64
import asyncio
import uuid
from typing import Dict, List, Optional, Any, Callable, AsyncIterator
from datetime import datetime, date
# Optional WebSocket support for subscriptions
try:
import websockets
from websockets.client import WebSocketClientProtocol
WEBSOCKETS_AVAILABLE = True
except ImportError:
WEBSOCKETS_AVAILABLE = False
websockets = None
WebSocketClientProtocol = None
# Optional keyring support for secure token storage
try:
import keyring
KEYRING_AVAILABLE = True
except ImportError:
KEYRING_AVAILABLE = False
keyring = None
# ==================== Constants & Enums ====================
class OrderStatus:
"""Order status constants for filtering activities."""
PENDING = 'PENDING' # Order submitted but not yet executed
FILLED = 'FILLED' # Order completed/executed
CANCELLED = 'CANCELLED' # Order cancelled
SUBMITTED = 'SUBMITTED' # Order submitted to exchange
REJECTED = 'REJECTED' # Order rejected
EXPIRED = 'EXPIRED' # Order expired
COMPLETED = 'COMPLETED' # Order completed (alternative to FILLED)
class OrderType:
"""Order type constants."""
BUY_QUANTITY = 'BUY_QUANTITY'
SELL_QUANTITY = 'SELL_QUANTITY'
# Activity types for filtering
DIY_BUY = 'DIY_BUY'
DIY_SELL = 'DIY_SELL'
OPTIONS_BUY = 'OPTIONS_BUY'
OPTIONS_SELL = 'OPTIONS_SELL'
OPTIONS_MULTILEG = 'OPTIONS_MULTILEG'
MANAGED_BUY = 'MANAGED_BUY'
MANAGED_SELL = 'MANAGED_SELL'
CRYPTO_BUY = 'CRYPTO_BUY'
CRYPTO_SELL = 'CRYPTO_SELL'
DIVIDEND = 'DIVIDEND'
class OrderSubType:
"""Order sub-type constants."""
LIMIT_ORDER = 'LIMIT_ORDER'
MARKET_ORDER = 'MARKET_ORDER'
STOP_ORDER = 'STOP_ORDER'
STOP_LIMIT_ORDER = 'STOP_LIMIT_ORDER'
FRACTIONAL_ORDER = 'FRACTIONAL_ORDER'
DIVIDEND_REINVESTMENT = 'DIVIDEND_REINVESTMENT'
class ExecutionType:
"""Execution type constants for order creation."""
MARKET = 'MARKET'
LIMIT = 'LIMIT'
STOP = 'STOP'
STOP_LIMIT = 'STOP_LIMIT'
class TimeInForce:
"""Time in force constants."""
DAY = 'DAY' # Day order
GTC = 'GTC' # Good till cancelled
GTD = 'GTD' # Good till date
IOC = 'IOC' # Immediate or cancel
FOK = 'FOK' # Fill or kill
class WealthsimpleV2:
"""
Unofficial Wealthsimple API v2 Client
This client uses the GraphQL API endpoint at https://my.wealthsimple.com/graphql
with OAuth v2 authentication.
Tokens are securely stored using the keyring library (if available), which uses
the operating system's credential storage (Keychain on macOS, Credential Locker
on Windows, Secret Service on Linux).
"""
# Keyring service name for token storage
KEYRING_SERVICE = "wealthsimple-python"
def __init__(self, username: Optional[str] = None, password: Optional[str] = None,
otp: Optional[str] = None, client_id: Optional[str] = None,
access_token: Optional[str] = None, refresh_token: Optional[str] = None):
"""
Initialize the Wealthsimple API client.
Args:
username: Your Wealthsimple email/username
password: Your Wealthsimple password
otp: Optional OTP/2FA token if 2FA is enabled
client_id: OAuth client ID (defaults to web client ID)
access_token: Optional - provide an existing access token to skip authentication
refresh_token: Optional - provide an existing refresh token
"""
self.api_url = "https://my.wealthsimple.com/graphql"
self.auth_url = "https://api.production.wealthsimple.com/v1/oauth/v2/token"
self.client_id = client_id or "4da53ac2b03225bed1550eba8e4611e086c7b905a3855e6ed12ea08c246758fa"
self.access_token = access_token
self.refresh_token = refresh_token
self.token_expiry = None
self.identity_id = None
self.profiles = None
# If credentials provided, authenticate
if username and password:
self.authenticate(username, password, otp)
elif not access_token:
# Try to load tokens from keyring first (most secure)
if self._load_tokens_from_keyring():
# Successfully loaded tokens from keyring
self._fetch_identity_id_from_token()
else:
# Fallback: Try to get tokens from environment variables
env_access_token = os.getenv('WS_ACCESS_TOKEN')
env_refresh_token = os.getenv('WS_REFRESH_TOKEN')
if env_access_token and env_refresh_token:
# Use existing tokens from environment
self.access_token = env_access_token
self.refresh_token = env_refresh_token
# Extract identity ID from token
self._fetch_identity_id_from_token()
else:
# Try to authenticate with credentials from environment variables
username = os.getenv('WS_USERNAME')
password = os.getenv('WS_PASSWORD')
otp = os.getenv('WS_OTP')
if username and password:
self.authenticate(username, password, otp)
def _save_tokens_to_keyring(self, username: Optional[str] = None) -> bool:
"""
Save tokens to keyring (secure credential storage).
Args:
username: Optional username to use as keyring username (defaults to 'default')
Returns:
True if tokens were successfully saved, False otherwise
"""
if not KEYRING_AVAILABLE:
return False
keyring_username = username or os.getenv('WS_USERNAME') or 'default'
try:
saved_any = False
if self.access_token:
keyring.set_password(self.KEYRING_SERVICE, f"{keyring_username}_access_token", self.access_token)
saved_any = True
if self.refresh_token:
keyring.set_password(self.KEYRING_SERVICE, f"{keyring_username}_refresh_token", self.refresh_token)
saved_any = True
if self.token_expiry:
keyring.set_password(self.KEYRING_SERVICE, f"{keyring_username}_token_expiry", str(self.token_expiry))
saved_any = True
return saved_any
except Exception as e:
print(f"Failed to save to keyring: {e}")
# If keyring fails, silently continue (tokens won't be persisted)
# In debug mode, you could log this: print(f"Failed to save to keyring: {e}")
return False
def _load_tokens_from_keyring(self, username: Optional[str] = None) -> bool:
"""
Load tokens from keyring (secure credential storage).
Args:
username: Optional username to use as keyring username (defaults to 'default')
Returns:
True if tokens were successfully loaded, False otherwise
"""
if not KEYRING_AVAILABLE:
return False
keyring_username = username or os.getenv('WS_USERNAME') or 'default'
try:
access_token = keyring.get_password(self.KEYRING_SERVICE, f"{keyring_username}_access_token")
refresh_token = keyring.get_password(self.KEYRING_SERVICE, f"{keyring_username}_refresh_token")
token_expiry_str = keyring.get_password(self.KEYRING_SERVICE, f"{keyring_username}_token_expiry")
if access_token and refresh_token:
self.access_token = access_token
self.refresh_token = refresh_token
if token_expiry_str:
try:
self.token_expiry = float(token_expiry_str)
except ValueError:
self.token_expiry = None
return True
except Exception:
pass
return False
def _delete_tokens_from_keyring(self, username: Optional[str] = None) -> None:
"""
Delete tokens from keyring.
Args:
username: Optional username to use as keyring username (defaults to 'default')
"""
if not KEYRING_AVAILABLE:
return
keyring_username = username or os.getenv('WS_USERNAME') or 'default'
try:
keyring.delete_password(self.KEYRING_SERVICE, f"{keyring_username}_access_token")
except Exception:
pass
try:
keyring.delete_password(self.KEYRING_SERVICE, f"{keyring_username}_refresh_token")
except Exception:
pass
try:
keyring.delete_password(self.KEYRING_SERVICE, f"{keyring_username}_token_expiry")
except Exception:
pass
def authenticate(self, username: str, password: str, otp: Optional[str] = None) -> Dict:
"""
Authenticate with Wealthsimple using OAuth v2.
Args:
username: Your Wealthsimple email/username
password: Your Wealthsimple password
otp: Optional OTP/2FA token
Returns:
Dict containing authentication response
Raises:
Exception if authentication fails
"""
payload = {
"grant_type": "password",
"username": username,
"password": password,
"skip_provision": True,
"scope": "invest.read invest.write trade.read trade.write tax.read tax.write",
"client_id": self.client_id
}
headers = {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15"
}
if otp:
headers["x-wealthsimple-otp"] = otp
response = requests.post(self.auth_url, json=payload, headers=headers)
if response.status_code == 200:
data = response.json()
self.access_token = data.get('access_token')
self.refresh_token = data.get('refresh_token')
expires_in = data.get('expires_in', 1800)
self.token_expiry = time.time() + expires_in
# Extract identity and profile information FIRST (before saving tokens)
self.identity_id = data.get('identity_canonical_id')
self.profiles = data.get('profiles', {})
# If identity_id not in response, try to extract from JWT token
if not self.identity_id and self.access_token:
self._fetch_identity_id_from_token()
# Save tokens to keyring (secure storage)
# Note: We save after extracting identity_id so we have all the info
self._save_tokens_to_keyring('default')
print(f"Saved tokens to keyring")
# Also save to environment variables as fallback
if self.access_token:
os.environ['WS_ACCESS_TOKEN'] = self.access_token
if self.refresh_token:
os.environ['WS_REFRESH_TOKEN'] = self.refresh_token
return data
else:
raise Exception(f"Authentication failed: {response.status_code} - {response.text}")
def _fetch_identity_id_from_token(self):
"""
Extract the identity ID from the JWT access token.
This is a fallback method if the OAuth response doesn't include identity_canonical_id.
"""
try:
if self.access_token:
# JWT tokens are base64 encoded, format: header.payload.signature
parts = self.access_token.split('.')
if len(parts) >= 2:
# Add padding if needed for base64 decoding
payload = parts[1]
payload += '=' * (4 - len(payload) % 4)
try:
decoded = base64.urlsafe_b64decode(payload)
token_data = json.loads(decoded)
# Look for identity-related fields in the JWT payload
# Common fields: sub, identity_canonical_id, identity_id, user_id
for key in ['identity_canonical_id', 'identity_id', 'sub', 'user_id']:
if key in token_data:
value = token_data[key]
if isinstance(value, str) and value.startswith('identity-'):
self.identity_id = value
return
except (ValueError, KeyError):
# Failed to decode JWT, identity_id will remain None
pass
except Exception:
# Failed to extract identity_id from token, will remain None
pass
def logout(self) -> None:
"""
Logout and clear all stored tokens from keyring and environment variables.
This will delete tokens from:
- Keyring (secure OS credential storage)
- Environment variables
- Instance variables
"""
# Clear tokens from keyring
self._delete_tokens_from_keyring()
# Clear tokens from environment variables
if 'WS_ACCESS_TOKEN' in os.environ:
del os.environ['WS_ACCESS_TOKEN']
if 'WS_REFRESH_TOKEN' in os.environ:
del os.environ['WS_REFRESH_TOKEN']
# Clear instance variables
self.access_token = None
self.refresh_token = None
self.token_expiry = None
self.identity_id = None
self.profiles = None
def refresh_access_token(self) -> bool:
"""
Refresh the access token using the refresh token.
Returns:
True if successful, False otherwise
"""
if not self.refresh_token:
return False
payload = {
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
"client_id": self.client_id
}
headers = {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0"
}
try:
response = requests.post(self.auth_url, json=payload, headers=headers)
if response.status_code == 200:
data = response.json()
self.access_token = data.get('access_token')
self.refresh_token = data.get('refresh_token')
expires_in = data.get('expires_in', 1800)
self.token_expiry = time.time() + expires_in
# Save updated tokens to keyring (secure storage)
self._save_tokens_to_keyring()
# Also update tokens in environment variables as fallback
if self.access_token:
os.environ['WS_ACCESS_TOKEN'] = self.access_token
if self.refresh_token:
os.environ['WS_REFRESH_TOKEN'] = self.refresh_token
return True
except:
pass
return False
def _ensure_authenticated(self):
"""Ensure we have a valid access token, refresh if needed."""
if not self.access_token:
raise Exception("Not authenticated. Please call authenticate() first.")
# Check if token is about to expire (within 5 minutes)
if self.token_expiry and (time.time() + 300) > self.token_expiry:
if not self.refresh_access_token():
raise Exception("Token expired and refresh failed. Please re-authenticate.")
def _get_headers(self) -> Dict[str, str]:
"""Get headers for GraphQL requests."""
self._ensure_authenticated()
return {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.access_token}",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15",
"x-ws-api-version": "12",
"x-platform-os": "web",
"x-ws-locale": "en-CA",
"x-ws-profile": "trade"
}
def graphql_query(self, operation_name: str, query: str, variables: Optional[Dict] = None) -> Dict:
"""
Execute a GraphQL query or mutation.
Args:
operation_name: The operation name
query: The GraphQL query string
variables: Optional variables for the query
Returns:
Response data dictionary
Raises:
Exception if the request fails
"""
payload = {
"operationName": operation_name,
"query": query,
"variables": variables or {}
}
response = requests.post(self.api_url, json=payload, headers=self._get_headers())
if response.status_code == 200:
data = response.json()
if 'errors' in data:
raise Exception(f"GraphQL errors: {data['errors']}")
return data
else:
raise Exception(f"Request failed: {response.status_code} - {response.text}")
# ==================== Security Search & Info ====================
def search_securities(self, query: str, security_group_ids: Optional[List[str]] = None) -> List[Dict]:
"""
Search for securities by ticker symbol or name.
Args:
query: Search query (ticker symbol or company name)
security_group_ids: Optional list of security group IDs to filter by
Returns:
List of security results
"""
gql_query = """
query FetchSecuritySearchResult($query: String!, $securityGroupIds: [String!]) {
securitySearch(input: {query: $query, securityGroupIds: $securityGroupIds}) {
results {
id
buyable
sellable
optionsEligible
securityType
allowedOrderSubtypes
status
stock {
symbol
name
primaryExchange
}
features
logoUrl
quoteV2(currency: null) {
securityId
currency
price
... on EquityQuote {
marketStatus
close
high
low
open
volume: vol
}
}
}
}
}
"""
variables = {
"query": query,
"securityGroupIds": security_group_ids
}
result = self.graphql_query("FetchSecuritySearchResult", gql_query, variables)
return result.get('data', {}).get('securitySearch', {}).get('results', [])
def get_security(self, security_id: str, currency: Optional[str] = None) -> Dict:
"""
Get detailed information about a security.
Args:
security_id: The security ID (e.g., 'sec-s-xxxxx')
currency: Optional currency for fundamentals
Returns:
Security details dictionary
"""
gql_query = """
query FetchSecurity($securityId: ID!, $currency: Currency) {
security(id: $securityId) {
id
active
activeDate
allowedOrderSubtypes
buyable
currency
depositEligible
features
inactiveDate
isVolatile
logoUrl
securityType
sellable
settleable
status
wsTradeEligible
wsTradeIneligibilityReason
optionsEligible
equityTradingSessionType
stock {
description
dividendFrequency
name
primaryExchange
primaryMic
symbol
}
fundamentals(currency: $currency) {
avgVolume
beta
marketCap
peRatio
eps
yield
high52Week
low52Week
description
}
quoteV2(currency: $currency) {
securityId
currency
price
ask
bid
... on EquityQuote {
marketStatus
close
high
low
open
volume: vol
askSize
bidSize
last
lastSize
mid
}
}
optionDetails {
expiryDate
maturity
multiplier
optionType
osiSymbol
strikePrice
underlyingSecurity {
id
stock {
name
symbol
primaryExchange
}
}
}
}
}
"""
variables = {
"securityId": security_id,
"currency": currency
}
result = self.graphql_query("FetchSecurity", gql_query, variables)
return result.get('data', {}).get('security', {})
def get_security_quote(self, security_id: str, currency: Optional[str] = None) -> Dict:
"""
Get real-time quote for a security.
Args:
security_id: The security ID
currency: Optional currency
Returns:
Quote dictionary
"""
gql_query = """
query FetchSecurityQuoteV2($id: ID!, $currency: Currency = null) {
security(id: $id) {
id
quoteV2(currency: $currency) {
securityId
ask
bid
currency
price
sessionPrice
quotedAsOf
previousBaseline
... on EquityQuote {
marketStatus
askSize
bidSize
close
high
last
lastSize
low
open
mid
volume: vol
referenceClose
}
... on OptionQuote {
marketStatus
askSize
bidSize
close
high
last
lastSize
low
open
mid
volume: vol
breakEven
inTheMoney
liquidityStatus
openInterest
underlyingSpot
}
}
}
}
"""
variables = {
"id": security_id,
"currency": currency
}
result = self.graphql_query("FetchSecurityQuoteV2", gql_query, variables)
return result.get('data', {}).get('security', {}).get('quoteV2', {})
def get_ticker_id(self, ticker: str, exchange: Optional[str] = None) -> Optional[str]:
"""
Get security ID by ticker symbol.
Args:
ticker: Stock ticker symbol (e.g., 'AAPL')
exchange: Optional exchange to filter by (e.g., 'NASDAQ', 'TSX')
Returns:
Security ID string or None if not found
"""
results = self.search_securities(ticker)
for result in results:
stock = result.get('stock', {})
if stock.get('symbol') == ticker:
if exchange is None or stock.get('primaryExchange') == exchange:
return result.get('id')
return None
# ==================== Options Trading ====================
def get_option_chain(self, security_id: str, expiry_date: str, option_type: str = 'CALL',
include_greeks: bool = True, real_time_quote: bool = True,
first: Optional[int] = None, cursor: Optional[str] = None) -> List[Dict]:
"""
Get option chain for a security.
Args:
security_id: Underlying security ID
expiry_date: Expiry date in YYYY-MM-DD format
option_type: 'CALL' or 'PUT'
include_greeks: Include option greeks
real_time_quote: Include real-time quotes
first: Optional limit on number of results
cursor: Optional cursor for pagination
Returns:
List of option contracts
"""
gql_query = """
query FetchOptionChain($id: ID!, $expiryDate: Date!, $optionType: OptionType!, $realTimeQuote: Boolean, $cursor: String, $first: Int, $includeGreeks: Boolean!) {
security(id: $id) {
id
optionChain(
expiryDate: $expiryDate
optionType: $optionType
realTimeQuote: $realTimeQuote
first: $first
after: $cursor
) {
edges {
node {
...OptionChainSecurity
__typename
}
__typename
}
pageInfo {
hasNextPage
endCursor
__typename
}
__typename
}
__typename
}
}
fragment OptionChainSecurity on Security {
id
...OptionDetailsSummary
quoteV2(currency: null) {
...SecurityQuoteV2
__typename
}
__typename
}
fragment OptionDetailsSummary on Security {
optionDetails {
strikePrice
optionType
greekSymbols @include(if: $includeGreeks) {
...OptionGreekSymbols
__typename
}
__typename
}
__typename
}
fragment OptionGreekSymbols on OptionGreekSymbols {
id
rho
vega
delta
theta
gamma
impliedVolatility
calculationTime
__typename
}
fragment StreamedSecurityQuoteV2 on UnifiedQuote {
__typename
securityId
ask
bid
currency
price
sessionPrice
quotedAsOf
... on EquityQuote {
marketStatus
askSize
bidSize
close
high
last
lastSize
low
open
mid
volume: vol
referenceClose
__typename
}
... on OptionQuote {
marketStatus
askSize
bidSize
close
high
last
lastSize
low
open
mid
volume: vol
breakEven
inTheMoney
liquidityStatus
openInterest
underlyingSpot
__typename
}
}
fragment SecurityQuoteV2 on UnifiedQuote {
...StreamedSecurityQuoteV2
previousBaseline
__typename
}
"""
variables = {
"id": security_id,
"expiryDate": expiry_date,
"optionType": option_type,
"realTimeQuote": real_time_quote,
"cursor": cursor,
"first": first,
"includeGreeks": include_greeks
}
result = self.graphql_query("FetchOptionChain", gql_query, variables)
chain = result.get('data', {}).get('security', {}).get('optionChain', {})
edges = chain.get('edges', [])
return [edge.get('node', {}) for edge in edges]
def get_option_expiry_dates(self, security_id: str, min_date: Optional[str] = None,
max_date: Optional[str] = None) -> List[str]:
"""
Get available option expiry dates for a security.
Args:
security_id: Underlying security ID
min_date: Minimum date in YYYY-MM-DD format
max_date: Maximum date in YYYY-MM-DD format
Returns:
List of expiry dates
"""
if not min_date:
min_date = datetime.now().strftime('%Y-%m-%d')
if not max_date:
# Default to 3 years from now
from datetime import timedelta
max_date = (datetime.now() + timedelta(days=1095)).strftime('%Y-%m-%d')
gql_query = """
query FetchOptionExpirationDates($securityId: ID!, $minDate: Date!, $maxDate: Date!) {
security(id: $securityId) {
id
optionExpirationDates(minDate: $minDate, maxDate: $maxDate) {
...OptionExpirationDates
__typename
}
__typename
}
}
fragment OptionExpirationDates on OptionExpirationDates {
expirationDates
__typename
}
"""
variables = {
"securityId": security_id,
"minDate": min_date,
"maxDate": max_date
}
result = self.graphql_query("FetchOptionExpirationDates", gql_query, variables)
option_dates = result.get('data', {}).get('security', {}).get('optionExpirationDates', {})
return option_dates.get('expirationDates', [])
def get_option_transaction_fees(self, side: str, premium: float, quantity: int,
multiplier: int = 100, currency: str = 'CAD') -> Dict:
"""
Calculate option transaction fees.
Args:
side: 'BUY_QUANTITY' or 'SELL_QUANTITY'
premium: Option premium price
quantity: Number of contracts
multiplier: Contract multiplier (usually 100)
currency: Currency