Skip to content

Commit 24ad552

Browse files
Integrate and apply ruff (#142)
1 parent ef0f49f commit 24ad552

53 files changed

Lines changed: 1655 additions & 1707 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ htmlcov/
5353
.coverage
5454
.coverage.*
5555
.cache
56+
.ruff_cache
5657
nosetests.xml
5758
coverage.xml
5859
pytest.xml

.pre-commit-config.yaml

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,16 +49,13 @@ repos:
4949
- --select=E9,F63,F7,F82
5050
- --show-source
5151
- --statistics
52-
- repo: https://github.com/pycqa/pylint
53-
rev: v2.17.0
52+
- repo: https://github.com/astral-sh/ruff-pre-commit
53+
rev: v0.0.282
5454
hooks:
55-
- id: pylint
56-
name: pylint
57-
types: [python]
58-
exclude: ^examples/|^tests/|^setup.py$
55+
- id: ruff
5956
args:
60-
- --rcfile=pyproject.toml
61-
- -d=R0801 # ignore duplicate code
57+
- --fix
58+
- --exit-non-zero-on-fix
6259
- repo: https://github.com/pre-commit/mirrors-mypy
6360
rev: v1.2.0
6461
hooks:

CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44

55
[Full Changelog](https://github.com/btschwertfeger/python-kraken-sdk/compare/v1.5.0...HEAD)
66

7+
**Breaking changes:**
8+
9+
- Integrate Websockets API v2 [\#130](https://github.com/btschwertfeger/python-kraken-sdk/issues/130)
10+
- Let `kraken.spot.OrderbookClient` use Spot Websocket API v2 [\#139](https://github.com/btschwertfeger/python-kraken-sdk/pull/139) ([btschwertfeger](https://github.com/btschwertfeger))
11+
- Integrate Kraken Websockets API v2; add `kraken.spot.KrakenSpotWebsocketClientV2`; internals [\#131](https://github.com/btschwertfeger/python-kraken-sdk/pull/131) ([btschwertfeger](https://github.com/btschwertfeger))
12+
713
**Implemented enhancements:**
814

915
- Add `/private/AccountTransfer` endpoint to `kraken.spot.User` [\#128](https://github.com/btschwertfeger/python-kraken-sdk/issues/128)

Makefile

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ PYTEST_OPTS := -vv --junit-xml=pytest.xml
99
PYTEST_COV_OPTS := $(PYTEST_OPTS) --cov --cov-report=xml:coverage.xml --cov-report=term
1010
TEST_DIR := tests
1111

12-
.PHONY := help build rebuild doc install dev test tests test-wip coverage doctest pre-commit changelog clean
12+
.PHONY := help build rebuild doc install dev test tests test-wip coverage doctest pre-commit ruff ruff-fix changelog clean
1313

1414
help:
1515
@grep "^##" Makefile | sed -e "s/##//"
@@ -71,6 +71,14 @@ doctest:
7171
pre-commit:
7272
@pre-commit run -a
7373

74+
## ruff Run ruff without fix
75+
ruff:
76+
ruff check .
77+
78+
## ruff-fix Run ruff with fix
79+
ruff-fix:
80+
ruff check . --fix
81+
7482
## changelog Generate the changelog
7583
##
7684
changelog:
@@ -92,7 +100,9 @@ clean:
92100
python_kraken_sdk.egg-info \
93101
docs/_build \
94102
.vscode \
95-
.mypy_cache
103+
.cache \
104+
.mypy_cache \
105+
.ruff_cache
96106

97107
rm -f .coverage coverage.xml pytest.xml mypy.xml \
98108
kraken/_version.py \

README.md

Lines changed: 20 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
[![Generic badge](https://img.shields.io/badge/python-3.7_|_3.8_|_3.9_|_3.10_|_3.11-blue.svg)](https://shields.io/)
88
[![Downloads](https://static.pepy.tech/personalized-badge/python-kraken-sdk?period=total&units=abbreviation&left_color=grey&right_color=orange&left_text=downloads)](https://pepy.tech/project/python-kraken-sdk)
99

10+
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)
1011
[![Typing](https://img.shields.io/badge/typing-mypy-informational)](https://mypy-lang.org/)
1112
[![CodeQL](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/codeql.yaml/badge.svg?branch=master)](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/codeql.yaml)
1213
[![CI/CD](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/cicd.yaml/badge.svg?branch=master)](https://github.com/btschwertfeger/python-kraken-sdk/actions/workflows/cicd.yaml)
@@ -90,13 +91,13 @@ release specific READMEs and changelogs.
9091

9192
# 🛠 Installation and setup
9293

93-
### 1. Install the Python module:
94+
### 1. Install the package into the desired environment
9495

9596
```bash
9697
python3 -m pip install python-kraken-sdk
9798
```
9899

99-
### 2. Register at Kraken and generate API Keys:
100+
### 2. Register at [Kraken](https://www.kraken.com) and generate API keys
100101

101102
- Spot Trading: https://www.kraken.com/u/security/api
102103
- Futures Trading: https://futures.kraken.com/trade/settings/api (see _[help](https://docs.futures.kraken.com/#introduction-generate-api-keys)_)
@@ -146,12 +147,12 @@ def main():
146147
user = User(key=key, secret=secret)
147148
print(user.get_account_balance())
148149
print(user.get_open_orders())
149-
# ...
150+
#
150151

151152
# ____MARKET____
152153
market = Market()
153154
print(market.get_ticker(pair="BTCUSD"))
154-
# ...
155+
#
155156

156157
# ____TRADE_________________________
157158
trade = Trade(key=key, secret=secret)
@@ -162,7 +163,7 @@ def main():
162163
pair="BTC/EUR",
163164
price=20000
164165
))
165-
# ...
166+
#
166167

167168
# ____FUNDING___________________________
168169
funding = Funding(key=key, secret=secret)
@@ -172,7 +173,7 @@ def main():
172173
)
173174
)
174175
print(funding.cancel_withdraw(asset="DOT", refid="<some id>"))
175-
# ...
176+
#
176177

177178
# ____STAKING___________________________
178179
staking = Staking(key=key, secret=secret)
@@ -182,7 +183,7 @@ def main():
182183
asset="DOT", amount=20, method="polkadot-staked"
183184
)
184185
)
185-
# ...
186+
#
186187

187188
if __name__ == "__main__":
188189
main()
@@ -227,7 +228,7 @@ async def main():
227228

228229
print(message)
229230
# here we can access lots of methods, for example to create an order:
230-
# if self._is_auth: # only if the client is authenticated …
231+
# if self.is_auth: # only if the client is authenticated …
231232
# await self.send_message(
232233
# message={
233234
# "method": "add_order",
@@ -242,7 +243,7 @@ async def main():
242243
# },
243244
# }
244245
# )
245-
# ... it is also possible to call regular REST endpoints
246+
# it is also possible to call regular REST endpoints
246247
# but using the websocket messages is more efficient.
247248
# You can also un-/subscribe here using self.subscribe/self.unsubscribe.
248249

@@ -255,13 +256,13 @@ async def main():
255256
await client.subscribe(
256257
params={"channel": "book", "depth": 25, "symbol": ["BTC/USD"]}
257258
)
258-
# wait because unsubscribing is faster than unsubscribing ... (just for that example)
259+
# wait because unsubscribing is faster than unsubscribing (just for that example)
259260
await asyncio.sleep(3)
260-
# print(client.active_public_subscriptions) # to list active subscriptions
261+
# print(client.active_public_subscriptions) # to list active subscriptions
261262
await client.unsubscribe(
262263
params={"channel": "ticker", "symbol": ["BTC/USD", "DOT/USD"]}
263264
)
264-
# ...
265+
#
265266

266267
# Per default, the authenticated client starts two websocket connections,
267268
# one for authenticated and one for public messages. If there is no need
@@ -325,7 +326,7 @@ def main():
325326
print(user.get_open_orders())
326327
print(user.get_open_positions())
327328
print(user.get_subaccounts())
328-
# ...
329+
#
329330

330331
# ____MARKET____
331332
market = Market()
@@ -334,7 +335,7 @@ def main():
334335
priv_market = Market(key=key, secret=secret)
335336
print(priv_market.get_fee_schedules_vol())
336337
print(priv_market.get_execution_events())
337-
# ...
338+
#
338339

339340
# ____TRADE_________________________
340341
trade = Trade(key=key, secret=secret)
@@ -376,11 +377,11 @@ def main():
376377
symbol="pf_bchusd"
377378
)
378379
)
379-
# ...
380+
#
380381

381382
# ____FUNDING___________________________
382383
funding = Funding(key=key, secret=secret)
383-
# ...
384+
#
384385

385386
if __name__ == "__main__":
386387
main()
@@ -420,7 +421,7 @@ async def main():
420421
# subscribe to a public websocket feed
421422
await client.subscribe(feed="ticker", products=products)
422423
# await client.subscribe(feed="book", products=products)
423-
# ...
424+
#
424425

425426
# unsubscribe from a public websocket feed
426427
# await client.unsubscribe(feed="ticker", products=products)
@@ -433,7 +434,7 @@ async def main():
433434
await client_auth.subscribe(feed="fills")
434435
await client_auth.subscribe(feed="open_positions")
435436
await client_auth.subscribe(feed="open_orders")
436-
# ...
437+
#
437438

438439
# unsubscribe from a private/authenticated websocket feed
439440
await client_auth.unsubscribe(feed="fills")
@@ -445,7 +446,7 @@ if __name__ == "__main__":
445446
try:
446447
asyncio.run(main())
447448
except KeyboardInterrupt:
448-
# do some exception handling ...
449+
# do some exception handling
449450
pass
450451
```
451452

docs/conf.py

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,12 @@
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" # pylint: disable=redefined-builtin
20+
copyright = "2023, Benjamin Thomas Schwertfeger" # noqa: A001
2121
author = "Benjamin Thomas Schwertfeger"
2222

2323
# to import the package
2424
sys.path.insert(0, os.path.abspath(".."))
2525

26-
# import links
2726
rst_epilog = ""
2827
# Read link all targets from file
2928
with open("links.rst", encoding="utf-8") as f:
@@ -44,11 +43,6 @@
4443
templates_path = ["_templates"]
4544
exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", "links.rst"]
4645

47-
48-
def setup(app):
49-
"""Run during the Sphinx building process"""
50-
51-
5246
# -- Options for HTML output -------------------------------------------------
5347
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
5448

examples/futures_examples.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
logging.getLogger("requests").setLevel(logging.WARNING)
2222
logging.getLogger("urllib3").setLevel(logging.WARNING)
2323

24-
key = os.getenv("Futures_SANDBOX_KEY")
25-
secret = os.getenv("Futures_SANDBOX_SECRET")
24+
key = os.getenv("FUTURES_SANDBOX_KEY")
25+
secret = os.getenv("FUTURES_SANDBOX_SECRET")
2626

2727
# _ _ ___ _____ _____
2828
# | \ | |/ _ \_ _| ____|_
@@ -93,7 +93,7 @@ def user_examples() -> None:
9393
def trade_examples() -> None:
9494
"""Example Trade client usage"""
9595
raise ValueError(
96-
"Attention: Please check if you really want to test the trade endpoints!"
96+
"Attention: Please check if you really want to test the trade endpoints!",
9797
)
9898
trade = Trade(key=key, secret=secret, sandbox=True)
9999
print(trade.get_fills())
@@ -129,7 +129,7 @@ def trade_examples() -> None:
129129
"cliOrdId": 123456789,
130130
},
131131
],
132-
)
132+
),
133133
)
134134
print(trade.cancel_all_orders())
135135
print(trade.cancel_all_orders(symbol="pi_xbtusd"))
@@ -138,8 +138,11 @@ def trade_examples() -> None:
138138
print(trade.cancel_order(order_id="some order id"))
139139
print(
140140
trade.edit_order(
141-
orderId="some order id", size=300, limitPrice=401, stopPrice=350
142-
)
141+
orderId="some order id",
142+
size=300,
143+
limitPrice=401,
144+
stopPrice=350,
145+
),
143146
)
144147
print(trade.get_orders_status(orderIds=["orderid1", "orderid2"]))
145148
print(
@@ -149,7 +152,7 @@ def trade_examples() -> None:
149152
size=1,
150153
limitPrice=4,
151154
symbol="pf_bchusd",
152-
)
155+
),
153156
)
154157
print(
155158
trade.create_order(
@@ -159,7 +162,7 @@ def trade_examples() -> None:
159162
symbol="pf_bchusd",
160163
stopPrice=100,
161164
triggerSignal="mark",
162-
)
165+
),
163166
)
164167

165168

examples/futures_trading_bot_template.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,8 @@ class TradingBot(KrakenFuturesWSClient):
5555

5656
def __init__(self: TradingBot, config: dict) -> None:
5757
super().__init__( # initialize the KrakenFuturesWSClient
58-
key=config["key"], secret=config["secret"]
58+
key=config["key"],
59+
secret=config["secret"],
5960
)
6061
self.__config: dict = config
6162

@@ -90,7 +91,10 @@ async def on_message(self: TradingBot, msg: Union[list, dict]) -> None:
9091

9192
def save_exit(self: TradingBot, reason: Optional[str] = "") -> None:
9293
"""Controlled shutdown of the strategy"""
93-
logging.warning(f"Save exit triggered, reason: {reason}")
94+
logging.warning(
95+
"Save exit triggered, reason: {reason}",
96+
extra={"reason": reason},
97+
)
9498
# some ideas:
9599
# * save the bots data
96100
# * maybe close trades
@@ -143,10 +147,12 @@ async def __main(self: ManagedBot) -> None:
143147
self.__trading_strategy = TradingBot(config=self.__config)
144148

145149
await self.__trading_strategy.subscribe(
146-
feed="ticker", products=self.__config["products"]
150+
feed="ticker",
151+
products=self.__config["products"],
147152
)
148153
await self.__trading_strategy.subscribe(
149-
feed="book", products=self.__config["products"]
154+
feed="book",
155+
products=self.__config["products"],
150156
)
151157

152158
await self.__trading_strategy.subscribe(feed="fills")
@@ -168,9 +174,8 @@ async def __main(self: ManagedBot) -> None:
168174

169175
await asyncio.sleep(6)
170176
self.__trading_strategy.save_exit(
171-
reason="Left main loop because of exception in strategy."
177+
reason="Left main loop because of exception in strategy.",
172178
)
173-
return
174179

175180
def __check_credentials(self: ManagedBot) -> bool:
176181
"""Checks the user credentials and the connection to Kraken"""
@@ -205,14 +210,14 @@ def main() -> None:
205210
"key": os.getenv("FUTURES_API_KEY"),
206211
"secret": os.getenv("FUTURES_SECRET_KEY"),
207212
"products": ["PI_XBTUSD", "PF_SOLUSD"],
208-
}
213+
},
209214
)
210215

211216
try:
212217
managed_bot.run()
213218
except Exception:
214219
managed_bot.save_exit(
215-
reason=f"manageBot.run() has ended: {traceback.format_exc()}"
220+
reason=f"manageBot.run() has ended: {traceback.format_exc()}",
216221
)
217222

218223

0 commit comments

Comments
 (0)