snaptrade-python-sdk 13.1.5__py3-none-any.whl → 13.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. snaptrade_client/__init__.py +3 -2
  2. snaptrade_client/api_client.py +1 -1
  3. snaptrade_client/auth.py +13 -0
  4. snaptrade_client/client.py +4 -0
  5. snaptrade_client/client.pyi +16 -0
  6. snaptrade_client/configuration.py +20 -2
  7. snaptrade_client/oauth_device.py +160 -0
  8. snaptrade_client/paths/accounts/get.py +5 -0
  9. snaptrade_client/paths/accounts/get.pyi +21 -0
  10. snaptrade_client/paths/accounts_account_id/get.py +5 -0
  11. snaptrade_client/paths/accounts_account_id/get.pyi +25 -0
  12. snaptrade_client/paths/accounts_account_id/put.py +5 -0
  13. snaptrade_client/paths/accounts_account_id/put.pyi +25 -0
  14. snaptrade_client/paths/accounts_account_id_activities/get.py +5 -0
  15. snaptrade_client/paths/accounts_account_id_activities/get.pyi +35 -0
  16. snaptrade_client/paths/accounts_account_id_balance_history/get.py +5 -0
  17. snaptrade_client/paths/accounts_account_id_balance_history/get.pyi +25 -0
  18. snaptrade_client/paths/accounts_account_id_balances/get.py +5 -0
  19. snaptrade_client/paths/accounts_account_id_balances/get.pyi +25 -0
  20. snaptrade_client/paths/accounts_account_id_details/get.py +5 -0
  21. snaptrade_client/paths/accounts_account_id_details/get.pyi +25 -0
  22. snaptrade_client/paths/accounts_account_id_holdings/get.py +5 -0
  23. snaptrade_client/paths/accounts_account_id_holdings/get.pyi +25 -0
  24. snaptrade_client/paths/accounts_account_id_orders/get.py +5 -0
  25. snaptrade_client/paths/accounts_account_id_orders/get.pyi +29 -0
  26. snaptrade_client/paths/accounts_account_id_orders_details/post.py +5 -0
  27. snaptrade_client/paths/accounts_account_id_orders_details/post.pyi +27 -0
  28. snaptrade_client/paths/accounts_account_id_orders_details_v2_brokerage_order_id/get.py +5 -0
  29. snaptrade_client/paths/accounts_account_id_orders_details_v2_brokerage_order_id/get.pyi +27 -0
  30. snaptrade_client/paths/accounts_account_id_orders_v2/get.py +5 -0
  31. snaptrade_client/paths/accounts_account_id_orders_v2/get.pyi +29 -0
  32. snaptrade_client/paths/accounts_account_id_positions_all/get.py +5 -0
  33. snaptrade_client/paths/accounts_account_id_positions_all/get.pyi +25 -0
  34. snaptrade_client/paths/accounts_account_id_quotes/get.py +5 -0
  35. snaptrade_client/paths/accounts_account_id_quotes/get.pyi +29 -0
  36. snaptrade_client/paths/accounts_account_id_recent_orders/get.py +5 -0
  37. snaptrade_client/paths/accounts_account_id_recent_orders/get.pyi +27 -0
  38. snaptrade_client/paths/accounts_account_id_recent_orders_v2/get.py +5 -0
  39. snaptrade_client/paths/accounts_account_id_recent_orders_v2/get.pyi +27 -0
  40. snaptrade_client/paths/accounts_account_id_symbols/post.py +5 -0
  41. snaptrade_client/paths/accounts_account_id_symbols/post.pyi +27 -0
  42. snaptrade_client/paths/accounts_account_id_trading_cancel/post.py +5 -0
  43. snaptrade_client/paths/accounts_account_id_trading_cancel/post.pyi +27 -0
  44. snaptrade_client/paths/accounts_account_id_trading_complex/post.py +5 -0
  45. snaptrade_client/paths/accounts_account_id_trading_complex/post.pyi +31 -0
  46. snaptrade_client/paths/accounts_account_id_trading_crypto/post.py +5 -0
  47. snaptrade_client/paths/accounts_account_id_trading_crypto/post.pyi +43 -0
  48. snaptrade_client/paths/accounts_account_id_trading_crypto_preview/post.py +5 -0
  49. snaptrade_client/paths/accounts_account_id_trading_crypto_preview/post.pyi +43 -0
  50. snaptrade_client/paths/accounts_account_id_trading_instruments_cryptocurrency_pairs/get.py +5 -0
  51. snaptrade_client/paths/accounts_account_id_trading_instruments_cryptocurrency_pairs/get.pyi +29 -0
  52. snaptrade_client/paths/accounts_account_id_trading_instruments_cryptocurrency_pairs_instrument_symbol_quote/get.py +5 -0
  53. snaptrade_client/paths/accounts_account_id_trading_instruments_cryptocurrency_pairs_instrument_symbol_quote/get.pyi +27 -0
  54. snaptrade_client/paths/accounts_account_id_trading_options/post.py +5 -0
  55. snaptrade_client/paths/accounts_account_id_trading_options/post.pyi +37 -0
  56. snaptrade_client/paths/accounts_account_id_trading_options_impact/post.py +5 -0
  57. snaptrade_client/paths/accounts_account_id_trading_options_impact/post.pyi +37 -0
  58. snaptrade_client/paths/accounts_account_id_trading_replace/post.py +5 -0
  59. snaptrade_client/paths/accounts_account_id_trading_replace/post.pyi +41 -0
  60. snaptrade_client/paths/accounts_account_id_trading_simple/post.py +5 -0
  61. snaptrade_client/paths/accounts_account_id_trading_simple/post.pyi +45 -0
  62. snaptrade_client/paths/accounts_all/get.py +5 -0
  63. snaptrade_client/paths/accounts_all/get.pyi +21 -0
  64. snaptrade_client/paths/authorizations/get.py +5 -0
  65. snaptrade_client/paths/authorizations/get.pyi +21 -0
  66. snaptrade_client/paths/authorizations_authorization_id/get.py +5 -0
  67. snaptrade_client/paths/authorizations_authorization_id/get.pyi +25 -0
  68. snaptrade_client/paths/authorizations_authorization_id_accounts/get.py +5 -0
  69. snaptrade_client/paths/authorizations_authorization_id_accounts/get.pyi +25 -0
  70. snaptrade_client/paths/authorizations_authorization_id_disable/post.py +5 -0
  71. snaptrade_client/paths/authorizations_authorization_id_disable/post.pyi +25 -0
  72. snaptrade_client/paths/authorizations_authorization_id_refresh/post.py +5 -0
  73. snaptrade_client/paths/authorizations_authorization_id_refresh/post.pyi +25 -0
  74. snaptrade_client/paths/authorizations_authorization_id_transactions_sync/post.py +5 -0
  75. snaptrade_client/paths/authorizations_authorization_id_transactions_sync/post.pyi +25 -0
  76. snaptrade_client/paths/brokerages/get.py +5 -0
  77. snaptrade_client/paths/brokerages/get.pyi +13 -0
  78. snaptrade_client/paths/brokerages_slug_instruments/get.py +5 -0
  79. snaptrade_client/paths/brokerages_slug_instruments/get.pyi +17 -0
  80. snaptrade_client/paths/connections_connection_id_accounts/get.py +5 -0
  81. snaptrade_client/paths/connections_connection_id_accounts/get.pyi +25 -0
  82. snaptrade_client/paths/exchanges/get.py +5 -0
  83. snaptrade_client/paths/exchanges/get.pyi +13 -0
  84. snaptrade_client/paths/snap_trade_login/post.py +5 -0
  85. snaptrade_client/paths/snap_trade_login/post.pyi +39 -0
  86. snaptrade_client/paths/snap_trade_partners/get.py +5 -0
  87. snaptrade_client/paths/snap_trade_partners/get.pyi +13 -0
  88. snaptrade_client/paths/symbols/post.py +5 -0
  89. snaptrade_client/paths/symbols/post.pyi +15 -0
  90. snaptrade_client/paths/symbols_query/get.py +5 -0
  91. snaptrade_client/paths/symbols_query/get.pyi +17 -0
  92. snaptrade_client/paths/trade_impact/post.py +5 -0
  93. snaptrade_client/paths/trade_impact/post.pyi +39 -0
  94. snaptrade_client/paths/trade_place/post.py +5 -0
  95. snaptrade_client/paths/trade_place/post.pyi +47 -0
  96. snaptrade_client/paths/trade_trade_id/post.py +5 -0
  97. snaptrade_client/paths/trade_trade_id/post.pyi +27 -0
  98. snaptrade_client/request_after_hook.py +2 -1
  99. {snaptrade_python_sdk-13.1.5.dist-info → snaptrade_python_sdk-13.2.0.dist-info}/METADATA +668 -10
  100. {snaptrade_python_sdk-13.1.5.dist-info → snaptrade_python_sdk-13.2.0.dist-info}/RECORD +102 -101
  101. {snaptrade_python_sdk-13.1.5.dist-info → snaptrade_python_sdk-13.2.0.dist-info}/LICENSE +0 -0
  102. {snaptrade_python_sdk-13.1.5.dist-info → snaptrade_python_sdk-13.2.0.dist-info}/WHEEL +0 -0
