Skip to content

Commit

Permalink
let the timeout be adjustable
Browse files Browse the repository at this point in the history
  • Loading branch information
btschwertfeger committed Dec 6, 2023
1 parent c7132c1 commit a03fe3d
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 36 deletions.
69 changes: 37 additions & 32 deletions kraken/base_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ class KrakenSpotBaseAPI:

URL: str = "https://api.kraken.com"
API_V: str = "/0"
TIMEOUT: int = 10

def __init__(
self: KrakenSpotBaseAPI,
Expand Down Expand Up @@ -259,14 +260,16 @@ def _request( # noqa: PLR0913 # pylint: disable=too-many-arguments
else extra_params
)

method = method.upper()
if method in {"GET", "DELETE"} and params:
METHOD: str = method.upper()
if METHOD in {"GET", "DELETE"} and params:
data_json: str = "&".join(
[f"{key}={params[key]}" for key in sorted(params)],
)
uri += f"?{data_json}".replace(" ", "%20")

headers: dict = {}
TIMEOUT: int = self.TIMEOUT if timeout != 10 else timeout
HEADERS: dict = {}

if auth:
if not self.__key or not self.__secret:
raise ValueError("Missing credentials.")
Expand All @@ -282,7 +285,7 @@ def _request( # noqa: PLR0913 # pylint: disable=too-many-arguments
content_type = "application/x-www-form-urlencoded; charset=utf-8"
sign_data = urllib.parse.urlencode(params)

headers.update(
HEADERS.update(
{
"Content-Type": content_type,
"API-Key": self.__key,
Expand All @@ -294,37 +297,37 @@ def _request( # noqa: PLR0913 # pylint: disable=too-many-arguments
},
)

url: str = f"{self.url}{uri}"
if method in {"GET", "DELETE"}:
URL: str = f"{self.url}{uri}"
if METHOD in {"GET", "DELETE"}:
return self.__check_response_data(
response=self.__session.request(
method=method,
url=url,
headers=headers,
timeout=timeout,
method=METHOD,
url=URL,
headers=HEADERS,
timeout=TIMEOUT,
),
return_raw=return_raw,
)

if do_json:
return self.__check_response_data(
response=self.__session.request(
method=method,
url=url,
headers=headers,
method=METHOD,
url=URL,
headers=HEADERS,
json=params,
timeout=timeout,
timeout=TIMEOUT,
),
return_raw=return_raw,
)

return self.__check_response_data(
response=self.__session.request(
method=method,
url=url,
headers=headers,
method=METHOD,
url=URL,
headers=HEADERS,
data=params,
timeout=timeout,
timeout=TIMEOUT,
),
return_raw=return_raw,
)
Expand Down Expand Up @@ -431,6 +434,7 @@ class KrakenFuturesBaseAPI:

URL: str = "https://futures.kraken.com"
SANDBOX_URL: str = "https://demo-futures.kraken.com"
TIMEOUT: int = 10

def __init__(
self: KrakenFuturesBaseAPI,
Expand Down Expand Up @@ -501,7 +505,7 @@ def _request( # noqa: PLR0913 # pylint: disable=too-many-arguments
:return: The response
:rtype: dict[str, Any] | list[dict[str, Any]] | list[str] | requests.Response
"""
method = method.upper()
METHOD: str = method.upper()

post_string: str = ""
listed_params: list[str]
Expand Down Expand Up @@ -531,12 +535,13 @@ def _request( # noqa: PLR0913 # pylint: disable=too-many-arguments
else:
query_params = {}

headers: dict = {}
TIMEOUT: int = self.TIMEOUT if timeout == 10 else timeout
HEADERS: dict = {}
if auth:
if not self.__key or not self.__secret:
raise ValueError("Missing credentials")
nonce: str = str(int(time.time() * 100_000_000))
headers.update(
HEADERS.update(
{
"Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
"Nonce": nonce,
Expand All @@ -549,38 +554,38 @@ def _request( # noqa: PLR0913 # pylint: disable=too-many-arguments
},
)

if method in {"GET", "DELETE"}:
if METHOD in {"GET", "DELETE"}:
return self.__check_response_data(
response=self.__session.request(
method=method,
method=METHOD,
url=f"{self.url}{uri}"
if not query_string
else f"{self.url}{uri}?{query_string}",
headers=headers,
timeout=timeout,
headers=HEADERS,
timeout=TIMEOUT,
),
return_raw=return_raw,
)

if method == "PUT":
if METHOD == "PUT":
return self.__check_response_data(
response=self.__session.request(
method=method,
method=METHOD,
url=f"{self.url}{uri}",
params=str.encode(post_string),
headers=headers,
timeout=timeout,
headers=HEADERS,
timeout=TIMEOUT,
),
return_raw=return_raw,
)

return self.__check_response_data(
response=self.__session.request(
method=method,
method=METHOD,
url=f"{self.url}{uri}?{post_string}",
data=str.encode(post_string),
headers=headers,
timeout=timeout,
headers=HEADERS,
timeout=TIMEOUT,
),
return_raw=return_raw,
)
Expand Down
3 changes: 3 additions & 0 deletions kraken/futures/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -484,6 +484,9 @@ def get_execution_events(
- https://docs.futures.kraken.com/#http-api-history-account-history-get-execution-events
(If you are facing some timeout error, just set the clients attribute
``TIMEOUT`` temporarily to the desired amount in seconds.)
:param before: Filter by time
:type before: int, optional
:param continuation_token: Token that can be used to continue requesting
Expand Down
8 changes: 8 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,10 @@ ignore-names = [
"trailingStopMaxDeviation",
"subaccountUid",
"ConnectSpotWebsocket",
"METHOD",
"TIMEOUT",
"URL",
"HEADERS",
]

[tool.ruff.pylint]
Expand Down Expand Up @@ -527,6 +531,10 @@ good-names = [
"trailingStopMaxDeviation",
"subaccountUid",
"ConnectSpotWebsocket",
"METHOD",
"TIMEOUT",
"URL",
"HEADERS",
]

# Good variable names regexes, separated by a comma. If names match any regex,
Expand Down
4 changes: 2 additions & 2 deletions tests/futures/test_futures_base_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ def test_KrakenFuturesBaseAPI_without_exception() -> None:
KrakenFuturesBaseAPI(
key="fake",
secret="fake",
)._request(method="POST", uri="/derivatives/api/v3/sendorder", auth=True)
)._request(METHOD="POST", uri="/derivatives/api/v3/sendorder", auth=True)

result: dict = (
KrakenFuturesBaseAPI(key="fake", secret="fake", use_custom_exceptions=False) # type: ignore[union-attr]
._request(method="POST", uri="/derivatives/api/v3/sendorder", auth=True)
._request(METHOD="POST", uri="/derivatives/api/v3/sendorder", auth=True)
.json()
)

Expand Down
3 changes: 3 additions & 0 deletions tests/futures/test_futures_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,15 @@ def test_get_execution_events(futures_auth_user: User) -> None:
assert "elements" in result


@pytest.mark.wip()
@pytest.mark.futures()
@pytest.mark.futures_auth()
@pytest.mark.futures_user()
def test_get_order_events(futures_auth_user: User) -> None:
"""
Checks the ``get_order_events`` endpoint.
"""
futures_auth_user.TIMEOUT = 30
result: dict = futures_auth_user.get_order_events(
tradeable="PF_SOLUSD",
since=1668989233,
Expand All @@ -127,6 +129,7 @@ def test_get_order_events(futures_auth_user: User) -> None:
)
assert isinstance(result, dict)
assert "elements" in result
futures_auth_user.TIMEOUT = 10


@pytest.mark.futures()
Expand Down
4 changes: 2 additions & 2 deletions tests/spot/test_spot_base_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ def test_KrakenSpotBaseAPI_without_exception() -> None:
KrakenSpotBaseAPI(
key="fake",
secret="fake",
)._request(method="POST", uri="/private/AddOrder", auth=True)
)._request(METHOD="POST", uri="/private/AddOrder", auth=True)

assert KrakenSpotBaseAPI(
key="fake",
secret="fake",
use_custom_exceptions=False,
)._request(method="POST", uri="/private/AddOrder", auth=True).json() == {
)._request(METHOD="POST", uri="/private/AddOrder", auth=True).json() == {
"error": ["EAPI:Invalid key"],
}

Expand Down

0 comments on commit a03fe3d

Please sign in to comment.