webull-openapi-python-sdk 3.0.3__py3-none-any.whl → 3.1.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.
- samples/__init__.py +1 -1
- samples/data/data_client.py +79 -0
- samples/data/data_client_event.py +7 -0
- samples/trade/trade_event_sse_client.py +58 -0
- webull/__init__.py +1 -1
- webull/core/__init__.py +1 -1
- webull/core/sse/__init__.py +0 -0
- webull/core/sse/default_retry_policy.py +113 -0
- webull/core/sse/signature_composer.py +73 -0
- webull/core/sse/sse_parser.py +69 -0
- webull/core/sse/subscribe_response.py +84 -0
- webull/data/__init__.py +1 -1
- webull/data/data_client.py +2 -0
- webull/data/quotes/crypto_market_data.py +6 -1
- webull/data/quotes/event_market_data.py +6 -1
- webull/data/quotes/fundamentals.py +99 -0
- webull/data/quotes/futures_market_data.py +6 -1
- webull/data/quotes/news.py +70 -0
- webull/data/quotes/option_market_data.py +6 -1
- webull/data/quotes/screener.py +34 -0
- webull/data/request/get_crypto_historical_bars_request.py +8 -0
- webull/data/request/get_economic_calendar_request.py +39 -0
- webull/data/request/get_event_bars_request.py +9 -1
- webull/data/request/get_futures_historical_bars_request.py +9 -1
- webull/data/request/get_insider_holdings_request.py +35 -0
- webull/data/request/get_insider_transactions_request.py +39 -0
- webull/data/request/get_institution_holding_changes_request.py +39 -0
- webull/data/request/get_institution_holdings_request.py +31 -0
- webull/data/request/get_institution_search_request.py +31 -0
- webull/data/request/get_news_detail_request.py +27 -0
- webull/data/request/get_news_search_request.py +39 -0
- webull/data/request/get_option_bars_request.py +21 -0
- webull/data/request/get_stock_news_request.py +39 -0
- webull/data/request/screener/get_fear_and_greed_index_request.py +27 -0
- webull/data/request/screener/get_stock_unusual_activities_request.py +43 -0
- webull/trade/__init__.py +1 -1
- webull/trade/trade/account_info.py +1 -1
- webull/trade/trade_events_sse_client.py +480 -0
- {webull_openapi_python_sdk-3.0.3.dist-info → webull_openapi_python_sdk-3.1.0.dist-info}/METADATA +2 -1
- {webull_openapi_python_sdk-3.0.3.dist-info → webull_openapi_python_sdk-3.1.0.dist-info}/RECORD +44 -25
- {webull_openapi_python_sdk-3.0.3.dist-info → webull_openapi_python_sdk-3.1.0.dist-info}/WHEEL +1 -1
- {webull_openapi_python_sdk-3.0.3.dist-info → webull_openapi_python_sdk-3.1.0.dist-info}/licenses/LICENSE +0 -0
- {webull_openapi_python_sdk-3.0.3.dist-info → webull_openapi_python_sdk-3.1.0.dist-info}/licenses/NOTICE +0 -0
- {webull_openapi_python_sdk-3.0.3.dist-info → webull_openapi_python_sdk-3.1.0.dist-info}/top_level.txt +0 -0
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
# Copyright 2022 Webull
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
# coding=utf-8
|
|
16
|
+
|
|
17
|
+
from webull.core.request import ApiRequest
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GetStockNewsRequest(ApiRequest):
|
|
21
|
+
def __init__(self):
|
|
22
|
+
ApiRequest.__init__(self, "/market-data/news/stock-news/list", version='v3', method="GET",
|
|
23
|
+
query_params={})
|
|
24
|
+
|
|
25
|
+
def set_symbol(self, symbol):
|
|
26
|
+
if symbol:
|
|
27
|
+
self.add_query_param("symbol", symbol)
|
|
28
|
+
|
|
29
|
+
def set_category(self, category):
|
|
30
|
+
if category:
|
|
31
|
+
self.add_query_param("category", category)
|
|
32
|
+
|
|
33
|
+
def set_sentiment(self, sentiment):
|
|
34
|
+
if sentiment:
|
|
35
|
+
self.add_query_param("sentiment", sentiment)
|
|
36
|
+
|
|
37
|
+
def set_pagination_key(self, pagination_key):
|
|
38
|
+
if pagination_key:
|
|
39
|
+
self.add_query_param("pagination_key", pagination_key)
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Copyright 2022 Webull
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
# coding=utf-8
|
|
16
|
+
|
|
17
|
+
from webull.core.request import ApiRequest
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GetFearAndGreedIndexRequest(ApiRequest):
|
|
21
|
+
def __init__(self):
|
|
22
|
+
ApiRequest.__init__(self, "/market-data/screeners/fear-greed-indexes/get", version='v3', method="GET",
|
|
23
|
+
query_params={})
|
|
24
|
+
|
|
25
|
+
def set_category(self, category):
|
|
26
|
+
if category:
|
|
27
|
+
self.add_query_param("category", category)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# Copyright 2022 Webull
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
# coding=utf-8
|
|
16
|
+
|
|
17
|
+
from webull.core.request import ApiRequest
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class GetStockUnusualActivitiesRequest(ApiRequest):
|
|
21
|
+
def __init__(self):
|
|
22
|
+
ApiRequest.__init__(self, "/market-data/screeners/unusual-activities/list", version='v3', method="GET",
|
|
23
|
+
query_params={})
|
|
24
|
+
|
|
25
|
+
def set_symbol(self, symbol):
|
|
26
|
+
if symbol:
|
|
27
|
+
self.add_query_param("symbol", symbol)
|
|
28
|
+
|
|
29
|
+
def set_category(self, category):
|
|
30
|
+
if category:
|
|
31
|
+
self.add_query_param("category", category)
|
|
32
|
+
|
|
33
|
+
def set_count(self, count):
|
|
34
|
+
if count:
|
|
35
|
+
self.add_query_param("count", count)
|
|
36
|
+
|
|
37
|
+
def set_alert_types(self, alert_types):
|
|
38
|
+
if alert_types:
|
|
39
|
+
self.add_query_param("alert_types", alert_types)
|
|
40
|
+
|
|
41
|
+
def set_extended_hours_required(self, extended_hours_required):
|
|
42
|
+
if extended_hours_required:
|
|
43
|
+
self.add_query_param("extended_hours_required", extended_hours_required)
|
webull/trade/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '3.0
|
|
1
|
+
__version__ = '3.1.0'
|
|
@@ -44,7 +44,7 @@ class Account:
|
|
|
44
44
|
|
|
45
45
|
:param account_id: Account ID
|
|
46
46
|
:param total_asset_currency: The currency in which the total assets are denominated: the value refers to Currency
|
|
47
|
-
in the dictionary value.
|
|
47
|
+
in the dictionary value.
|
|
48
48
|
"""
|
|
49
49
|
account_balance_request = AccountBalanceRequest()
|
|
50
50
|
account_balance_request.set_account_id(account_id)
|
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
# Copyright 2022 Webull
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
# coding=utf-8
|
|
16
|
+
import json
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
import ssl
|
|
20
|
+
import threading
|
|
21
|
+
import time
|
|
22
|
+
|
|
23
|
+
import httpx
|
|
24
|
+
|
|
25
|
+
from webull.core.auth.algorithm import sha_hmac256_new
|
|
26
|
+
from webull.core.common import api_type
|
|
27
|
+
from webull.core.endpoint.default_endpoint_resolver import \
|
|
28
|
+
DefaultEndpointResolver
|
|
29
|
+
from webull.core.endpoint.resolver_endpoint_request import \
|
|
30
|
+
ResolveEndpointRequest
|
|
31
|
+
from webull.core.exception import error_code
|
|
32
|
+
from webull.core.exception.exceptions import ClientException, ServerException
|
|
33
|
+
from webull.core.retry.retry_condition import RetryCondition
|
|
34
|
+
from webull.core.sse.default_retry_policy import DefaultSseSubscribeRetryPolicy, SseSubscribeRetryPolicyContext
|
|
35
|
+
from webull.core.sse.signature_composer import calc_signature
|
|
36
|
+
from webull.core.sse.sse_parser import iter_sse_frames
|
|
37
|
+
from webull.core.sse.subscribe_response import SseSubscribeResponse, EVENT_SUBSCRIBE_SUCCESS, EVENT_PING, \
|
|
38
|
+
EVENT_BUSINESS, EVENT_AUTH_ERROR, EVENT_NUM_OF_CONN_EXCEED, EVENT_SUBSCRIBE_EXPIRED
|
|
39
|
+
from webull.core.utils import common as core_common
|
|
40
|
+
import webull.core.headers as hd
|
|
41
|
+
|
|
42
|
+
# contentTypes
|
|
43
|
+
JSON = "application/json"
|
|
44
|
+
TEXT = "text/plain"
|
|
45
|
+
|
|
46
|
+
DEFAULT_REGION_ID = "us"
|
|
47
|
+
DEFAULT_SUBSCRIBE_PATH = "/subscribe/sse"
|
|
48
|
+
# 1 2 4 allowed now, 7 subscribes order, position and option at once
|
|
49
|
+
DEFAULT_SUBSCRIBE_TYPE = 7
|
|
50
|
+
DEFAULT_CONNECT_TIMEOUT = 10
|
|
51
|
+
# Server writes a ": heartbeat" comment line every 20s by default, give up
|
|
52
|
+
# after two missed heartbeats and let the retry policy rebuild the subscription.
|
|
53
|
+
DEFAULT_READ_TIMEOUT = 45
|
|
54
|
+
MAX_ERROR_BODY_LENGTH = 512
|
|
55
|
+
ACCEPT_EVENT_STREAM = "text/event-stream"
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _mask(value, prefix_length=6):
|
|
59
|
+
"""Keep only a short prefix of a credential like value for logging."""
|
|
60
|
+
if not value:
|
|
61
|
+
return value
|
|
62
|
+
return value[:prefix_length] + "***"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class TradeEventsSseClient:
|
|
66
|
+
"""Trade events subscription over the SSE channel.
|
|
67
|
+
|
|
68
|
+
Drop in alternative to ``TradeEventsClient``: callbacks, logging hooks and
|
|
69
|
+
the retry mechanism keep the same shape, only the transport differs
|
|
70
|
+
(HTTP text/event-stream instead of gRPC server streaming).
|
|
71
|
+
|
|
72
|
+
Note that subscriptions are mutually exclusive per app key across both
|
|
73
|
+
channels. While another subscription of the same app key is active, the
|
|
74
|
+
new SSE subscribe request is rejected (the active one is not affected),
|
|
75
|
+
either with HTTP 429 before the stream is established, or with a
|
|
76
|
+
``numOfConnExceed`` frame right after it. Both cases are retried with
|
|
77
|
+
jittered exponential backoff.
|
|
78
|
+
|
|
79
|
+
``authError`` and ``subscribeExpired`` frames require client side action
|
|
80
|
+
(fix the credentials, renew the subscription), reconnecting with the same
|
|
81
|
+
credentials would fail again. They are passed to ``on_fatal_error``; the
|
|
82
|
+
subscription stops and raises ``ServerException`` unless the callback
|
|
83
|
+
returns True, in which case it keeps reconnecting with backoff (e.g. while
|
|
84
|
+
waiting for a renewal of the same app key).
|
|
85
|
+
|
|
86
|
+
Only stream closes and transport failures are reconnected. Exceptions
|
|
87
|
+
raised by ``on_connect`` / ``on_events_message`` or by decoding a JSON
|
|
88
|
+
payload stop the subscription and are re-raised by ``do_subscribe``, the
|
|
89
|
+
same as ``TradeEventsClient``.
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
def __init__(self, app_key, app_secret, region_id=DEFAULT_REGION_ID, host=None, port=443,
|
|
93
|
+
tls_enable=True, retry_policy=None, subscribe_type=DEFAULT_SUBSCRIBE_TYPE,
|
|
94
|
+
subscribe_path=DEFAULT_SUBSCRIBE_PATH, signer_spec=sha_hmac256_new,
|
|
95
|
+
connect_timeout=DEFAULT_CONNECT_TIMEOUT, read_timeout=DEFAULT_READ_TIMEOUT,
|
|
96
|
+
verify=None):
|
|
97
|
+
self._app_key = app_key
|
|
98
|
+
self._app_secret = app_secret
|
|
99
|
+
self._region_id = region_id
|
|
100
|
+
self._tls_enable = tls_enable
|
|
101
|
+
self._endpoint_resolver = DefaultEndpointResolver(self)
|
|
102
|
+
if not host:
|
|
103
|
+
endpoint_request = ResolveEndpointRequest(
|
|
104
|
+
self._region_id, api_type=api_type.EVENTS)
|
|
105
|
+
endpoint = self._endpoint_resolver.resolve(endpoint_request)
|
|
106
|
+
self._host = endpoint
|
|
107
|
+
else:
|
|
108
|
+
self._host = host
|
|
109
|
+
self._port = port
|
|
110
|
+
if retry_policy:
|
|
111
|
+
self._retry_policy = retry_policy
|
|
112
|
+
else:
|
|
113
|
+
self._retry_policy = DefaultSseSubscribeRetryPolicy()
|
|
114
|
+
self._subscribe_type = subscribe_type
|
|
115
|
+
self._subscribe_path = subscribe_path
|
|
116
|
+
self._signer_spec = signer_spec
|
|
117
|
+
self._connect_timeout = connect_timeout
|
|
118
|
+
self._read_timeout = read_timeout
|
|
119
|
+
self._verify = verify
|
|
120
|
+
|
|
121
|
+
self._logger = None
|
|
122
|
+
self._in_callback_mutex = threading.Lock()
|
|
123
|
+
self._callback_mutex = threading.RLock()
|
|
124
|
+
# callbacks
|
|
125
|
+
self._on_connect = None
|
|
126
|
+
self._on_events_message = None
|
|
127
|
+
self._on_fatal_error = None
|
|
128
|
+
self._on_log = None
|
|
129
|
+
# Last control frame of the current stream that ends the
|
|
130
|
+
# subscription (numOfConnExceed, authError, subscribeExpired).
|
|
131
|
+
self._fatal_response = None
|
|
132
|
+
# Whether the current stream received a subscribeSuccess frame.
|
|
133
|
+
self._stream_subscribed = False
|
|
134
|
+
|
|
135
|
+
def _get_url(self):
|
|
136
|
+
scheme = "https" if self._tls_enable else "http"
|
|
137
|
+
return "%s://%s:%s%s" % (scheme, self._host, self._port, self._subscribe_path)
|
|
138
|
+
|
|
139
|
+
def _get_verify_value(self):
|
|
140
|
+
verify = self._verify
|
|
141
|
+
if verify is None:
|
|
142
|
+
verify = os.environ.get('WEBULL_API_CA_BUNDLE', True)
|
|
143
|
+
# httpx deprecates a CA bundle path as the verify value, wrap it in an
|
|
144
|
+
# SSL context instead.
|
|
145
|
+
if isinstance(verify, str):
|
|
146
|
+
return ssl.create_default_context(cafile=verify)
|
|
147
|
+
return verify
|
|
148
|
+
|
|
149
|
+
def _build_request(self, accounts):
|
|
150
|
+
"""Build the request body and headers of one subscribe attempt.
|
|
151
|
+
|
|
152
|
+
The signature covers the exact body bytes being sent, so the body is
|
|
153
|
+
serialized once and reused for both signing and sending.
|
|
154
|
+
"""
|
|
155
|
+
body = {
|
|
156
|
+
"subscribeType": self._subscribe_type,
|
|
157
|
+
"timestamp": int(time.time() * 1000), # millis
|
|
158
|
+
"accounts": list(accounts),
|
|
159
|
+
}
|
|
160
|
+
body_string = core_common.json_dumps_compact(body)
|
|
161
|
+
body_bytes = body_string.encode("utf-8")
|
|
162
|
+
signature, headers = calc_signature(
|
|
163
|
+
self._app_key, self._app_secret, body_bytes, self._signer_spec)
|
|
164
|
+
request_id = core_common.get_uuid()
|
|
165
|
+
headers[hd.REQUEST_ID] = request_id
|
|
166
|
+
headers[hd.NATIVE_CONTENT_TYPE] = JSON
|
|
167
|
+
headers["Accept"] = ACCEPT_EVENT_STREAM
|
|
168
|
+
self._easy_log(logging.DEBUG,
|
|
169
|
+
"sse subscribe request, url:%s, request_id:%s, body:%s, signature:%s",
|
|
170
|
+
self._get_url(), request_id, body_string, _mask(signature))
|
|
171
|
+
return body_bytes, headers
|
|
172
|
+
|
|
173
|
+
def _read_error_body(self, response):
|
|
174
|
+
try:
|
|
175
|
+
# Streamed responses must be read before the body is accessible.
|
|
176
|
+
response.read()
|
|
177
|
+
content = response.text
|
|
178
|
+
except Exception as err:
|
|
179
|
+
return "failed to read error body:%s" % err
|
|
180
|
+
if content and len(content) > MAX_ERROR_BODY_LENGTH:
|
|
181
|
+
return content[:MAX_ERROR_BODY_LENGTH]
|
|
182
|
+
return content
|
|
183
|
+
|
|
184
|
+
def _to_server_exception(self, response, error_body):
|
|
185
|
+
error_code = str(response.status_code)
|
|
186
|
+
error_msg = error_body
|
|
187
|
+
if error_body:
|
|
188
|
+
try:
|
|
189
|
+
decoded = json.loads(error_body)
|
|
190
|
+
if isinstance(decoded, dict) and "error" in decoded:
|
|
191
|
+
error_msg = decoded["error"]
|
|
192
|
+
except ValueError:
|
|
193
|
+
pass
|
|
194
|
+
return ServerException(error_code, error_msg, http_status=response.status_code,
|
|
195
|
+
request_id=response.headers.get(hd.REQUEST_ID))
|
|
196
|
+
|
|
197
|
+
def _to_fatal_exception(self, response):
|
|
198
|
+
"""Turn a fatal control frame into a ``ServerException``.
|
|
199
|
+
|
|
200
|
+
The error code is the SSE frame name (e.g. ``subscribeExpired``) and
|
|
201
|
+
the message is the frame payload, a human readable reason.
|
|
202
|
+
"""
|
|
203
|
+
return ServerException(response.event, response.payload,
|
|
204
|
+
http_status=httpx.codes.OK, request_id=response.requestId)
|
|
205
|
+
|
|
206
|
+
def _stream_processing(self, session, accounts):
|
|
207
|
+
"""Implementation of subscription logic.
|
|
208
|
+
|
|
209
|
+
Args:
|
|
210
|
+
session: an ``httpx.Client`` with HTTP/2 enabled. HTTP/2 is
|
|
211
|
+
negotiated through TLS ALPN, the client falls back to HTTP/1.1
|
|
212
|
+
when the server does not offer HTTP/2 or TLS is disabled.
|
|
213
|
+
accounts: account IDs to subscribe.
|
|
214
|
+
"""
|
|
215
|
+
url = self._get_url()
|
|
216
|
+
timeout = httpx.Timeout(self._read_timeout, connect=self._connect_timeout)
|
|
217
|
+
retry_policy_context = SseSubscribeRetryPolicyContext(None, 0, None)
|
|
218
|
+
retries = 0
|
|
219
|
+
final_exception = None
|
|
220
|
+
while True:
|
|
221
|
+
self._fatal_response = None
|
|
222
|
+
self._stream_subscribed = False
|
|
223
|
+
body_bytes, headers = self._build_request(accounts)
|
|
224
|
+
try:
|
|
225
|
+
request = session.build_request("POST", url, headers=headers,
|
|
226
|
+
content=body_bytes, timeout=timeout)
|
|
227
|
+
response = session.send(request, stream=True)
|
|
228
|
+
try:
|
|
229
|
+
if response.status_code != httpx.codes.OK:
|
|
230
|
+
error_body = self._read_error_body(response)
|
|
231
|
+
final_exception = self._to_server_exception(response, error_body)
|
|
232
|
+
retry_policy_context = SseSubscribeRetryPolicyContext(
|
|
233
|
+
final_exception, retries, response.status_code)
|
|
234
|
+
self._easy_log(logging.ERROR,
|
|
235
|
+
"sse subscribe failed, http status:%s, error:%s",
|
|
236
|
+
response.status_code, error_body)
|
|
237
|
+
else:
|
|
238
|
+
self._easy_log(logging.INFO, "sse stream established, url:%s, http_version:%s",
|
|
239
|
+
url, response.http_version)
|
|
240
|
+
for event, data in iter_sse_frames(response.iter_lines()):
|
|
241
|
+
self._easy_handler(event, data)
|
|
242
|
+
if self._fatal_response is not None:
|
|
243
|
+
# The server closes the stream right after a
|
|
244
|
+
# fatal frame, stop reading it.
|
|
245
|
+
break
|
|
246
|
+
# The server closed the stream, this channel has no
|
|
247
|
+
# resume support so a new subscription is required.
|
|
248
|
+
final_exception = None
|
|
249
|
+
retry_policy_context = SseSubscribeRetryPolicyContext(
|
|
250
|
+
None, retries, None)
|
|
251
|
+
self._easy_log(logging.WARNING, "sse stream closed by server")
|
|
252
|
+
finally:
|
|
253
|
+
response.close()
|
|
254
|
+
except httpx.HTTPError as request_error:
|
|
255
|
+
final_exception = request_error
|
|
256
|
+
retry_policy_context = SseSubscribeRetryPolicyContext(
|
|
257
|
+
request_error, retries, None)
|
|
258
|
+
self._easy_log(logging.ERROR, "sse request error:%s", request_error)
|
|
259
|
+
except Exception as exception:
|
|
260
|
+
final_exception = exception
|
|
261
|
+
retry_policy_context = SseSubscribeRetryPolicyContext(
|
|
262
|
+
exception, retries, None)
|
|
263
|
+
self._easy_log(logging.ERROR, "sse exception:%s", exception)
|
|
264
|
+
# The subscription succeeded on this attempt, count consecutive
|
|
265
|
+
# failures from scratch whatever ended the stream (server close,
|
|
266
|
+
# read timeout, connection reset). A 200 stream without
|
|
267
|
+
# subscribeSuccess (e.g. numOfConnExceed) keeps the backoff going.
|
|
268
|
+
if self._stream_subscribed:
|
|
269
|
+
retries = 0
|
|
270
|
+
retry_policy_context.retries_attempted = 0
|
|
271
|
+
retryable = self._retry_policy.should_retry(retry_policy_context)
|
|
272
|
+
fatal_response = self._fatal_response
|
|
273
|
+
if fatal_response is not None:
|
|
274
|
+
final_exception = self._to_fatal_exception(fatal_response)
|
|
275
|
+
retry_policy_context.exception = final_exception
|
|
276
|
+
if fatal_response.event != EVENT_NUM_OF_CONN_EXCEED \
|
|
277
|
+
and not self._handle_fatal_error(fatal_response):
|
|
278
|
+
self._easy_log(
|
|
279
|
+
logging.ERROR, "processing stopped due to fatal frame, response:%s",
|
|
280
|
+
fatal_response)
|
|
281
|
+
break
|
|
282
|
+
# Mutex rejections share the backoff of HTTP 429, and so do
|
|
283
|
+
# the reconnects requested by on_fatal_error.
|
|
284
|
+
retryable |= RetryCondition.SHOULD_RETRY_WITH_THROTTLING_BACKOFF
|
|
285
|
+
if retryable & RetryCondition.NO_RETRY:
|
|
286
|
+
self._easy_log(
|
|
287
|
+
logging.ERROR, "processing stopped, not retryable, retry_context:%s",
|
|
288
|
+
retry_policy_context)
|
|
289
|
+
break
|
|
290
|
+
retry_policy_context.retryable = retryable
|
|
291
|
+
time_to_sleep = self._retry_policy.compute_delay_before_next_retry(
|
|
292
|
+
retry_policy_context)
|
|
293
|
+
self._easy_log(logging.INFO, "next retry will be started in %s ms, retry_context:%s",
|
|
294
|
+
time_to_sleep, retry_policy_context)
|
|
295
|
+
time.sleep(time_to_sleep / 1000.0)
|
|
296
|
+
retries += 1
|
|
297
|
+
if final_exception:
|
|
298
|
+
raise final_exception
|
|
299
|
+
|
|
300
|
+
@property
|
|
301
|
+
def on_connect(self):
|
|
302
|
+
return self._on_connect
|
|
303
|
+
|
|
304
|
+
@on_connect.setter
|
|
305
|
+
def on_connect(self, func):
|
|
306
|
+
with self._callback_mutex:
|
|
307
|
+
self._on_connect = func
|
|
308
|
+
|
|
309
|
+
@property
|
|
310
|
+
def on_events_message(self):
|
|
311
|
+
return self._on_events_message
|
|
312
|
+
|
|
313
|
+
@on_events_message.setter
|
|
314
|
+
def on_events_message(self, func):
|
|
315
|
+
with self._callback_mutex:
|
|
316
|
+
self._on_events_message = func
|
|
317
|
+
|
|
318
|
+
@property
|
|
319
|
+
def on_fatal_error(self):
|
|
320
|
+
"""Callback ``on_fatal_error(client, response)`` invoked on an
|
|
321
|
+
``authError`` or ``subscribeExpired`` frame.
|
|
322
|
+
|
|
323
|
+
Return True to keep reconnecting with backoff, e.g. when the
|
|
324
|
+
subscription of the same app key is going to be renewed. Any other
|
|
325
|
+
return value (the default when no callback is set) stops the
|
|
326
|
+
subscription and makes ``do_subscribe`` raise ``ServerException``.
|
|
327
|
+
"""
|
|
328
|
+
return self._on_fatal_error
|
|
329
|
+
|
|
330
|
+
@on_fatal_error.setter
|
|
331
|
+
def on_fatal_error(self, func):
|
|
332
|
+
with self._callback_mutex:
|
|
333
|
+
self._on_fatal_error = func
|
|
334
|
+
|
|
335
|
+
@property
|
|
336
|
+
def on_log(self):
|
|
337
|
+
return self._on_log
|
|
338
|
+
|
|
339
|
+
@on_log.setter
|
|
340
|
+
def on_log(self, func):
|
|
341
|
+
self._on_log = func
|
|
342
|
+
|
|
343
|
+
def _easy_log(self, level, fmt, *args):
|
|
344
|
+
if self.on_log is not None:
|
|
345
|
+
buf = fmt % args
|
|
346
|
+
try:
|
|
347
|
+
self.on_log(level, buf)
|
|
348
|
+
except Exception:
|
|
349
|
+
pass
|
|
350
|
+
if self._logger is not None:
|
|
351
|
+
self._logger.log(level, fmt, *args)
|
|
352
|
+
|
|
353
|
+
def enable_logger(self, logger=None):
|
|
354
|
+
if logger is None:
|
|
355
|
+
if self._logger is not None:
|
|
356
|
+
return
|
|
357
|
+
logger = logging.getLogger(__name__)
|
|
358
|
+
self._logger = logger
|
|
359
|
+
|
|
360
|
+
def disable_logger(self):
|
|
361
|
+
self._logger = None
|
|
362
|
+
|
|
363
|
+
def _handle_subscribe_success(self, response):
|
|
364
|
+
self._stream_subscribed = True
|
|
365
|
+
self._easy_log(
|
|
366
|
+
logging.INFO, "subscribe success, response:%s", response)
|
|
367
|
+
with self._callback_mutex:
|
|
368
|
+
on_connect = self.on_connect
|
|
369
|
+
if not on_connect:
|
|
370
|
+
return
|
|
371
|
+
with self._in_callback_mutex:
|
|
372
|
+
try:
|
|
373
|
+
on_connect(self, response.payload, response)
|
|
374
|
+
except Exception as err:
|
|
375
|
+
self._easy_log(
|
|
376
|
+
logging.ERROR, 'Caught exception in on_connect: %s', err)
|
|
377
|
+
raise err
|
|
378
|
+
|
|
379
|
+
def _handle_fatal_error(self, response):
|
|
380
|
+
"""Ask ``on_fatal_error`` whether to keep reconnecting.
|
|
381
|
+
|
|
382
|
+
Returns:
|
|
383
|
+
True to keep reconnecting, False to stop the subscription.
|
|
384
|
+
"""
|
|
385
|
+
with self._callback_mutex:
|
|
386
|
+
on_fatal_error = self.on_fatal_error
|
|
387
|
+
if not on_fatal_error:
|
|
388
|
+
return False
|
|
389
|
+
with self._in_callback_mutex:
|
|
390
|
+
try:
|
|
391
|
+
return on_fatal_error(self, response) is True
|
|
392
|
+
except Exception as err:
|
|
393
|
+
self._easy_log(
|
|
394
|
+
logging.ERROR, 'Caught exception in on_fatal_error: %s', err)
|
|
395
|
+
return False
|
|
396
|
+
|
|
397
|
+
def _handle_default(self, response, level):
|
|
398
|
+
self._easy_log(level, "response:%s", response)
|
|
399
|
+
|
|
400
|
+
def _handle_message(self, response):
|
|
401
|
+
self._easy_log(
|
|
402
|
+
logging.DEBUG, "message received, response:%s", response)
|
|
403
|
+
with self._callback_mutex:
|
|
404
|
+
on_events_message = self.on_events_message
|
|
405
|
+
if not on_events_message:
|
|
406
|
+
return
|
|
407
|
+
with self._in_callback_mutex:
|
|
408
|
+
content_type = response.contentType
|
|
409
|
+
_payload = response.payload
|
|
410
|
+
if JSON == content_type:
|
|
411
|
+
try:
|
|
412
|
+
_payload = json.loads(response.payload)
|
|
413
|
+
except Exception as err:
|
|
414
|
+
self._easy_log(
|
|
415
|
+
logging.ERROR, 'Caught exception in decode message: %s, %s', _payload, err)
|
|
416
|
+
raise err
|
|
417
|
+
try:
|
|
418
|
+
on_events_message(response.eventType,
|
|
419
|
+
response.subscribeType, _payload, response)
|
|
420
|
+
except Exception as err:
|
|
421
|
+
self._easy_log(
|
|
422
|
+
logging.ERROR, 'Caught exception in on_events_message: %s', err)
|
|
423
|
+
raise err
|
|
424
|
+
|
|
425
|
+
def _easy_handler(self, event, data):
|
|
426
|
+
try:
|
|
427
|
+
response = SseSubscribeResponse(event, data)
|
|
428
|
+
except ValueError as err:
|
|
429
|
+
self._easy_log(
|
|
430
|
+
logging.ERROR, 'Caught exception in decode sse frame: %s, %s, %s', event, data, err)
|
|
431
|
+
return
|
|
432
|
+
# Dispatch on the SSE frame name, the eventType value in the data is
|
|
433
|
+
# the upstream business type for "event" frames only.
|
|
434
|
+
if event == EVENT_BUSINESS:
|
|
435
|
+
self._handle_message(response)
|
|
436
|
+
elif event == EVENT_SUBSCRIBE_SUCCESS:
|
|
437
|
+
self._handle_subscribe_success(response)
|
|
438
|
+
elif event == EVENT_PING:
|
|
439
|
+
self._handle_default(response, logging.DEBUG)
|
|
440
|
+
elif event == EVENT_AUTH_ERROR or event == EVENT_SUBSCRIBE_EXPIRED:
|
|
441
|
+
self._handle_default(response, logging.FATAL)
|
|
442
|
+
self._fatal_response = response
|
|
443
|
+
elif event == EVENT_NUM_OF_CONN_EXCEED:
|
|
444
|
+
# Rejected by the session mutex, retried with backoff.
|
|
445
|
+
self._handle_default(response, logging.ERROR)
|
|
446
|
+
self._fatal_response = response
|
|
447
|
+
else:
|
|
448
|
+
self._easy_log(logging.WARNING, "unknown sse frame ignored, response:%s", response)
|
|
449
|
+
|
|
450
|
+
@staticmethod
|
|
451
|
+
def _validate_accounts(accounts):
|
|
452
|
+
# A plain string is iterable too, reject it explicitly instead of
|
|
453
|
+
# subscribing each character as an account ID.
|
|
454
|
+
if not isinstance(accounts, (list, tuple)) or not accounts:
|
|
455
|
+
raise ClientException(error_code.SDK_INVALID_PARAMETER,
|
|
456
|
+
"accounts should be a non empty list of account IDs.")
|
|
457
|
+
for account in accounts:
|
|
458
|
+
if not isinstance(account, str) or not account.strip():
|
|
459
|
+
raise ClientException(error_code.SDK_INVALID_PARAMETER,
|
|
460
|
+
"account ID should be a non empty string.")
|
|
461
|
+
|
|
462
|
+
def do_subscribe(self, accounts):
|
|
463
|
+
"""Subscribe the given accounts and keep reading events until stopped.
|
|
464
|
+
|
|
465
|
+
This call is synchronous, it returns only when the retry policy gives
|
|
466
|
+
up, and raises the last failure in that case.
|
|
467
|
+
|
|
468
|
+
Args:
|
|
469
|
+
accounts: non empty list of account IDs to subscribe.
|
|
470
|
+
|
|
471
|
+
Raises:
|
|
472
|
+
ClientException: ``accounts`` is empty or contains an invalid ID,
|
|
473
|
+
the server would reject the request with HTTP 400.
|
|
474
|
+
"""
|
|
475
|
+
self._validate_accounts(accounts)
|
|
476
|
+
self._easy_log(logging.INFO,
|
|
477
|
+
"sse subscribe starting, url:%s, tls_enable:%s, accounts:%s",
|
|
478
|
+
self._get_url(), self._tls_enable, accounts)
|
|
479
|
+
with httpx.Client(http2=True, verify=self._get_verify_value()) as session:
|
|
480
|
+
self._stream_processing(session, accounts)
|
{webull_openapi_python_sdk-3.0.3.dist-info → webull_openapi_python_sdk-3.1.0.dist-info}/METADATA
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: webull-openapi-python-sdk
|
|
3
|
-
Version: 3.0
|
|
3
|
+
Version: 3.1.0
|
|
4
4
|
Summary: Webull Python SDK.
|
|
5
5
|
Home-page:
|
|
6
6
|
Author: Webull
|
|
@@ -16,6 +16,7 @@ Requires-Dist: cachetools<6,>=5.2.0
|
|
|
16
16
|
Requires-Dist: paho-mqtt<2,>=1.6.1
|
|
17
17
|
Requires-Dist: urllib3>=2.0
|
|
18
18
|
Requires-Dist: requests>=2.31.0
|
|
19
|
+
Requires-Dist: httpx[http2]<0.29,>=0.28.1
|
|
19
20
|
Requires-Dist: six>=1.16.0
|
|
20
21
|
Requires-Dist: cryptography<42,>=3.4; python_version < "3.12"
|
|
21
22
|
Requires-Dist: cryptography<43,>=41.0; python_version >= "3.12" and python_version < "3.14"
|