Skip to content

Commit 445ee5d

Browse files
Adjust logging and examples; add pylint check (#144)
1 parent 24ad552 commit 445ee5d

12 files changed

Lines changed: 712 additions & 79 deletions

.pre-commit-config.yaml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,16 @@ repos:
4949
- --select=E9,F63,F7,F82
5050
- --show-source
5151
- --statistics
52+
- repo: https://github.com/pycqa/pylint
53+
rev: v2.17.0
54+
hooks:
55+
- id: pylint
56+
name: pylint
57+
types: [python]
58+
exclude: ^examples/|^tests/|^setup.py$
59+
args:
60+
- --rcfile=pyproject.toml
61+
- -d=R0801 # ignore duplicate code
5262
- repo: https://github.com/astral-sh/ruff-pre-commit
5363
rev: v0.0.282
5464
hooks:

docs/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
1818

1919
project = "python-kraken-sdk"
20-
copyright = "2023, Benjamin Thomas Schwertfeger" # noqa: A001
20+
copyright = "2023, Benjamin Thomas Schwertfeger" # noqa: A001 # pylint: disable=redefined-builtin
2121
author = "Benjamin Thomas Schwertfeger"
2222

2323
# to import the package

examples/futures_ws_examples.py

Lines changed: 25 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -67,30 +67,31 @@ async def on_message(self: "Client", msg: Union[list, dict]) -> None:
6767
# ...
6868

6969
# _____Private_Websocket_Feeds_________________
70-
client_auth = Client(key=key, secret=secret)
71-
# print(client_auth.get_available_private_subscription_feeds())
72-
73-
# subscribe to a private/authenticated websocket feed
74-
await client_auth.subscribe(feed="fills")
75-
await client_auth.subscribe(feed="open_positions")
76-
# await client_auth.subscribe(feed='open_orders')
77-
# await client_auth.subscribe(feed='open_orders_verbose')
78-
# await client_auth.subscribe(feed='deposits_withdrawals')
79-
# await client_auth.subscribe(feed='account_balances_and_margins')
80-
# await client_auth.subscribe(feed='balances')
81-
# await client_auth.subscribe(feed='account_log')
82-
# await client_auth.subscribe(feed='notifications_auth')
83-
84-
# authenticated clients can also subscribe to public feeds
85-
# await client_auth.subscribe(feed='ticker', products=['PI_XBTUSD', 'PF_ETHUSD'])
86-
87-
# time.sleep(1)
88-
# unsubscribe from a private/authenticated websocket feed
89-
await client_auth.unsubscribe(feed="fills")
90-
await client_auth.unsubscribe(feed="open_positions")
91-
# ...
92-
93-
while not client.exception_occur and not client_auth.exception_occur:
70+
if key and secret:
71+
client_auth = Client(key=key, secret=secret)
72+
# print(client_auth.get_available_private_subscription_feeds())
73+
74+
# subscribe to a private/authenticated websocket feed
75+
await client_auth.subscribe(feed="fills")
76+
await client_auth.subscribe(feed="open_positions")
77+
# await client_auth.subscribe(feed='open_orders')
78+
# await client_auth.subscribe(feed='open_orders_verbose')
79+
# await client_auth.subscribe(feed='deposits_withdrawals')
80+
# await client_auth.subscribe(feed='account_balances_and_margins')
81+
# await client_auth.subscribe(feed='balances')
82+
# await client_auth.subscribe(feed='account_log')
83+
# await client_auth.subscribe(feed='notifications_auth')
84+
85+
# authenticated clients can also subscribe to public feeds
86+
# await client_auth.subscribe(feed='ticker', products=['PI_XBTUSD', 'PF_ETHUSD'])
87+
88+
# time.sleep(1)
89+
# unsubscribe from a private/authenticated websocket feed
90+
await client_auth.unsubscribe(feed="fills")
91+
await client_auth.unsubscribe(feed="open_positions")
92+
# ...
93+
94+
while not client.exception_occur: # and not client_auth.exception_occur:
9495
await asyncio.sleep(6)
9596

9697

examples/spot_trading_bot_template_v2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
"""
77
Module that provides a template to build a Spot trading algorithm using the
8-
python-kraken-sdk and Kraken Spot websocket API v1.
8+
python-kraken-sdk and Kraken Spot websocket API v2.
99
"""
1010

1111
from __future__ import annotations

examples/spot_ws_examples_v1.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -82,18 +82,19 @@ async def on_message(self: Client, message: Union[list, dict]) -> None:
8282
await client.unsubscribe(subscription={"name": "spread"}, pair=["DOT/USD"])
8383
# ...
8484

85-
client_auth = Client(key=key, secret=secret)
86-
# print(client_auth.active_private_subscriptions)
87-
# print(client_auth.private_channel_names) # list private channel names
88-
# when using the authenticated client, you can also subscribe to public feeds
89-
await client_auth.subscribe(subscription={"name": "ownTrades"})
90-
await client_auth.subscribe(subscription={"name": "openOrders"})
91-
92-
await asyncio.sleep(2)
93-
await client_auth.unsubscribe(subscription={"name": "ownTrades"})
94-
await client_auth.unsubscribe(subscription={"name": "openOrders"})
95-
96-
while not client.exception_occur and not client_auth.exception_occur:
85+
if key and secret:
86+
client_auth = Client(key=key, secret=secret)
87+
# print(client_auth.active_private_subscriptions)
88+
# print(client_auth.private_channel_names) # list private channel names
89+
# when using the authenticated client, you can also subscribe to public feeds
90+
await client_auth.subscribe(subscription={"name": "ownTrades"})
91+
await client_auth.subscribe(subscription={"name": "openOrders"})
92+
93+
await asyncio.sleep(2)
94+
await client_auth.unsubscribe(subscription={"name": "ownTrades"})
95+
await client_auth.unsubscribe(subscription={"name": "openOrders"})
96+
97+
while not client.exception_occur: # and not client_auth.exception_occur:
9798
await asyncio.sleep(6)
9899

99100

examples/spot_ws_examples_v2.py

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -90,19 +90,20 @@ async def on_message(self: Client, message: dict) -> None:
9090
)
9191
# ...
9292