@@ -12,14 +12,15 @@
12
12
  Created by: https://snaptrade.com/
13
13
  """
14
14
 
15
- __version__ = "13.1.5"
15
+ __version__ = "13.2.0"
16
16
 
17
17
  # import ApiClient
18
18
  from snaptrade_client.api_client import ApiClient
19
19
 
20
20
  # import Configuration
21
21
  from snaptrade_client.configuration import Configuration
22
- from snaptrade_client.auth import SnapTradeAuth, AuthMode, CommercialApiKeyAuth, PersonalApiKeyAuth
22
+ from snaptrade_client.auth import SnapTradeAuth, AuthMode, CommercialApiKeyAuth, PersonalApiKeyAuth, OAuthAuth
23
+ from snaptrade_client.oauth_device import SnapTradeOAuthDevice, SnapTradeDeviceAuthorization, SnapTradeDeviceTokens, SnapTradeOAuthDeviceError
23
24
 
24
25
  # import exceptions
25
26
  from snaptrade_client.exceptions import OpenApiException
@@ -1175,7 +1175,7 @@ class ApiClient(typing.Generic[TAuth]):
1175
1175
  self.default_headers[header_name] = header_value
1176
1176
  self.cookie = cookie
1177
1177
  # Set default User-Agent.
1178
- self.user_agent = 'Konfig/13.1.5/python'
1178
+ self.user_agent = 'Konfig/13.2.0/python'
1179
1179
 
1180
1180
  def __enter__(self):
1181
1181
  return self
snaptrade_client/auth.py CHANGED
@@ -28,6 +28,10 @@ class PersonalApiKeyAuth(AuthMode):
28
28
  pass
29
29
 
30
30
 
31
+ class OAuthAuth(AuthMode):
32
+ pass
33
+
34
+
31
35
  class SnapTradeAuth:
32
36
  def __init__(self):
33
37
  raise RuntimeError("SnapTradeAuth should not be instantiated")
@@ -48,3 +52,12 @@ class SnapTradeAuth:
48
52
  client_id=client_id
49
53
  )
50
54
 
55
+ @staticmethod
56
+ def oauth(access_token: typing.Optional[str] = None) -> OAuthAuth:
57
+ if not isinstance(access_token, str) or not access_token.strip():
58
+ raise ValueError("access_token must be a nonempty string.")
59
+ return OAuthAuth(
60
+ "oauth",
61
+ access_token=access_token
62
+ )
63
+
@@ -38,6 +38,7 @@ class SnapTrade(ClientCustom, typing.Generic[TAuth]):
38
38
  auth: typing.Optional[TAuth],
39
39
  consumer_key: None = None,
40
40
  client_id: None = None,
41
+ access_token: None = None,
41
42
  **kwargs,
42
43
  ):
43
44
  """Create a client.
