webull-openapi-python-sdk 3.0.4__py3-none-any.whl → 3.1.1__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/trade/trade_client_v3.py +5 -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/trade/__init__.py +1 -1
- webull/trade/common/currency.py +1 -0
- webull/trade/trade/account_info.py +1 -1
- webull/trade/trade_events_sse_client.py +480 -0
- {webull_openapi_python_sdk-3.0.4.dist-info → webull_openapi_python_sdk-3.1.1.dist-info}/METADATA +2 -1
- {webull_openapi_python_sdk-3.0.4.dist-info → webull_openapi_python_sdk-3.1.1.dist-info}/RECORD +21 -14
- {webull_openapi_python_sdk-3.0.4.dist-info → webull_openapi_python_sdk-3.1.1.dist-info}/WHEEL +1 -1
- {webull_openapi_python_sdk-3.0.4.dist-info → webull_openapi_python_sdk-3.1.1.dist-info}/licenses/LICENSE +0 -0
- {webull_openapi_python_sdk-3.0.4.dist-info → webull_openapi_python_sdk-3.1.1.dist-info}/licenses/NOTICE +0 -0
- {webull_openapi_python_sdk-3.0.4.dist-info → webull_openapi_python_sdk-3.1.1.dist-info}/top_level.txt +0 -0
samples/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '3.
|
|
1
|
+
__version__ = '3.1.1'
|
samples/trade/trade_client_v3.py
CHANGED
|
@@ -94,6 +94,11 @@ if __name__ == '__main__':
|
|
|
94
94
|
# Currently, only Webull JP is supported.
|
|
95
95
|
# "account_tax_type":"GENERAL",
|
|
96
96
|
# "margin_type": "ONE_DAY"
|
|
97
|
+
# trade_currency: Currently, only Webull JP is supported.
|
|
98
|
+
# Specifies the settlement currency of the order. Only applicable to Japan stock (JP) orders,
|
|
99
|
+
# and required for JP market orders in both preview_order and place_order.
|
|
100
|
+
# Valid values: JPY, USD.
|
|
101
|
+
# "trade_currency": "JPY"
|
|
97
102
|
}
|
|
98
103
|
]
|
|
99
104
|
|
|
@@ -0,0 +1,58 @@
|
|
|
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
|
+
import logging
|
|
16
|
+
|
|
17
|
+
from webull.trade.events.types import ORDER_STATUS_CHANGED, EVENT_TYPE_ORDER, EVENT_TYPE_POSITION, \
|
|
18
|
+
POSITION_STATUS_CHANGED, EVENT_TYPE_OPTION, OPTION_STATUS_CHANGED
|
|
19
|
+
from webull.trade.trade_events_sse_client import TradeEventsSseClient
|
|
20
|
+
|
|
21
|
+
your_app_key = "<your_app_key>"
|
|
22
|
+
your_app_secret = "<your_app_secret>"
|
|
23
|
+
account_id = "<your_account_id>"
|
|
24
|
+
region_id = "<region_id>"
|
|
25
|
+
|
|
26
|
+
optional_api_endpoint = "<event_api_endpoint>"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _on_log(level, log_content):
|
|
30
|
+
print(logging.getLevelName(level), log_content)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def my_on_events_message(event_type, subscribe_type, payload, raw_message):
|
|
34
|
+
if EVENT_TYPE_ORDER == event_type and ORDER_STATUS_CHANGED == subscribe_type:
|
|
35
|
+
print('----request_id:%s----' % payload['request_id'])
|
|
36
|
+
print(payload)
|
|
37
|
+
if EVENT_TYPE_POSITION == event_type and POSITION_STATUS_CHANGED == subscribe_type:
|
|
38
|
+
print('event payload:%s' % payload)
|
|
39
|
+
if EVENT_TYPE_OPTION == event_type and OPTION_STATUS_CHANGED == subscribe_type:
|
|
40
|
+
print('option payload:%s' % payload)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
if __name__ == '__main__':
|
|
44
|
+
# Create SSE EventsClient instance
|
|
45
|
+
trade_events_sse_client = TradeEventsSseClient(your_app_key, your_app_secret, region_id)
|
|
46
|
+
# [Important] For non production environment, you need to set the domain name of the subscription service through events client. For example, the domain name of the UAT environment is set here
|
|
47
|
+
# [Important] The SSE endpoint shares the public port and TLS settings with the gRPC channel, the defaults (443, TLS) apply
|
|
48
|
+
# trade_events_sse_client = TradeEventsSseClient(your_app_key, your_app_secret, region_id, host=optional_api_endpoint)
|
|
49
|
+
trade_events_sse_client.on_log = _on_log
|
|
50
|
+
|
|
51
|
+
# Set the callback function when the event data is received.
|
|
52
|
+
# The data of order status change is printed here
|
|
53
|
+
|
|
54
|
+
trade_events_sse_client.on_events_message = my_on_events_message
|
|
55
|
+
# Set the account ID to be subscribed and initiate the subscription. This method is synchronous
|
|
56
|
+
# Note: one app key can hold only one active subscription across the gRPC and SSE channels,
|
|
57
|
+
# close the gRPC subscription first, otherwise the request is rejected with HTTP 429
|
|
58
|
+
trade_events_sse_client.do_subscribe([account_id])
|
webull/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '3.
|
|
1
|
+
__version__ = '3.1.1'
|
webull/core/__init__.py
CHANGED
|
File without changes
|
|
@@ -0,0 +1,113 @@
|
|
|
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 httpx
|
|
17
|
+
|
|
18
|
+
from webull.core.retry.backoff_strategy import (
|
|
19
|
+
BackoffStrategy, FixedDelayStrategy, JitteredExponentialBackoffStrategy)
|
|
20
|
+
from webull.core.retry.retry_condition import (
|
|
21
|
+
MaxRetryTimesCondition, MergeRetryCondition, RetryCondition)
|
|
22
|
+
from webull.core.retry.retry_policy import RetryPolicy
|
|
23
|
+
from webull.core.retry.retry_policy_context import RetryPolicyContext
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class SseSubscribeRetryPolicyContext(RetryPolicyContext):
|
|
27
|
+
"""Retry context of the SSE subscription.
|
|
28
|
+
|
|
29
|
+
``http_status_code`` is None when the failure happened on an already
|
|
30
|
+
established stream (connection reset, read timeout, server closed the
|
|
31
|
+
stream) or before any HTTP response was received.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def __init__(self, exception, retries_attempted, http_status_code):
|
|
35
|
+
super().__init__(None, exception, retries_attempted, http_status_code)
|
|
36
|
+
|
|
37
|
+
def __str__(self):
|
|
38
|
+
return "exception:%s, retries:%s, http_status_code:%s" % (
|
|
39
|
+
self.exception, self.retries_attempted, self.http_status_code)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class RetryOnSseHttpStatusCondition(RetryCondition):
|
|
43
|
+
# 429 is the session mutex rejection, it must be retried with backoff.
|
|
44
|
+
# 5xx are transient server side failures.
|
|
45
|
+
DEFAULT_RETRYABLE_HTTP_STATUS_LIST = [429, 500, 502, 503, 504]
|
|
46
|
+
THROTTLING_HTTP_STATUS_LIST = [429]
|
|
47
|
+
|
|
48
|
+
def __init__(self, retryable_http_status_list=None):
|
|
49
|
+
if retryable_http_status_list:
|
|
50
|
+
self.retryable_http_status_list = retryable_http_status_list
|
|
51
|
+
else:
|
|
52
|
+
self.retryable_http_status_list = self.DEFAULT_RETRYABLE_HTTP_STATUS_LIST
|
|
53
|
+
|
|
54
|
+
def should_retry(self, retry_policy_context):
|
|
55
|
+
http_status_code = retry_policy_context.http_status_code
|
|
56
|
+
if http_status_code is None:
|
|
57
|
+
exception = retry_policy_context.exception
|
|
58
|
+
# A stream closed by the server (no exception) or a transport level
|
|
59
|
+
# failure: the SSE channel has no resume support so a brand new
|
|
60
|
+
# subscription is the only way to keep receiving events.
|
|
61
|
+
if exception is None or isinstance(exception, httpx.TransportError):
|
|
62
|
+
return RetryCondition.RETRY
|
|
63
|
+
# Any other exception (e.g. raised by a user callback or a payload
|
|
64
|
+
# that cannot be decoded) would happen again after reconnecting,
|
|
65
|
+
# surface it to the caller instead, same as the gRPC channel.
|
|
66
|
+
return RetryCondition.NO_RETRY
|
|
67
|
+
if http_status_code in self.retryable_http_status_list:
|
|
68
|
+
if http_status_code in self.THROTTLING_HTTP_STATUS_LIST:
|
|
69
|
+
return RetryCondition.RETRY | RetryCondition.SHOULD_RETRY_WITH_THROTTLING_BACKOFF
|
|
70
|
+
return RetryCondition.RETRY
|
|
71
|
+
# 400/401/403/404/405 are caused by the request itself, retrying with
|
|
72
|
+
# the same parameters would fail again.
|
|
73
|
+
return RetryCondition.NO_RETRY
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class DefaultSseSubscribeRetryCondition(RetryCondition):
|
|
77
|
+
def __init__(self, max_retry_times=-1):
|
|
78
|
+
RetryCondition.__init__(self)
|
|
79
|
+
if max_retry_times < 0:
|
|
80
|
+
_conditions = []
|
|
81
|
+
else:
|
|
82
|
+
_conditions = [MaxRetryTimesCondition(max_retry_times)]
|
|
83
|
+
_conditions.append(RetryOnSseHttpStatusCondition())
|
|
84
|
+
self._condition = MergeRetryCondition(_conditions)
|
|
85
|
+
|
|
86
|
+
def should_retry(self, retry_policy_context):
|
|
87
|
+
return self._condition.should_retry(retry_policy_context)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class SseSubscribeBackoffStrategy(BackoffStrategy):
|
|
91
|
+
"""Fixed delay for regular reconnects, jittered backoff for 429 rejections."""
|
|
92
|
+
|
|
93
|
+
DEFAULT_THROTTLED_BASE_DELAY = 5000
|
|
94
|
+
DEFAULT_THROTTLED_MAX_DELAY = 60000
|
|
95
|
+
|
|
96
|
+
def __init__(self, fixed_delay=5000, throttled_base_delay=None, throttled_max_delay=None):
|
|
97
|
+
self._fixed_backoff_strategy = FixedDelayStrategy(fixed_delay)
|
|
98
|
+
self._throttled_backoff_strategy = JitteredExponentialBackoffStrategy(
|
|
99
|
+
throttled_base_delay or self.DEFAULT_THROTTLED_BASE_DELAY,
|
|
100
|
+
throttled_max_delay or self.DEFAULT_THROTTLED_MAX_DELAY)
|
|
101
|
+
|
|
102
|
+
def compute_delay_before_next_retry(self, retry_policy_context):
|
|
103
|
+
if retry_policy_context.retryable & RetryCondition.SHOULD_RETRY_WITH_THROTTLING_BACKOFF:
|
|
104
|
+
return self._throttled_backoff_strategy.compute_delay_before_next_retry(
|
|
105
|
+
retry_policy_context)
|
|
106
|
+
return self._fixed_backoff_strategy.compute_delay_before_next_retry(
|
|
107
|
+
retry_policy_context)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class DefaultSseSubscribeRetryPolicy(RetryPolicy):
|
|
111
|
+
def __init__(self, max_retry_times=-1, fixed_delay=5000):
|
|
112
|
+
RetryPolicy.__init__(self, DefaultSseSubscribeRetryCondition(max_retry_times),
|
|
113
|
+
SseSubscribeBackoffStrategy(fixed_delay))
|
|
@@ -0,0 +1,73 @@
|
|
|
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 logging
|
|
17
|
+
|
|
18
|
+
from webull.core.auth.algorithm import sha_hmac256_new
|
|
19
|
+
from webull.core.auth.composer import default_signature_composer
|
|
20
|
+
import webull.core.headers as hd
|
|
21
|
+
import webull.core.utils.common as core_common
|
|
22
|
+
|
|
23
|
+
logger = logging.getLogger(__name__)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def _build_sign_headers(app_key_id, signer_spec):
|
|
27
|
+
return {
|
|
28
|
+
hd.APP_KEY: app_key_id,
|
|
29
|
+
hd.SIGN_ALGORITHM: signer_spec.get_signer_name(),
|
|
30
|
+
hd.SIGN_VERSION: signer_spec.get_signer_version(),
|
|
31
|
+
hd.NONCE: core_common.get_uuid(),
|
|
32
|
+
hd.TIMESTAMP: core_common.get_iso_8601_date()
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _get_body_string(body_bytes, signer_spec):
|
|
37
|
+
"""Hash the exact bytes that will be sent as the HTTP request body.
|
|
38
|
+
|
|
39
|
+
The SSE channel signs the raw JSON body bytes, unlike the gRPC channel
|
|
40
|
+
which signs the protobuf serialized bytes of SubscribeRequest.
|
|
41
|
+
"""
|
|
42
|
+
if body_bytes:
|
|
43
|
+
if signer_spec == sha_hmac256_new:
|
|
44
|
+
return core_common.sha256_hex(body_bytes)
|
|
45
|
+
return core_common.md5_hex(body_bytes)
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def calc_signature(app_key_id, app_key_secret, body_bytes, signer_spec):
|
|
50
|
+
"""Sign an SSE subscribe request.
|
|
51
|
+
|
|
52
|
+
Args:
|
|
53
|
+
app_key_id: application app key.
|
|
54
|
+
app_key_secret: application app secret.
|
|
55
|
+
body_bytes: raw bytes of the JSON request body, exactly as sent.
|
|
56
|
+
signer_spec: signing algorithm module, e.g. sha_hmac256_new or sha_hmac1.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
tuple of (signature, headers dict) where headers already contains the
|
|
60
|
+
five signing headers plus x-signature.
|
|
61
|
+
"""
|
|
62
|
+
headers = _build_sign_headers(app_key_id, signer_spec)
|
|
63
|
+
sign_params = default_signature_composer._lower_key_dict(headers)
|
|
64
|
+
logger.debug("sign_params:%s", sign_params)
|
|
65
|
+
body_string = _get_body_string(body_bytes, signer_spec)
|
|
66
|
+
logger.debug("body_string:%s", body_string)
|
|
67
|
+
string_to_sign = default_signature_composer._build_sign_string(
|
|
68
|
+
sign_params, None, body_string)
|
|
69
|
+
logger.debug("string_to_sign:%s", string_to_sign)
|
|
70
|
+
signature = default_signature_composer._gen_signature(
|
|
71
|
+
string_to_sign, app_key_secret, signer_spec)
|
|
72
|
+
headers[hd.SIGNATURE] = signature
|
|
73
|
+
return signature, headers
|
|
@@ -0,0 +1,69 @@
|
|
|
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
|
+
# Default event name used when the server omits the "event" field.
|
|
18
|
+
DEFAULT_EVENT_NAME = "message"
|
|
19
|
+
|
|
20
|
+
_FIELD_EVENT = "event"
|
|
21
|
+
_FIELD_DATA = "data"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _decode_line(line):
|
|
25
|
+
if line is None:
|
|
26
|
+
return None
|
|
27
|
+
if isinstance(line, bytes):
|
|
28
|
+
return line.decode("utf-8", "replace")
|
|
29
|
+
return line
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def iter_sse_frames(lines):
|
|
33
|
+
"""Turn a raw SSE line stream into (event_name, data) tuples.
|
|
34
|
+
|
|
35
|
+
Args:
|
|
36
|
+
lines: iterator over the response lines, either bytes or str.
|
|
37
|
+
Typically ``httpx.Response.iter_lines()``.
|
|
38
|
+
|
|
39
|
+
Yields:
|
|
40
|
+
tuple of (event name, data payload). Multiple ``data:`` lines of the
|
|
41
|
+
same frame are joined with a newline, as required by the SSE spec.
|
|
42
|
+
"""
|
|
43
|
+
event_name = None
|
|
44
|
+
data_lines = []
|
|
45
|
+
for raw_line in lines:
|
|
46
|
+
line = _decode_line(raw_line)
|
|
47
|
+
if line is None:
|
|
48
|
+
continue
|
|
49
|
+
line = line.rstrip("\r")
|
|
50
|
+
if not line:
|
|
51
|
+
# Blank line terminates the current frame.
|
|
52
|
+
if event_name is not None or data_lines:
|
|
53
|
+
yield event_name or DEFAULT_EVENT_NAME, "\n".join(data_lines)
|
|
54
|
+
event_name = None
|
|
55
|
+
data_lines = []
|
|
56
|
+
continue
|
|
57
|
+
if line.startswith(":"):
|
|
58
|
+
# Comment line, used by some servers to keep the connection alive.
|
|
59
|
+
continue
|
|
60
|
+
field, _, value = line.partition(":")
|
|
61
|
+
if value.startswith(" "):
|
|
62
|
+
value = value[1:]
|
|
63
|
+
if field == _FIELD_EVENT:
|
|
64
|
+
event_name = value
|
|
65
|
+
elif field == _FIELD_DATA:
|
|
66
|
+
data_lines.append(value)
|
|
67
|
+
# Other fields (id, retry) are not used by this channel.
|
|
68
|
+
if event_name is not None or data_lines:
|
|
69
|
+
yield event_name or DEFAULT_EVENT_NAME, "\n".join(data_lines)
|
|
@@ -0,0 +1,84 @@
|
|
|
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
|
+
|
|
18
|
+
# Control event type values, kept identical to the gRPC EventType enum.
|
|
19
|
+
# Declared locally so that the SSE channel does not depend on protobuf.
|
|
20
|
+
SUBSCRIBE_SUCCESS = 0
|
|
21
|
+
PING = 1
|
|
22
|
+
AUTH_ERROR = 2
|
|
23
|
+
NUM_OF_CONN_EXCEED = 3
|
|
24
|
+
SUBSCRIBE_EXPIRED = 4
|
|
25
|
+
|
|
26
|
+
# SSE frame names pushed by the server.
|
|
27
|
+
EVENT_SUBSCRIBE_SUCCESS = "subscribeSuccess"
|
|
28
|
+
EVENT_PING = "ping"
|
|
29
|
+
EVENT_BUSINESS = "event"
|
|
30
|
+
EVENT_SUBSCRIBE_EXPIRED = "subscribeExpired"
|
|
31
|
+
EVENT_AUTH_ERROR = "authError"
|
|
32
|
+
EVENT_NUM_OF_CONN_EXCEED = "numOfConnExceed"
|
|
33
|
+
|
|
34
|
+
# Control frames are identified by the SSE frame name, not by the eventType
|
|
35
|
+
# value in the data (zero value fields such as eventType 0 are omitted).
|
|
36
|
+
EVENT_NAME_TO_EVENT_TYPE = {
|
|
37
|
+
EVENT_SUBSCRIBE_SUCCESS: SUBSCRIBE_SUCCESS,
|
|
38
|
+
EVENT_PING: PING,
|
|
39
|
+
EVENT_AUTH_ERROR: AUTH_ERROR,
|
|
40
|
+
EVENT_NUM_OF_CONN_EXCEED: NUM_OF_CONN_EXCEED,
|
|
41
|
+
EVENT_SUBSCRIBE_EXPIRED: SUBSCRIBE_EXPIRED,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class SseSubscribeResponse:
|
|
46
|
+
"""Decoded SSE frame exposing the same fields as the gRPC SubscribeResponse.
|
|
47
|
+
|
|
48
|
+
Field names intentionally match the protobuf message (``eventType``,
|
|
49
|
+
``subscribeType``, ``contentType``, ``payload``, ``requestId``,
|
|
50
|
+
``timestamp``) so that callbacks written against the gRPC channel keep
|
|
51
|
+
working without changes.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
def __init__(self, event, data):
|
|
55
|
+
"""
|
|
56
|
+
Args:
|
|
57
|
+
event: SSE frame name, e.g. ``subscribeSuccess``, ``ping``, ``event``.
|
|
58
|
+
data: raw ``data:`` payload of the frame, a JSON string.
|
|
59
|
+
|
|
60
|
+
Raises:
|
|
61
|
+
ValueError: the frame data is not a JSON object.
|
|
62
|
+
"""
|
|
63
|
+
self.event = event
|
|
64
|
+
self.raw_data = data
|
|
65
|
+
fields = json.loads(data) if data else {}
|
|
66
|
+
if not isinstance(fields, dict):
|
|
67
|
+
raise ValueError("unexpected sse data, not a json object: %s" % data)
|
|
68
|
+
if event in EVENT_NAME_TO_EVENT_TYPE:
|
|
69
|
+
self.eventType = EVENT_NAME_TO_EVENT_TYPE[event]
|
|
70
|
+
else:
|
|
71
|
+
self.eventType = fields.get("eventType")
|
|
72
|
+
self.subscribeType = fields.get("subscribeType", 0)
|
|
73
|
+
self.contentType = fields.get("contentType", "")
|
|
74
|
+
self.payload = fields.get("payload", "")
|
|
75
|
+
self.requestId = fields.get("requestId", "")
|
|
76
|
+
self.timestamp = fields.get("timestamp", 0)
|
|
77
|
+
|
|
78
|
+
def __str__(self):
|
|
79
|
+
return ("event:%s, eventType:%s, subscribeType:%s, contentType:%s, "
|
|
80
|
+
"requestId:%s, timestamp:%s, payload:%s") % (
|
|
81
|
+
self.event, self.eventType, self.subscribeType, self.contentType,
|
|
82
|
+
self.requestId, self.timestamp, self.payload)
|
|
83
|
+
|
|
84
|
+
__repr__ = __str__
|
webull/data/__init__.py
CHANGED
webull/trade/__init__.py
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
__version__ = '3.
|
|
1
|
+
__version__ = '3.1.1'
|
webull/trade/common/currency.py
CHANGED
|
@@ -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.4.dist-info → webull_openapi_python_sdk-3.1.1.dist-info}/METADATA
RENAMED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: webull-openapi-python-sdk
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.1.1
|
|
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"
|
{webull_openapi_python_sdk-3.0.4.dist-info → webull_openapi_python_sdk-3.1.1.dist-info}/RECORD
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
samples/__init__.py,sha256=
|
|
1
|
+
samples/__init__.py,sha256=lmDIxaFmSp0AjpogkMZtaIakitn7fHM4TDvV5XVgm9k,22
|
|
2
2
|
samples/account/__init__.py,sha256=eoZ6GfifbqhMLNzjlqRDVil-yyBkOmVN9ujSgJWNBlY,15
|
|
3
3
|
samples/account/account_client.py,sha256=vwh-nI_JnjwcIeOr1sQPMzG8pAqZwliUusE49ZmYE3s,1796
|
|
4
4
|
samples/assets/__init__.py,sha256=eoZ6GfifbqhMLNzjlqRDVil-yyBkOmVN9ujSgJWNBlY,15
|
|
@@ -18,13 +18,14 @@ samples/screener/screener_client.py,sha256=R9LApEv9gZhn0RU3Jy4u3b-64FdvoMRf3gZpp
|
|
|
18
18
|
samples/trade/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
19
19
|
samples/trade/trade_client.py,sha256=LyWSvZJH4ByCkRORqP9WdkXfx65A2b6fhc9_GzL8DOM,6258
|
|
20
20
|
samples/trade/trade_client_v2.py,sha256=IO-zmRiUnCmIetTdiYunPh8jVK2VaPrOR77Dwvz1auY,10771
|
|
21
|
-
samples/trade/trade_client_v3.py,sha256=
|
|
21
|
+
samples/trade/trade_client_v3.py,sha256=Q45x3EfgNZs_KrNy-qVgZEIf06T9sFYJW_aa79X6Ryw,36450
|
|
22
22
|
samples/trade/trade_client_v3_event.py,sha256=91HlT04KlK8Q5gUnsB8F5ErCFdJRnpDABKkBfYRc-YE,3932
|
|
23
23
|
samples/trade/trade_event_client.py,sha256=ni7OEc4nnz2Hpbh0Kzl6DXB-FuDPc2UGBaLFnCrdFZ4,2824
|
|
24
|
+
samples/trade/trade_event_sse_client.py,sha256=b_D3QiTiXD9_nky55tAFKPzxAtUDirsWfpx5693skoI,2781
|
|
24
25
|
samples/watchlist/__init__.py,sha256=rtV5s4_CJgDAT4DGEJa_pNLJU71Wdr5OLz_IQ1EajFQ,567
|
|
25
26
|
samples/watchlist/watchlist_client.py,sha256=lpzJs7SXuSka2KKkJ0u9s83A9iHta5qrjvIdkbfNcwg,3246
|
|
26
|
-
webull/__init__.py,sha256=
|
|
27
|
-
webull/core/__init__.py,sha256=
|
|
27
|
+
webull/__init__.py,sha256=lmDIxaFmSp0AjpogkMZtaIakitn7fHM4TDvV5XVgm9k,22
|
|
28
|
+
webull/core/__init__.py,sha256=UKPa8RYyH4jt_0dEzmqPqumRzsZxA-mtLhA1Hm9Axro,225
|
|
28
29
|
webull/core/client.py,sha256=zxSBiII9KDxc5tHpTerJfV_PKPt8E9e3oTOpiakAtJw,16758
|
|
29
30
|
webull/core/compat.py,sha256=_r6Y_f3vTo_DoxOaCvLjnvOo1KRkD2Z9kXSh8OijEIA,3088
|
|
30
31
|
webull/core/headers.py,sha256=Wj2zev1XYyYsy2b9YKnoK3GqjVsXZO_o2WziMmuVBTw,2061
|
|
@@ -85,12 +86,17 @@ webull/core/retry/backoff_strategy.py,sha256=PMJe8Kwvf3-hV30_-zhcbJ3egBedgiMIQa8
|
|
|
85
86
|
webull/core/retry/retry_condition.py,sha256=Hel380uhtcgmrK0NZiuY015vyBQWzM2dv4npjoMrv7A,8020
|
|
86
87
|
webull/core/retry/retry_policy.py,sha256=y1Kwc7lw1N4sgvR71AcUbsv8cYYLAJRdDMx7VWO6ubs,2549
|
|
87
88
|
webull/core/retry/retry_policy_context.py,sha256=rVAqF6NE6Aw-OUJY1TaxEhSLLCuYe8Kfs6Poqol0WOk,2036
|
|
89
|
+
webull/core/sse/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
90
|
+
webull/core/sse/default_retry_policy.py,sha256=MulainWSyDU_bZnXgUCG_NjhxAgJ9TLnWYuKDnYpW7A,5213
|
|
91
|
+
webull/core/sse/signature_composer.py,sha256=lrkto7bopv4gHpPe3P6qiHuNfZsIHObmsXEEYMYRVk4,2746
|
|
92
|
+
webull/core/sse/sse_parser.py,sha256=O18YikkmOPqkEzWWm6AXy1b5HfO4n6C_iL3nTymmDb8,2334
|
|
93
|
+
webull/core/sse/subscribe_response.py,sha256=7EopPitvAgbUMkfLSNicCNJoh653ZwBeq2mUQyQq6-4,3134
|
|
88
94
|
webull/core/utils/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
89
95
|
webull/core/utils/common.py,sha256=bb64grSP7PjaAIe8YYKDNzQ4qwgN7-qW0r24idTEqEY,2177
|
|
90
96
|
webull/core/utils/data.py,sha256=YUyoWY68_2RkKanh3jsDscgGx__FIPh5VNEGXr1Qotc,852
|
|
91
97
|
webull/core/utils/desensitize.py,sha256=186BKVDomhhKnIi_4-1bWJ7P5s01rStjeIwJkTEGoIA,952
|
|
92
98
|
webull/core/utils/validation.py,sha256=WXNBtJSvKfZ4qX40ke1rOMcu8TyYRemKsLog_t_T6tQ,2192
|
|
93
|
-
webull/data/__init__.py,sha256=
|
|
99
|
+
webull/data/__init__.py,sha256=IDaSX_WgD-0Fz54mk5hWvsI5nYud_6Q1K-8FccUqZ7Q,38
|
|
94
100
|
webull/data/data_client.py,sha256=6RLUr7Wsfs8bHaM8EbQBn8Xu8JcuTRap15SGXNSTQ6s,2605
|
|
95
101
|
webull/data/data_streaming_client.py,sha256=kLKjFH4INREkPIjw6efPwnHGHWIDJn42IEsQam0njb8,4623
|
|
96
102
|
webull/data/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
@@ -251,15 +257,16 @@ webull/data/request/watchlist/get_watchlist_request.py,sha256=AC59m2-5I78ctAcTUh
|
|
|
251
257
|
webull/data/request/watchlist/remove_watchlist_instruments_request.py,sha256=Fr9whov0qTCSINYSi_eDbvIhZmqdm5p7XW-X-eyICwk,1472
|
|
252
258
|
webull/data/request/watchlist/update_watchlist_instruments_request.py,sha256=OYuF3dYQJAZLf0FkB3i9SxwG6Zy9ZUaiBvsu5flKhvA,1514
|
|
253
259
|
webull/data/request/watchlist/update_watchlist_request.py,sha256=vGWnDZoK3bT9NKLJ7TO4rqlDqcOemj0HOuARTeAGnS0,1459
|
|
254
|
-
webull/trade/__init__.py,sha256=
|
|
260
|
+
webull/trade/__init__.py,sha256=lmDIxaFmSp0AjpogkMZtaIakitn7fHM4TDvV5XVgm9k,22
|
|
255
261
|
webull/trade/trade_client.py,sha256=c2SWGi0ATix5U2ZRWgsx4p4CJKmGy2qPkq1Pn2ndN0s,2279
|
|
256
262
|
webull/trade/trade_events_client.py,sha256=sHoKPKQQ2Ye_c9tt9MYxFeza3T5lLR5VosNro7H1gN4,9748
|
|
263
|
+
webull/trade/trade_events_sse_client.py,sha256=UTOhe081qQKjWLIV5_tkEen9f3Of1euBMHU42LR2XNw,20981
|
|
257
264
|
webull/trade/common/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
258
265
|
webull/trade/common/account_type.py,sha256=haVAB33MERN6XyPsbrfVQhK9_CpU90VltI6_KDkxzlE,715
|
|
259
266
|
webull/trade/common/category.py,sha256=lrSKMO11wMpw9iWWeefTdWXedJAFfWRlJ76swfqVP0c,947
|
|
260
267
|
webull/trade/common/combo_ticker_type.py,sha256=lvyH9Pk3QTBKSwY4N_bpWFdwAeOBPKH2ZEsCF6lfkzg,748
|
|
261
268
|
webull/trade/common/combo_type.py,sha256=yC7KKF-xjtw9YzD49ijph-sq8W98HRBRefGK7ovJaDM,1084
|
|
262
|
-
webull/trade/common/currency.py,sha256=
|
|
269
|
+
webull/trade/common/currency.py,sha256=LDzG1_GRIrNIyAIm9ySYdVx22rkvxc0VM7QOJYQgPsk,767
|
|
263
270
|
webull/trade/common/forbid_reason.py,sha256=S3lfFEJrsfdn-qxvbkqI8fi97n1qq6Sy7AUaS0SA5MM,983
|
|
264
271
|
webull/trade/common/instrument_type.py,sha256=HBBGIuPE9wY5ciykxQtZ7Q60x7hbPyMynOMBz876_Yc,863
|
|
265
272
|
webull/trade/common/markets.py,sha256=eZ_vH4OJupCqOJS5vgAparYysqm38EFjrjDj2C0XkzQ,753
|
|
@@ -334,7 +341,7 @@ webull/trade/request/v3/place_order_request.py,sha256=4WadcssswvLleaIw4DAuUo4Y9C
|
|
|
334
341
|
webull/trade/request/v3/preview_order_request.py,sha256=40IAlgfT11B1hVCQgtTKxkS6BsPxKvYkAw6y_v2YZ_0,1127
|
|
335
342
|
webull/trade/request/v3/replace_order_request.py,sha256=vaC1Y6y10_MITkAweCwAi4Lo80cBOxWGFnGubPrGKAQ,1207
|
|
336
343
|
webull/trade/trade/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
337
|
-
webull/trade/trade/account_info.py,sha256=
|
|
344
|
+
webull/trade/trade/account_info.py,sha256=89Lvr4FGzVOIapMCnUaQbMhDDNrMhRoejTzcXv_hqig,3574
|
|
338
345
|
webull/trade/trade/activity.py,sha256=ppPuJ_8uFzGqSvipLxogJ5_u75qAqSUkOWu0D8TwSvs,7882
|
|
339
346
|
webull/trade/trade/order_operation.py,sha256=QrL4Da87RTOSupiAbuXtZigo9602Byp14DQGyR99hkI,12849
|
|
340
347
|
webull/trade/trade/trade_calendar.py,sha256=rGSiR5GZggQnZOmmpbC-06trgPQgFTvdpUzGMpw2ycw,1415
|
|
@@ -344,9 +351,9 @@ webull/trade/trade/v2/account_info_v2.py,sha256=TX-BskDxag52Om-RY803mOThZUtN1j2G
|
|
|
344
351
|
webull/trade/trade/v2/order_operation_v2.py,sha256=ZWH-6dp5rvokb5YX5HO2Op-KPLjGR4gpJ06Kc_IUilQ,12816
|
|
345
352
|
webull/trade/trade/v3/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
346
353
|
webull/trade/trade/v3/order_operation_v3.py,sha256=0tYdvcUIht4PNxZfAZLB4BlvgW5_kOFMzQhiL9YTJU4,15382
|
|
347
|
-
webull_openapi_python_sdk-3.
|
|
348
|
-
webull_openapi_python_sdk-3.
|
|
349
|
-
webull_openapi_python_sdk-3.
|
|
350
|
-
webull_openapi_python_sdk-3.
|
|
351
|
-
webull_openapi_python_sdk-3.
|
|
352
|
-
webull_openapi_python_sdk-3.
|
|
354
|
+
webull_openapi_python_sdk-3.1.1.dist-info/licenses/LICENSE,sha256=ALOnsLtb1aHxmDJg3-oMi0BO-i-cjfyZaOBfnnavKMc,11359
|
|
355
|
+
webull_openapi_python_sdk-3.1.1.dist-info/licenses/NOTICE,sha256=X5TApte6CPV10b96Cb70IRLusXmiRmK_R-dB-1tQM_I,2018
|
|
356
|
+
webull_openapi_python_sdk-3.1.1.dist-info/METADATA,sha256=RLluNi62-OfZ8L9QWmoAhh9WyVX0wR0GU6p9CWvNInA,1253
|
|
357
|
+
webull_openapi_python_sdk-3.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
358
|
+
webull_openapi_python_sdk-3.1.1.dist-info/top_level.txt,sha256=h8pEjNDGWS2ZUZ2vYFpUShoMQT0ZRIQaD57QJWD8_aI,15
|
|
359
|
+
webull_openapi_python_sdk-3.1.1.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|