93-
# Per default, the authenticated client starts two websocket connections,
94-
# one for authenticated and one for public messages. If there is no need
95-
# for a public connection, it can be disabled using the ``no_public``
96-
# parameter.
97-
client_auth = Client(key=key, secret=secret, no_public=True)
98-
# print(client_auth.private_channel_names) # … list private channel names
99-
# when using the authenticated client, you can also subscribe to public feeds
100-
await client_auth.subscribe(params={"channel": "executions"})
101-
102-
await asyncio.sleep(5)
103-
await client_auth.unsubscribe(params={"channel": "executions"})
104-
105-
while not client.exception_occur and not client_auth.exception_occur:
93+
if key and secret:
94+
# Per default, the authenticated client starts two websocket connections,
95+
# one for authenticated and one for public messages. If there is no need
96+
# for a public connection, it can be disabled using the ``no_public``
97+
# parameter.
98+
client_auth = Client(key=key, secret=secret, no_public=True)
99+
# print(client_auth.private_channel_names) # … list private channel names
100+
# when using the authenticated client, you can also subscribe to public feeds
101+
await client_auth.subscribe(params={"channel": "executions"})
102+
103+
await asyncio.sleep(5)
104+
await client_auth.unsubscribe(params={"channel": "executions"})
105+
106+
while not client.exception_occur: # and not client_auth.exception_occur:
106107
await asyncio.sleep(6)
107108

108109

kraken/futures/user.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@
1010

1111
from typing import TYPE_CHECKING, Optional, Union
1212

13+
from kraken.base_api import KrakenBaseFuturesAPI, defined
14+
1315
if TYPE_CHECKING:
1416
import requests
1517

16-
from kraken.base_api import KrakenBaseFuturesAPI, defined
17-
1818