@@ -45,11 +46,14 @@ class SnapTrade(ClientCustom, typing.Generic[TAuth]):
45
46
  Authentication credentials must be provided through ``auth``.
46
47
  :param consumer_key: Unsupported. Pass this credential through ``auth``.
47
48
  :param client_id: Unsupported. Pass this credential through ``auth``.
49
+ :param access_token: Unsupported. Pass this credential through ``auth``.
48
50
  """
49
51
  if consumer_key is not None:
50
52
  raise TypeError("consumer_key must be passed through 'auth'")
51
53
  if client_id is not None:
52
54
  raise TypeError("client_id must be passed through 'auth'")
55
+ if access_token is not None:
56
+ raise TypeError("access_token must be passed through 'auth'")
53
57
  if len(kwargs) > 0 or configuration is None:
54
58
  configuration = Configuration(auth=auth, **kwargs)
55
59
  super().__init__(configuration)
@@ -13,6 +13,7 @@ import typing
13
13
  from snaptrade_client.auth import AuthMode
14
14
  from snaptrade_client.auth import CommercialApiKeyAuth
15
15
  from snaptrade_client.auth import PersonalApiKeyAuth
16
+ from snaptrade_client.auth import OAuthAuth
16
17
  from snaptrade_client.configuration import Configuration
17
18
  from snaptrade_client.apis.tags.account_information_api import AccountInformationApi
18
19
  from snaptrade_client.apis.tags.api_status_api import APIStatusApi
@@ -36,6 +37,7 @@ class SnapTrade(ClientCustom, typing.Generic[TAuth]):
36
37
  auth: CommercialApiKeyAuth,
37
38
  consumer_key: None = None,
38
39
  client_id: None = None,
40
+ access_token: None = None,
39
41
  **kwargs: typing.Any,
40
42
  ) -> None: ...
41
43
  @typing.overload
@@ -46,6 +48,18 @@ class SnapTrade(ClientCustom, typing.Generic[TAuth]):
46
48
  auth: PersonalApiKeyAuth,
47
49
  consumer_key: None = None,
48
50
  client_id: None = None,
51
+ access_token: None = None,
52
+ **kwargs: typing.Any,
53
+ ) -> None: ...
54
+ @typing.overload
55
+ def __init__(
56
+ self: "SnapTrade[OAuthAuth]",
57
+ configuration: None = None,
58
+ *,
59
+ auth: OAuthAuth,
60
+ consumer_key: None = None,
61
+ client_id: None = None,
62
+ access_token: None = None,
49
63
  **kwargs: typing.Any,
50
64
  ) -> None: ...
51
65
  @typing.overload
@@ -56,6 +70,7 @@ class SnapTrade(ClientCustom, typing.Generic[TAuth]):
56
70
  auth: None,
57
71
  consumer_key: None = None,
58
72
  client_id: None = None,
73
+ access_token: None = None,
59
74
  **kwargs: typing.Any,
60
75
  ) -> None: ...
61
76
  def __init__(
@@ -65,6 +80,7 @@ class SnapTrade(ClientCustom, typing.Generic[TAuth]):
65
80
  auth: typing.Optional[TAuth],
66
81
  consumer_key: None = None,
67
82
  client_id: None = None,
83
+ access_token: None = None,
68
84
  **kwargs: typing.Any,
69
85
  ) -> None:
70
86
  ...
@@ -114,6 +114,7 @@ conf = snaptrade_client.Configuration(
114
114
  def __init__(self, host=None,
115
115
  auth: typing.Optional[TAuth] = None,
116
116
  api_key=None, api_key_prefix=None,
117
+ access_token=None,
117
118
  username=None, password=None,
118
119
  discard_unknown_keys=False,
119
120
  client_id=None,
@@ -154,6 +155,9 @@ conf = snaptrade_client.Configuration(
154
155
  client_id = getattr(auth, "client_id")
155
156
  if getattr(auth, "consumer_key", None) is not None:
156
157
  self.consumer_key = getattr(auth, "consumer_key")
158
+ if self.auth_mode == "oauth":
159
+ if getattr(auth, "access_token", None) is not None:
160
+ access_token = getattr(auth, "access_token")
157
161
  self.server_variables = server_variables or {}
158
162
  self.server_operation_variables = server_operation_variables or {}
159
163
  """Default server variables