1919
class User(KrakenBaseFuturesAPI):
2020
"""

kraken/futures/websocket/__init__.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
from kraken.exceptions import KrakenException
2222

2323
if TYPE_CHECKING:
24-
# to avoid circular import for type checking
2524
from kraken.futures import KrakenFuturesWSClient
2625

2726

@@ -89,10 +88,10 @@ async def __run(self: ConnectFuturesWebsocket, event: asyncio.Event) -> None:
8988
try:
9089
_msg = await asyncio.wait_for(self.__socket.recv(), timeout=15)
9190
except asyncio.TimeoutError:
92-
logging.debug(
93-
"Timeout error in {endpoint}",
94-
extra={"endpoint": self.__ws_endpoint},
95-
) # important
91+
logging.debug( # important
92+
"Timeout error in %s",
93+
self.__ws_endpoint,
94+
)
9695
except asyncio.CancelledError:
9796
logging.exception("asyncio.CancelledError")
9897
keep_alive = False
@@ -138,8 +137,9 @@ async def __reconnect(self: ConnectFuturesWebsocket) -> None:
138137

139138
reconnect_wait: float = self.__get_reconnect_wait(self.__reconnect_num)
140139
logging.debug(
141-
"asyncio sleep reconnect_wait={wait} s reconnect_num={num}",
142-
extra={"wait": reconnect_wait, "num": self.__reconnect_num},
140+
"asyncio sleep reconnect_wait=%f s reconnect_num=%d",
141+
reconnect_wait,
142+
self.__reconnect_num,
143143
)
144144
await asyncio.sleep(reconnect_wait)
145145
logging.debug("asyncio sleep done")
@@ -165,7 +165,7 @@ async def __reconnect(self: ConnectFuturesWebsocket) -> None:
165165
message = f"{task} got an exception {task.exception()}\n {task.get_stack()}"
166166
logging.warning(message)
167167
for process in pending:
168-
logging.warning("pending {proc}", extra={"proc": process})
168+
logging.warning("pending %s", process)
169169
try:
170170
process.cancel()
171171
except asyncio.CancelledError:
@@ -181,8 +181,8 @@ async def __recover_subscription_req_msg(
181181
event: asyncio.Event,
182182
) -> None:
183183
logging.info(
184-
"Recover subscriptions {subscriptions} waiting.",
185-
extra={"subscriptions": self.__subscriptions},
184+
"Recover subscriptions %s waiting.",
185+
self.__subscriptions,
186186
)
187187
await event.wait()
188188

@@ -191,11 +191,11 @@ async def __recover_subscription_req_msg(
191191
await self.send_message(deepcopy(sub), private=True)
192192
elif sub["feed"] in self.__client.get_available_public_subscription_feeds():
193193
await self.send_message(deepcopy(sub), private=False)
194-
logging.info("{sub}: OK", extra={"sub": sub})
194+
logging.info("%s: OK", sub)
195195

196196
logging.info(
197-
"Recover subscriptions {subscriptions} done.",
198-
extra={"subscriptions": self.__subscriptions},
197+
"Recover subscriptions %s done.",
198+
self.__subscriptions,
199199
)
200200

201201
async def send_message(

kraken/spot/orderbook.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -306,8 +306,8 @@ async def on_book_update(
306306
message: list
307307
) -> None:
308308
book: Dict[str, Any] = self.get(pair="XBT/USD")
309-
ask: List[Tuple[str, str]] = list(book["ask"].items())
310-
bid: List[Tuple[str, str]] = list(book["bid"].items())
309+
ask: list[Tuple[str, str]] = list(book["ask"].items())
310+
bid: list[Tuple[str, str]] = list(book["bid"].items())
311311
# ask and bid are now in format [price, (volume, timestamp)]
312312
# … and include the whole orderbook
313313
"""

kraken/spot/websocket/connectors.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ async def __run(self: ConnectSpotWebsocketBase, event: asyncio.Event) -> None:
108108
None if not self.__is_auth else self.__client.get_ws_token()
109109
)
110110
self.LOG.debug(
111-
"Websocket token: {details}",
112-
extra={"details": self.ws_conn_details},
111+
"Websocket token: %s",
112+
self.ws_conn_details,
113113
)
114114

115115
async with websockets.connect( # pylint: disable=no-member
@@ -162,8 +162,9 @@ async def __run_forever(self: ConnectSpotWebsocketBase) -> None:
162162
except Exception as exc:
163163
traceback_: str = traceback.format_exc()
164164
logging.exception(
165-
"{exc}: {traceback}",
166-
extra={"exc": exc, "traceback": traceback_},
165+
"%s: %s",
166+
exc,
167+
traceback_,
167168
)
168169
await self.__callback({"error": traceback_})
169170
finally:
@@ -215,7 +216,7 @@ async def __reconnect(self: ConnectSpotWebsocketBase) -> None:
215216
message: str = f"{task} got an exception {task.exception()}\n {task.get_stack()}"
216217
self.LOG.warning(message)
217218
for process in pending:
218-
self.LOG.warning("pending {proc}", extra={"proc": process})
219+
self.LOG.warning("pending %s", process)
219220
try:
220221
process.cancel()
221222
except asyncio.CancelledError:
@@ -355,7 +356,7 @@ async def _recover_subscriptions(
355356
private = True
356357

357358
await self.client.send_message(cpy, private=private)
358-
self.LOG.info("{sub} OK", extra={"sub": sub})
359+
self.LOG.info("%s: OK", sub)
359360

360361
self.LOG.info("%s done.", log_msg)
361362

@@ -500,7 +501,7 @@ async def _recover_subscriptions(
500501

501502
for subscription in self._subscriptions:
502503
await self.client.subscribe(params=subscription)
503-
self.LOG.info("{subscription} OK", extra={"subscription": subscription})
504+
self.LOG.info("%s: OK", subscription)
504505

505506
self.LOG.info("%s done.", log_msg)
506507

0 commit comments

Comments
 (0)