@@ -192,6 +196,9 @@ conf = snaptrade_client.Configuration(
192
196
  self.refresh_api_key_hook = None
193
197
  """function hook to refresh API key if expired
194
198
  """
199
+ self.access_token = access_token
200
+ """Token for HTTP Basic Bearer Authentication
201
+ """
195
202
  self.username = username
196
203
  """Username for HTTP basic authentication
197
204
  """
@@ -426,6 +433,13 @@ conf = snaptrade_client.Configuration(
426
433
  :return: The Auth Settings information dict.
427
434
  """
428
435
  auth = {}
436
+ if self.access_token is not None:
437
+ auth['OAuthBearer'] = {
438
+ 'type': 'bearer',
439
+ 'in': 'header',
440
+ 'key': 'Authorization',
441
+ 'value': 'Bearer ' + self.access_token
442
+ }
429
443
  if 'PartnerClientId' in self.api_key:
430
444
  auth['PartnerClientId'] = {
431
445
  'type': 'api_key',
@@ -508,7 +522,11 @@ conf = snaptrade_client.Configuration(
508
522
  return fallback_auth_settings
509
523
  if self.auth_mode is None:
510
524
  return fallback_auth_settings
511
- return auth_modes.get(self.auth_mode, [])
525
+ if self.auth_mode not in auth_modes:
526
+ raise ClientConfigurationError(
527
+ "This operation does not support the selected auth mode: %s" % self.auth_mode
528
+ )
529
+ return auth_modes[self.auth_mode]
512
530
 
513
531
  def to_debug_report(self):
514
532
  """Gets the essential information for debugging.
@@ -519,7 +537,7 @@ conf = snaptrade_client.Configuration(
519
537
  "OS: {env}\n"\
520
538
  "Python Version: {pyversion}\n"\
521
539
  "Version of the API: 1.0.0\n"\
522
- "SDK Package Version: 13.1.5".\
540
+ "SDK Package Version: 13.2.0".\
523
541
  format(env=sys.platform, pyversion=sys.version)
524
542
 
525
543
  def get_host_settings(self):
@@ -0,0 +1,160 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ SnapTrade
5
+
6
+ Connect brokerage accounts to your app for live positions and trading. ## Rate limiting Two limits apply to requests signed with your `clientId`. The stricter one wins, and exceeding either returns `429 Too Many Requests`. - **Customer-level** — 250 requests/minute by default, scoped to your `clientId` and applied across all endpoints. Reported in `X-RateLimit-Limit`, `X-RateLimit-Remaining` and `X-RateLimit-Reset`. - **Account-level** — 10 requests/minute per account, scoped to (`clientId`, `accountId`). All covered operations for one account draw on the same bucket — reading balances and reading positions share it — and enforcement does not depend on the HTTP method, so updating an account consumes the same bucket as reading it. Only enforced for Personal users, and only for integrations it has been rolled out to — it is not yet in force for every Personal integration. It also does not apply on every operation that documents a 429 below. Where it applies it is reported in `X-RateLimit-Account-Limit`, `X-RateLimit-Account-Remaining` and `X-RateLimit-Account-Reset`. Do not read the absence of those headers as proof the limit is off — some configurations omit the rate limit headers while still enforcing the limit, so header absence tells you nothing about your allowance. On a 429, `X-RateLimit-Remaining: 0` means you hit the customer-level limit and `X-RateLimit-Account-Remaining: 0` means the account-level one. Wait for the corresponding `*-Reset` value (seconds) before retrying, or fall back to exponential backoff with jitter. Not every 429 is explained by those headers. A separate per-authenticated-user limit, reported in no `X-RateLimit-*` header, covers OAuth-authenticated requests and signed requests in configurations where the customer-level limit is not in effect — on the operations that use the default throttles. A few operations override those and are governed by the customer-level limit alone. The two do not stack: a signed request governed by the customer-level limit above is not additionally subject to the per-user one. If a 429 arrives with no header at zero — or with no `X-RateLimit-*` headers at all — honour `Retry-After` and back off. Treat the remaining counts as a hint, not a guarantee that the next request will succeed. Because the customer-level limit applies everywhere, any signed request can return 429. **OAuth-authenticated requests are an exception.** They are not subject to the customer-level limit and do not receive `X-RateLimit-Limit`, `X-RateLimit-Remaining` or `X-RateLimit-Reset` — do not wait on those headers or design around a customer-level allowance on this path. The account-level limit still applies to them on the account-data endpoints above, reported in the `X-RateLimit-Account-*` headers. On operations using the default throttles the per-user limit above applies to them as well, so an OAuth request can be rejected while the account headers still show capacity; on the few operations that override those throttles, OAuth callers have no per-user ceiling at all. Drive retries from `Retry-After` and exponential backoff with jitter rather than from the headers. See https://docs.snaptrade.com/docs/ratelimiting.
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Contact: api@snaptrade.com
10
+ Created by: https://snaptrade.com/
11
+ """
12
+
13
+ from dataclasses import dataclass, field
14
+ import json
15
+ import math
16
+ import socket
17
+ import threading
18
+ import time
19
+ import typing
20
+ import urllib.error
21
+ import urllib.parse
22
+ import urllib.request
23
+
24
+
25
+ class SnapTradeOAuthDeviceError(RuntimeError):
26
+ """OAuth error code without response bodies or private device/token values."""
27
+
28
+ def __init__(self, error: str):
29
+ self.error = error
30
+ super().__init__(f"Device authorization failed: {error}")
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class SnapTradeDeviceAuthorization:
35
+ device_code: str = field(repr=False)
36
+ user_code: str
37
+ verification_uri: str
38
+ verification_uri_complete: typing.Optional[str]
39
+ # Process-local monotonic deadline in seconds; do not persist this object.
40
+ expires_at: float
41
+ interval: float
42
+
43
+
44
+ @dataclass(frozen=True)
45
+ class SnapTradeDeviceTokens:
46
+ access_token: str = field(repr=False)
47
+ refresh_token: typing.Optional[str] = field(repr=False)
48
+ token_type: typing.Optional[str]
49
+ expires_in: typing.Optional[int]
50
+ scope: typing.Optional[str]
51
+
52
+
53
+ def _positive_number(value: typing.Any) -> bool:
54
+ return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and value > 0
55
+
56
+
57
+ class SnapTradeOAuthDevice:
58
+ """Initial read-only device login for a pre-registered public device client.
59
+
60
+ The application displays the code/URL and owns token storage and refresh.
61
+ Cancellation interrupts polling waits; an in-flight HTTP call is bounded by
62
+ timeout and the authorization deadline.
63
+ """
64
+
65
+ def __init__(self, issuer: typing.Optional[str] = None, timeout: float = 30):
66
+ parsed = urllib.parse.urlsplit(issuer or "https://api.snaptrade.com")
67
+ if parsed.scheme not in ("https", "http") or not parsed.netloc:
68
+ raise ValueError("OAuth issuer must be an absolute HTTP(S) URL.")
69
+ if not _positive_number(timeout):
70
+ raise ValueError("timeout must be a positive finite number.")
71
+ self.issuer = urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, "", "", ""))
72
+ self.timeout = timeout
73
+
74
+ def start_device_authorization(self, *, client_id: str) -> SnapTradeDeviceAuthorization:
75
+ """Display user_code and verification_uri; keep device_code private."""
76
+ started_at = time.monotonic()
77
+ raw = self._post("device_authorization", {"client_id": client_id, "scope": "read"}, self.timeout)
78
+ interval = raw.get("interval", 5)
79
+ if not all(isinstance(raw.get(key), str) and raw[key] for key in ("device_code", "user_code", "verification_uri")) or not _positive_number(raw.get("expires_in")) or not _positive_number(interval):
80
+ raise SnapTradeOAuthDeviceError("invalid_response")
81
+ return SnapTradeDeviceAuthorization(
82
+ device_code=raw["device_code"], user_code=raw["user_code"],
83
+ verification_uri=raw["verification_uri"],
84
+ verification_uri_complete=raw.get("verification_uri_complete"),
85
+ expires_at=started_at + raw["expires_in"], interval=interval,
86
+ )
87
+
88
+ def wait_for_device_token(
89
+ self, *, client_id: str, authorization: SnapTradeDeviceAuthorization,
90
+ cancel: typing.Optional[threading.Event] = None,
91
+ ) -> SnapTradeDeviceTokens:
92
+ """Poll until approval; raise OAuthDeviceError on denial, expiry or cancellation."""
93
+ stop = cancel if cancel is not None else threading.Event()
94
+ interval = authorization.interval
95
+ if not _positive_number(interval) or not _positive_number(authorization.expires_at):
96
+ raise ValueError("Invalid device authorization deadline or interval.")
97
+ while True:
98
+ if stop.is_set():
99
+ raise SnapTradeOAuthDeviceError("cancelled")
100
+ remaining = authorization.expires_at - time.monotonic()
101
+ if remaining <= 0:
102
+ raise SnapTradeOAuthDeviceError("expired_token")
103
+ if stop.wait(min(interval, remaining)):
104
+ raise SnapTradeOAuthDeviceError("cancelled")
105
+ remaining = authorization.expires_at - time.monotonic()
106
+ if remaining <= 0:
107
+ raise SnapTradeOAuthDeviceError("expired_token")
108
+ try:
109
+ raw = self._post("token", {
110
+ "client_id": client_id, "device_code": authorization.device_code,
111
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
112
+ }, min(self.timeout, remaining))
113
+ except SnapTradeOAuthDeviceError as exc:
114
+ if exc.error == "authorization_pending":
115
+ continue
116
+ if exc.error == "slow_down":
117
+ interval += 5
118
+ continue
119
+ raise
120
+ except (TimeoutError, socket.timeout):
121
+ interval *= 2
122
+ continue
123
+ if stop.is_set():
124
+ raise SnapTradeOAuthDeviceError("cancelled")
125
+ if time.monotonic() >= authorization.expires_at:
126
+ raise SnapTradeOAuthDeviceError("expired_token")
127
+ if not isinstance(raw.get("access_token"), str) or not raw["access_token"]:
128
+ raise SnapTradeOAuthDeviceError("invalid_response")
129
+ return SnapTradeDeviceTokens(
130
+ access_token=raw["access_token"], refresh_token=raw.get("refresh_token"),
131
+ token_type=raw.get("token_type"), expires_in=raw.get("expires_in"), scope=raw.get("scope"),
132
+ )
133
+
134
+ def _post(self, endpoint: str, body: typing.Dict[str, str], timeout: float) -> typing.Dict[str, typing.Any]:
135
+ request = urllib.request.Request(
136
+ f"{self.issuer}/oauth/{endpoint}/", data=urllib.parse.urlencode(body).encode("utf-8"),
137
+ headers={"Content-Type": "application/x-www-form-urlencoded"}, method="POST",
138
+ )
139
+ try:
140
+ with urllib.request.urlopen(request, timeout=timeout) as response:
141
+ raw = json.load(response)
142
+ except urllib.error.HTTPError as exc:
143
+ try:
144
+ raw = json.load(exc)
145
+ except (ValueError, UnicodeError):
146
+ raise SnapTradeOAuthDeviceError("http_error") from None
147
+ error = raw.get("error") if isinstance(raw, dict) else None
148
+ allowed = {"authorization_pending", "slow_down", "access_denied", "expired_token", "invalid_client", "invalid_grant", "invalid_request", "unauthorized_client", "unsupported_grant_type", "invalid_scope"}
149
+ if not isinstance(error, str) or error not in allowed:
150
+ error = "http_error"
151
+ raise SnapTradeOAuthDeviceError(error) from None
152
+ except urllib.error.URLError as exc:
153
+ if isinstance(exc.reason, (TimeoutError, socket.timeout)):
154
+ raise TimeoutError("OAuth request timed out.") from None
155
+ raise SnapTradeOAuthDeviceError("network_error") from None
156
+ except (ValueError, UnicodeError):
157
+ raise SnapTradeOAuthDeviceError("invalid_response") from None
158
+ if not isinstance(raw, dict):
159
+ raise SnapTradeOAuthDeviceError("invalid_response")
160
+ return raw
@@ -53,11 +53,15 @@ _auth_modes = {
53
53
  "PersonalClientId",
54
54
  "PersonalTimestamp",
55
55
  ],
56
+ "oauth": [
57
+ "OAuthBearer",
58
+ ],
56
59
  }
57
60
  _operation_auth_context = {
58
61
  "auth_modes": [
59
62
  "commercialApiKey",
60
63
  "personalApiKey",
64
+ "oauth",
61
65
  ],
62
66
  "request_signing_by_auth_mode": {
63
67
  "commercialApiKey": {
@@ -77,6 +81,7 @@ _operation_auth_context = {
77
81
  },
78
82
  }
79
83
  _legacy_auth = [
84
+ 'OAuthBearer',
80
85
  'PartnerClientId',
81
86
  'PartnerSignature',
82
87
  'PartnerTimestamp',
@@ -16,6 +16,7 @@ from snaptrade_client import api_client
16
16
  from snaptrade_client.auth import AuthMode
17
17
  from snaptrade_client.auth import CommercialApiKeyAuth
18
18
  from snaptrade_client.auth import PersonalApiKeyAuth
19
+ from snaptrade_client.auth import OAuthAuth
19
20
 
20
21
  TAuth = typing.TypeVar("TAuth", bound=AuthMode)
21
22
 
@@ -45,6 +46,16 @@ class ListUserAccounts(BaseApi, typing.Generic[TAuth]):
45
46
  validate: bool = ...,
46
47
  timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
47
48
  ) -> typing.Any: ...
49
+ @typing.overload
50
+ def list_user_accounts(
51
+ self: "ListUserAccounts[OAuthAuth]",
52
+ user_id: typing.Optional[typing_extensions.Never] = None,
53
+ user_secret: typing.Optional[typing_extensions.Never] = None,
54
+ query_params: typing.Optional[dict] = ...,
55
+ header_params: typing.Optional[dict] = ...,
56
+ validate: bool = ...,
57
+ timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
58
+ ) -> typing.Any: ...
48
59
 
49
60
 
50
61
  class ApiForget(ListUserAccounts[TAuth]):
@@ -68,4 +79,14 @@ class ApiForget(ListUserAccounts[TAuth]):
68
79
  validate: bool = ...,
69
80
  timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
70
81
  ) -> typing.Any: ...
82
+ @typing.overload
83
+ def get(
84
+ self: "ApiForget[OAuthAuth]",
85
+ user_id: typing.Optional[typing_extensions.Never] = None,
86
+ user_secret: typing.Optional[typing_extensions.Never] = None,
87
+ query_params: typing.Optional[dict] = ...,
88
+ header_params: typing.Optional[dict] = ...,
89
+ validate: bool = ...,
90
+ timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
91
+ ) -> typing.Any: ...
71
92
 
@@ -81,11 +81,15 @@ _auth_modes = {
81
81
  "PersonalClientId",
82
82
  "PersonalTimestamp",
83
83
  ],
84
+ "oauth": [
85
+ "OAuthBearer",
86
+ ],
84
87
  }
85
88
  _operation_auth_context = {
86
89
  "auth_modes": [
87
90
  "commercialApiKey",
88
91
  "personalApiKey",
92
+ "oauth",
89
93
  ],
90
94
  "request_signing_by_auth_mode": {
91
95
  "commercialApiKey": {
@@ -105,6 +109,7 @@ _operation_auth_context = {
105
109
  },
106
110
  }
107
111
  _legacy_auth = [
112
+ 'OAuthBearer',
108
113
  'PartnerClientId',
109
114
  'PartnerSignature',
110
115
  'PartnerTimestamp',
@@ -16,6 +16,7 @@ from snaptrade_client import api_client
16
16
  from snaptrade_client.auth import AuthMode
17
17
  from snaptrade_client.auth import CommercialApiKeyAuth
18
18
  from snaptrade_client.auth import PersonalApiKeyAuth
19
+ from snaptrade_client.auth import OAuthAuth
19
20
 
20
21
  TAuth = typing.TypeVar("TAuth", bound=AuthMode)
21
22
 
@@ -49,6 +50,18 @@ class GetUserAccountDetails(BaseApi, typing.Generic[TAuth]):
49
50
  validate: bool = ...,
50
51
  timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
51
52
  ) -> typing.Any: ...
53
+ @typing.overload
54
+ def get_user_account_details(
55
+ self: "GetUserAccountDetails[OAuthAuth]",
56
+ account_id: str,
57
+ user_id: typing.Optional[typing_extensions.Never] = None,
58
+ user_secret: typing.Optional[typing_extensions.Never] = None,
59
+ query_params: typing.Optional[dict] = ...,
60
+ header_params: typing.Optional[dict] = ...,
61
+ path_params: typing.Optional[dict] = ...,
62
+ validate: bool = ...,
63
+ timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
64
+ ) -> typing.Any: ...
52
65
 
53
66
 
54
67
  class ApiForget(GetUserAccountDetails[TAuth]):
@@ -76,4 +89,16 @@ class ApiForget(GetUserAccountDetails[TAuth]):
76
89
  validate: bool = ...,
77
90
  timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
78
91
  ) -> typing.Any: ...
92
+ @typing.overload
93
+ def get(
94
+ self: "ApiForget[OAuthAuth]",
95
+ account_id: str,
96
+ user_id: typing.Optional[typing_extensions.Never] = None,
97
+ user_secret: typing.Optional[typing_extensions.Never] = None,
98
+ query_params: typing.Optional[dict] = ...,
99
+ header_params: typing.Optional[dict] = ...,
100
+ path_params: typing.Optional[dict] = ...,
101
+ validate: bool = ...,
102
+ timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
103
+ ) -> typing.Any: ...
79
104
 
@@ -81,11 +81,15 @@ _auth_modes = {
81
81
  "PersonalClientId",
82
82
  "PersonalTimestamp",
83
83
  ],
84
+ "oauth": [
85
+ "OAuthBearer",
86
+ ],
84
87
  }
85
88
  _operation_auth_context = {
86
89
  "auth_modes": [
87
90
  "commercialApiKey",
88
91
  "personalApiKey",
92
+ "oauth",
89
93
  ],
90
94
  "request_signing_by_auth_mode": {
91
95
  "commercialApiKey": {
@@ -105,6 +109,7 @@ _operation_auth_context = {
105
109
  },
106
110
  }
107
111
  _legacy_auth = [
112
+ 'OAuthBearer',
108
113
  'PartnerClientId',
109
114
  'PartnerSignature',
110
115
  'PartnerTimestamp',
@@ -16,6 +16,7 @@ from snaptrade_client import api_client
16
16
  from snaptrade_client.auth import AuthMode
17
17
  from snaptrade_client.auth import CommercialApiKeyAuth
18
18
  from snaptrade_client.auth import PersonalApiKeyAuth
19
+ from snaptrade_client.auth import OAuthAuth
19
20
 
20
21
  TAuth = typing.TypeVar("TAuth", bound=AuthMode)
21
22
 
@@ -49,6 +50,18 @@ class UpdateUserAccount(BaseApi, typing.Generic[TAuth]):
49
50
  validate: bool = ...,
50
51
  timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
51
52
  ) -> typing.Any: ...
53
+ @typing.overload
54
+ def update_user_account(
55
+ self: "UpdateUserAccount[OAuthAuth]",
56
+ account_id: str,
57
+ user_id: typing.Optional[typing_extensions.Never] = None,
58
+ user_secret: typing.Optional[typing_extensions.Never] = None,
59
+ query_params: typing.Optional[dict] = ...,
60
+ header_params: typing.Optional[dict] = ...,
61
+ path_params: typing.Optional[dict] = ...,
62
+ validate: bool = ...,
63
+ timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
64
+ ) -> typing.Any: ...
52
65
 
53
66
 
54
67
  class ApiForput(UpdateUserAccount[TAuth]):
@@ -76,4 +89,16 @@ class ApiForput(UpdateUserAccount[TAuth]):
76
89
  validate: bool = ...,
77
90
  timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
78
91
  ) -> typing.Any: ...
92
+ @typing.overload
93
+ def put(
94
+ self: "ApiForput[OAuthAuth]",
95
+ account_id: str,
96
+ user_id: typing.Optional[typing_extensions.Never] = None,
97
+ user_secret: typing.Optional[typing_extensions.Never] = None,
98
+ query_params: typing.Optional[dict] = ...,
99
+ header_params: typing.Optional[dict] = ...,
100
+ path_params: typing.Optional[dict] = ...,
101
+ validate: bool = ...,
102
+ timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
103
+ ) -> typing.Any: ...
79
104
 
@@ -159,11 +159,15 @@ _auth_modes = {
159
159
  "PersonalClientId",
160
160
  "PersonalTimestamp",
161
161
  ],
162
+ "oauth": [
163
+ "OAuthBearer",
164
+ ],
162
165
  }
163
166
  _operation_auth_context = {
164
167
  "auth_modes": [
165
168
  "commercialApiKey",
166
169
  "personalApiKey",
170
+ "oauth",
167
171
  ],
168
172
  "request_signing_by_auth_mode": {
169
173
  "commercialApiKey": {
@@ -183,6 +187,7 @@ _operation_auth_context = {
183
187
  },
184
188
  }
185
189
  _legacy_auth = [
190
+ 'OAuthBearer',
186
191
  'PartnerClientId',
187
192
  'PartnerSignature',
188
193
  'PartnerTimestamp',
@@ -16,6 +16,7 @@ from snaptrade_client import api_client
16
16
  from snaptrade_client.auth import AuthMode
17
17
  from snaptrade_client.auth import CommercialApiKeyAuth
18
18
  from snaptrade_client.auth import PersonalApiKeyAuth
19
+ from snaptrade_client.auth import OAuthAuth
19
20
 
20
21
  TAuth = typing.TypeVar("TAuth", bound=AuthMode)
21
22
 
@@ -59,6 +60,23 @@ class GetAccountActivities(BaseApi, typing.Generic[TAuth]):
59
60
  validate: bool = ...,
60
61
  timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
61
62
  ) -> typing.Any: ...
63
+ @typing.overload
64
+ def get_account_activities(
65
+ self: "GetAccountActivities[OAuthAuth]",
66
+ account_id: str,
67
+ start_date: typing.Optional[date] = None,
68
+ end_date: typing.Optional[date] = None,
69
+ offset: typing.Optional[int] = None,
70
+ limit: typing.Optional[int] = None,
71
+ type: typing.Optional[str] = None,
72
+ user_id: typing.Optional[typing_extensions.Never] = None,
73
+ user_secret: typing.Optional[typing_extensions.Never] = None,
74
+ query_params: typing.Optional[dict] = ...,
75
+ header_params: typing.Optional[dict] = ...,
76
+ path_params: typing.Optional[dict] = ...,
77
+ validate: bool = ...,
78
+ timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
79
+ ) -> typing.Any: ...
62
80
 
63
81
 
64
82
  class ApiForget(GetAccountActivities[TAuth]):
@@ -96,4 +114,21 @@ class ApiForget(GetAccountActivities[TAuth]):
96
114
  validate: bool = ...,
97
115
  timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
98
116
  ) -> typing.Any: ...
117
+ @typing.overload
118
+ def get(
119
+ self: "ApiForget[OAuthAuth]",
120
+ account_id: str,
121
+ start_date: typing.Optional[date] = None,
122
+ end_date: typing.Optional[date] = None,
123
+ offset: typing.Optional[int] = None,
124
+ limit: typing.Optional[int] = None,
125
+ type: typing.Optional[str] = None,
126
+ user_id: typing.Optional[typing_extensions.Never] = None,
127
+ user_secret: typing.Optional[typing_extensions.Never] = None,
128
+ query_params: typing.Optional[dict] = ...,
129
+ header_params: typing.Optional[dict] = ...,
130
+ path_params: typing.Optional[dict] = ...,
131
+ validate: bool = ...,
132
+ timeout: typing.Optional[typing.Union[float, typing.Tuple]] = None,
133
+ ) -> typing.Any: ...
99
134
 
@@ -81,11 +81,15 @@ _auth_modes = {
81
81
  "PersonalClientId",
82
82
  "PersonalTimestamp",
83
83
  ],
84
+ "oauth": [
85
+ "OAuthBearer",
86
+ ],
84
87
  }
85
88
  _operation_auth_context = {
86
89
  "auth_modes": [
87
90
  "commercialApiKey",
88
91
  "personalApiKey",
92
+ "oauth",
89
93
  ],
90
94
  "request_signing_by_auth_mode": {
91
95
  "commercialApiKey": {
@@ -105,6 +109,7 @@ _operation_auth_context = {
105
109
  },
106
110
  }
107
111
  _legacy_auth = [
112
+ 'OAuthBearer',
108
113
  'PartnerClientId',
109
114
  'PartnerSignature',
110
115
  'PartnerTimestamp',