### Python Spot Websocket Client Setup Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/spot_ws_examples.md This snippet shows the basic setup for a Python Spot websocket client using the python-kraken-sdk. Ensure the library is installed before running. ```python # !/usr/bin/env python3 # -*- mode: python; coding: utf-8 -*- # # Copyright (C) 2023 Benjamin Thomas Schwertfeger # All rights reserved. # https://github.com/btschwertfeger ``` -------------------------------- ### SpotWSClient with Callback Function Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md This example shows how to use the SpotWSClient with a separate callback function to process incoming messages. It demonstrates starting the client, subscribing to a feed, and keeping the connection alive. ```APIDOC ## SpotWSClient with Callback ### Description This example demonstrates initializing the SpotWSClient with a callback function to handle incoming messages. It shows how to start the client, subscribe to the 'ticker' channel for 'BTC/USD', and maintain the connection. ### Method: `__init__` and `subscribe` ### Example Usage ```python import asyncio from kraken.spot import SpotWSClient async def on_message(message): print(message) async def main(): client = SpotWSClient(callback=on_message) await client.start() await client.subscribe( params={"channel": "ticker", "symbol": ["BTC/USD"]} ) while not client.exception_occur: await asyncio.sleep(10) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: pass ``` ``` -------------------------------- ### Installation Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/README.md Install the python-kraken-sdk package into your environment. ```APIDOC ## Installation ### Description Install the python-kraken-sdk package into your desired environment. ### Command ```bash python3 -m pip install python-kraken-sdk ``` ``` -------------------------------- ### Initialize and Start SpotWSClient Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md Demonstrates initializing both authenticated and unauthenticated SpotWSClient instances and starting their connections. The on_message method is overridden to handle incoming messages. ```python import asyncio from kraken.spot import SpotWSClient class Client(SpotWSClient): async def on_message(self, message): print(message) async def main(): client = Client() # unauthenticated client_auth = Client( # authenticated key="kraken-api-key", secret="kraken-secret-key" ) # open the websocket connections await client.start() await auth_client.start() # subscribe to the desired feeds: await client.subscribe( params={"channel": "ticker", "symbol": ["BTC/USD"]} ) # from now on the on_message function receives the ticker feed while not client.exception_occur: await asyncio.sleep(6) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: pass ``` -------------------------------- ### Python Kraken SDK Spot Orderbook Client Setup Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/trading_bot_templates/spot_orderbook.md This snippet shows the basic setup for the SpotOrderBookClient, which utilizes the websocket API v2 for realtime orderbook data. Ensure you have the kraken-sdk installed. ```python #!/usr/bin/env python3 # -*- mode: python; coding: utf-8 -*- # # Copyright (C) 2023 Benjamin Thomas Schwertfeger # All rights reserved. # https://github.com/btschwertfeger ``` -------------------------------- ### Main Function for Kraken SDK Examples Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/spot_rest_examples.md The main entry point for running various example functions within the Kraken SDK. Users can uncomment specific function calls to execute different sets of examples. ```python def main() -> None: """Uncomment the examples you want to run:""" # NOTE: These are only examples that show how to use the clients, there are # many other functions available in the clients. # user_examples() # market_examples() # trade_examples() # funding_examples() if __name__ == "__main__": main() ``` -------------------------------- ### Install python-kraken-sdk Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/README.md Install the package into your desired Python environment using pip. ```bash python3 -m pip install python-kraken-sdk ``` -------------------------------- ### Install Libraries and Kernel Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/examples/market_client_example.ipynb Installs matplotlib, numpy, pandas, and ipykernel. Also installs the kraken kernel for Jupyter. ```bash pip install matplotlib numpy pands ipykernel python3 -m ipykernel install --user --name=kraken ``` -------------------------------- ### Get Order Status Example Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Shows how to retrieve the status of multiple orders by providing a list of order IDs. ```python print(trade.get_orders_status(orderIds=["orderid1", "orderid2"])) ``` -------------------------------- ### Get Historical Funding Rates Example Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Shows how to retrieve historical funding rates for a specific symbol using the Funding client. ```python print(funding.get_historical_funding_rates(symbol="PF_SOLUSD")) ``` -------------------------------- ### Create Limit Order Example Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Example of creating a limit order with specified type, side, size, price, and symbol. ```python print( trade.create_order( orderType="lmt", side="buy", size=1, limitPrice=4, symbol="pf_bchusd", ), ) ``` -------------------------------- ### Command-line Interface (CLI) Usage Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/README.md Examples of using the kraken CLI for interacting with Spot and Futures APIs. ```APIDOC ## Command-line Interface (CLI) Usage ### Description The python-kraken-sdk provides a command-line interface to access the Kraken API. The Spot and Futures API are accessible following the pattern `kraken {spot,futures} [OPTIONS] URL`. ### Examples #### Get Server Time (Spot) ```bash kraken spot https://api.kraken.com/0/public/Time ``` **Response:** ```json {'unixtime': 1716707589, 'rfc1123': 'Sun, 26 May 24 07:13:09 +0000'} ``` #### Get User's Balances (Spot, Private) ```bash kraken spot --api-key= --secret-key= -X POST https://api.kraken.com/0/private/Balance ``` **Response:** ```json {'ATOM': '17.28229999', 'BCH': '0.0000077100', 'ZUSD': '1000.0000'} ``` #### Get User's Trade Balances (Spot, Private, with data) ```bash kraken spot --api-key= --secret-key= -X POST https://api.kraken.com/0/private/TradeBalance --data '{"asset": "DOT"}' ``` **Response:** ```json {'eb': '2.8987347115', 'tb': '1.1694303513', 'm': '0.0000000000', 'uv': '0', 'n': '0.0000000000', 'c': '0.0000000000', 'v': '0.0000000000', 'e': '1.1694303513', 'mf': '1.1694303513'} ``` #### Get 1D Candles for a Futures Instrument ```bash kraken futures https://futures.kraken.com/api/charts/v1/spot/PI_XBTUSD/1d ``` **Response:** ```json {'candles': [{'time': 1625616000000, 'open': '34557.84000000000', 'high': '34803.20000000000', 'low': '33816.32000000000', 'close': '33880.22000000000', 'volume': '0' ...} ``` #### Get User's Open Futures Positions (Futures, Private) ```bash kraken futures --api-key= --secret-key= https://futures.kraken.com/derivatives/api/v3/openpositions ``` **Response:** ```json {'result': 'success', 'openPositions': [], 'serverTime': '2024-05-26T07:15:38.91Z'} ``` ### Note All endpoints of the Kraken Spot and Futures API can be accessed using this CLI pattern. ``` -------------------------------- ### Create Take Profit Order Example Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Demonstrates creating a 'take profit' order with a stop price and trigger signal. ```python print( trade.create_order( orderType="take_profit", side="buy", size=1, symbol="pf_bchusd", stopPrice=100, triggerSignal="mark", ), ) ``` -------------------------------- ### Subscribe to Public WebSocket Feeds Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_ws_examples.md Instantiate a client, start it, and subscribe to public data feeds like 'ticker' and 'book'. Ensure the client is started before subscribing. ```python client = Client() clients.append(client) await client.start() products = ["PI_XBTUSD", "PF_SOLUSD"] # subscribe to a public websocket feed await client.subscribe(feed="ticker", products=products) await client.subscribe(feed="book", products=products) ``` -------------------------------- ### Start Websocket Connection Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md Initiates the websocket connection. This method is asynchronous. ```APIDOC ## Start Websocket Connection ### Description Starts the websocket connection. This is an asynchronous operation. ### Method `start()` ### Endpoint N/A (Method Call) ### Parameters None ### Request Example ```python await client.start() ``` ### Response None ``` -------------------------------- ### Initialize Futures Websocket Client Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_ws_examples.md Sets up logging and imports necessary modules for the Futures websocket client. Ensure you have the kraken-sdk installed. ```python #!/usr/bin/env python3 # -*- mode: python; coding: utf-8 -*- # # Copyright (C) 2023 Benjamin Thomas Schwertfeger # All rights reserved. # https://github.com/btschwertfeger # """ Module that provides an example usage for the Kraken Futures websocket client. """ from __future__ import annotations import asyncio import logging import os import time from kraken.futures import FuturesWSClient logging.basicConfig( format="%(asctime)s %(module)s,line: %(lineno)d %(levelname)8s | %(message)s", datefmt="%Y/%m/%d %H:%M:%S", level=logging.INFO, ) logging.getLogger("requests").setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) LOG: logging.Logger = logging.getLogger(__name__) clients = [] ``` -------------------------------- ### Cancel All Orders Example Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Demonstrates how to cancel all open orders, with an option to specify a symbol. ```python print(trade.cancel_all_orders()) print(trade.cancel_all_orders(symbol="pi_xbtusd")) ``` -------------------------------- ### Edit Order Example Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Demonstrates how to modify an existing order by providing the order ID and new parameters like size and prices. ```python print( trade.edit_order( orderId="some order id", size=300, limitPrice=401, stopPrice=350, ), ) ``` -------------------------------- ### Initialize SpotWSClient with Async Context Manager Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md Illustrates using the SpotWSClient as an asynchronous context manager, which handles connection setup and teardown. It subscribes to the ticker feed for BTC/USD. ```python import asyncio from kraken.spot import SpotWSClient async def on_message(message): print(message) async def main(): async with SpotWSClient( key="api-key", secret="secret-key", callback=on_message ) as session: await session.subscribe( params={"channel": "ticker", "symbol": ["BTC/USD"]} ) while True: await asyncio.sleep(6) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: pass ``` -------------------------------- ### Initialize SpotWSClient with Callback Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md Shows how to initialize the SpotWSClient with a callback function for handling messages and subscribing to the ticker feed for BTC/USD. ```python import asyncio from kraken.spot import SpotWSClient async def on_message(message): print(message) async def main(): client = SpotWSClient(callback=on_message) await client.start() await client.subscribe( params={"channel": "ticker", "symbol": ["BTC/USD"]} ) while not client.exception_occur: await asyncio.sleep(10) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: pass ``` -------------------------------- ### Get Leverage Preference - Kraken Futures Private Market Client Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Access private market endpoints using credentials. This example shows how to get the leverage preference for an account. Ensure `key`, `secret`, and `sandbox=True` are set. ```python priv_market = Market(key=key, secret=secret, sandbox=True) print(priv_market.get_leverage_preference()) ``` -------------------------------- ### SpotWSClient Initialization and Usage Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md This snippet demonstrates how to initialize the SpotWSClient, establish both authenticated and unauthenticated connections, subscribe to the ticker feed for BTC/USD, and handle incoming messages. ```APIDOC ## SpotWSClient Class ### Description Class to access public and private/authenticated websocket connections using Kraken Websocket API v2. It supports un-/subscribing to websocket feeds and sending messages. ### Parameters * **key** (*str*, optional): API Key for the Kraken Spot API. * **secret** (*str*, optional): Secret API Key for the Kraken Spot API. * **callback** (Callable | None, optional): A function to be called when a message is received. * **no_public** (bool, optional): Disables public connection. Defaults to False. * **rest_url** (str | None, optional): Set a specific URL to access the Kraken REST API. * **ws_url** (str | None, optional): Set a specific Websocket URL to access the Kraken Spot API. * **auth_ws_url** (str | None, optional): Set a specific Authenticated Websocket URL to access the Kraken Spot API. ### Method: `__init__` ### Example Usage ```python import asyncio from kraken.spot import SpotWSClient class Client(SpotWSClient): async def on_message(self, message): print(message) async def main(): client = Client() # unauthenticated client_auth = Client( key="kraken-api-key", secret="kraken-secret-key" ) # open the websocket connections await client.start() await client_auth.start() # subscribe to the desired feeds: await client.subscribe( params={"channel": "ticker", "symbol": ["BTC/USD"]} ) # from now on the on_message function receives the ticker feed while not client.exception_occur: await asyncio.sleep(6) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: pass ``` ``` -------------------------------- ### Get Tradeable Products - Kraken Futures Market Client Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Fetch tradeable products from the Kraken Futures market. Specify the tick type, for example, 'trade'. ```python market = Market() print(market.get_tradeable_products(tick_type="trade")) ``` -------------------------------- ### Get Recent Withdraw Status Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Retrieve information on recent withdrawal statuses, covering the past 90 days with a maximum of 500 results. Supports filtering by asset, method, start, and end timestamps, as well as cursor-based pagination. ```python >>> from kraken.spot import Funding >>> funding = Funding(key="api-key", secret="secret-key") >>> funding.get_recent_withdraw_status() [ { 'method': 'Polkadot', 'aclass': 'currency', 'asset': 'DOT', 'refid': 'XXXXXX-XXXXXX-HLDRM5', 'txid': '0x51d9d13ade1c31a138dae81b845f091d1a6cf2e3c1c36d9cf4f7baf905c483e4', 'info': '16LrqRXyhjBCSfA6kKrdqxPKrZoMEUtmoW4nkx5ZhA374Bp3', 'amount': '94.39581164', 'fee': '0.05000000', 'time': 1677816733, 'status': 'Success' }, ... ] ``` -------------------------------- ### Instantiate Kraken Spot User Client Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Demonstrates how to instantiate the User client for authenticated and unauthenticated access. Requires API keys for authenticated operations. ```python from kraken.spot import User user = User() # unauthenticated auth_user = User(key="api-key", secret="secret-key") # authenticated ``` -------------------------------- ### Instantiate Kraken Spot Trade Client with Context Manager Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Use the Trade client within a context manager for automatic resource management. Ensure you provide authentication credentials. ```python from kraken.spot import Trade with Trade(key="api-key", secret="secret-key") as trade: print(trade.create_order(...)) ``` -------------------------------- ### Get Orderbook Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Get the orderbook of a specific asset/symbol. It is recommended to use the `symbol` parameter. ```APIDOC ## get_orderbook(symbol: str | None = None, *, extra_params: dict | None = None) -> dict ### Description Get the orderbook of a specific asset/symbol. Even if the official kraken documentation states that the parameter `symbol` is not required, they will always respond with an error message, so it is recommended to use the `symbol` parameter until they don’t fix this issue. ### Parameters #### Path Parameters None #### Query Parameters * **symbol** (str) - Optional - The asset/symbol to get the orderbook from #### Request Body None ### Request Example ```python >>> from kraken.futures import Market >>> Market().get_orderbook(symbol="PI_XBTUSD") ``` ### Response #### Success Response (200) * **result** (str) - Indicates the result of the operation ('success' or 'error') * **orderBook** (dict) - Contains the order book data with 'bids' and 'asks' #### Response Example ```json { "result": "success", "orderBook": { "bids": [ [27909, 3000], [27908.5, 1703], [27906, 1716], [27905, 2900], [27904.5, 2900], [27904, 2900], [27903.5, 8900], [27903, 3415], [27902.5, 2900], [27902, 2900], [27901, 4200], [27900.5, 6000], ... ], "asks": [ [27915, 4200], [27916, 1706], [27917.5, 2900], [27918, 4619], [27918.5, 4200], [27919, 2900], [27919.5, 78], [27920, 2900], [27920.5, 2900], [27921, 6342], [27921.5, 4200], [27923, 27851], ... ] } } ``` ``` -------------------------------- ### Initialize Funding Client with Context Manager Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Use the Funding client as a context manager for authenticated operations. This ensures proper setup and teardown of the client session. ```python >>> from kraken.spot import Funding >>> with Funding(key="api-key", secret="secret-key") as funding: ... print(funding.get_deposit_methods(asset="XLM")) ``` -------------------------------- ### Cancel Order Example Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Example of canceling a specific order using its order ID. ```python print(trade.cancel_order(order_id="some order id")) ``` -------------------------------- ### Configure SpotWSClient with Custom URLs Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md Example of initializing the SpotWSClient with custom URLs for REST, WebSocket, and authenticated WebSocket endpoints, useful for testing or specific environments. ```python client_auth = SpotWSClient( key="api-key", secret="secret-key", rest_url="https://api.vip.uat.lobster.kraken.com", ws_url="wss://ws.vip.uat.lobster.kraken.com", auth_ws_url="wss://ws-auth.vip.uat.lobster.kraken.com", ) ``` -------------------------------- ### Initialize Kraken Spot Market client Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Instantiate the Market client for accessing Kraken Spot market data. It can be used unauthenticated or authenticated with API keys. ```python >>> from kraken.spot import Market >>> market = Market() # unauthenticated >>> auth_market = Market(key="api-key", secret="secret-key") # authenticated ``` -------------------------------- ### Get PNL Preference Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Get the current PNL (profit & loss) preferences. This can be used to define the currency in which the profits and losses are realized. ```APIDOC ## get_pnl_preference(*, extra_params: dict | None = None) -> dict ### Description Get the current PNL (profit & loss) preferences. This can be used to define the currency in which the profits and losses are realized. Requires at least the `General API - Read Only` permission in the API key settings. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python >>> from kraken.futures import Market >>> market = Market(key="api-key", secret="secret-key") >>> market.get_pnl_preference() ``` ### Response #### Success Response (200) * **result** (str) - Indicates the result of the operation ('success' or 'error') * **serverTime** (str) - The server time * **preferences** (list) - The current PNL preferences #### Response Example ```json {'result': 'success', 'serverTime': '2023-04-04T15:21:29.413Z', 'preferences': []} ``` ``` -------------------------------- ### Initialize Funding Client Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Instantiate the Funding client for interacting with Kraken's spot funding endpoints. It can be initialized without authentication or with API keys for authenticated requests. ```python >>> from kraken.spot import Funding >>> funding = Funding() # unauthenticated >>> auth_funding = Funding(key="api-key", secret="secret-key") # authenticated ``` -------------------------------- ### Use Funding Client with Context Manager Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Initialize the Funding client using a context manager for automatic resource management. Requires API keys for authenticated access. ```python from kraken.futures import Funding with Funding(key="api-key", secret="secret-key") as funding: print(funding.get_historical_funding_rates(symbol="PI_XBTUSD")) ``` -------------------------------- ### Get Fills - Kraken Futures Trade Client Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/futures_rest_examples.md Retrieve a list of recent trade fills. This endpoint can be used with a `lastFillTime` parameter to get fills after a specific time. Use with caution as it involves trade data. ```python trade = Trade(key=key, secret=secret, sandbox=True) print(trade.get_fills()) print(trade.get_fills(lastFillTime="2020-07-21T12:41:52.790Z")) ``` -------------------------------- ### Initialize Kraken Futures Funding Client Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Instantiate the Funding client. Use an empty constructor for unauthenticated access or provide API keys for authenticated access. ```python from kraken.futures import Funding funding = Funding() # unauthenticated funding = Funding(key="api-key", secret="secret-key") # authenticated ``` -------------------------------- ### Spot Client - Asynchronous Usage Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/README.md Demonstrates how to use the asynchronous SpotAsyncClient for making API requests. ```APIDOC ## Spot Client - Asynchronous Usage ### Description The `SpotAsyncClient` allows for asynchronous access to Kraken's Spot API endpoints, suitable for non-blocking operations. ### Example 1: Manual Client Closing This example shows how to manually close the client after the request is made. ```python import asyncio from kraken.spot import SpotAsyncClient async def main(): client = SpotAsyncClient(key="", secret="") try: response = await client.request("POST", "/0/private/Balance") print(response) finally: await client.close() if __name__ == "__main__": asyncio.run(main()) ``` ### Example 2: Using Context Manager This example demonstrates the use of the context manager, which ensures the client is automatically closed after the request is completed. ```python import asyncio from kraken.spot import SpotAsyncClient async def main(): async with SpotAsyncClient(key="", secret="") as client: response = await client.request("POST", "/0/private/Balance") print(response) if __name__ == "__main__": asyncio.run(main()) ``` ### Note Refer to the official Kraken API documentation for a comprehensive list of available endpoints and their usage: [https://docs.kraken.com/api/docs/guides/global-intro](https://docs.kraken.com/api/docs/guides/global-intro) ``` -------------------------------- ### get_leverage_preference Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Get the current leverage preferences of the user. ```APIDOC ## get_leverage_preference ### Description Get the current leverage preferences of the user. Requires at least the `General API - Read Only` permission in the API key settings. ### Method GET ### Endpoint /api/v1/user/leverage-preference ### Parameters None ### Response #### Success Response (200) - **leveragePreferences** (list) - List of leverage preference objects - **symbol** (str) - The symbol of the futures contract - **maxLeverage** (float) - The maximum leverage for the contract ### Request Example ```python market = Market(key="api-key", secret="secret-key") market.get_leverage_preference() ``` ### Response Example ```json { "leveragePreferences": [ {'symbol': 'PF_XBTUSD', 'maxLeverage': 5.0} ] } ``` ``` -------------------------------- ### Get Current Tickers Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Retrieves information about the current tickers for all futures contracts. ```python >>> from kraken.futures import Market >>> Market().get_tickers() { 'tickers': [{ 'tag': 'perpetual', 'pair': 'COMP:USD', 'symbol': 'pf_compusd', 'markPrice': 42.192, 'bid': 42.14, 'bidSize': 11.8, 'ask': 42.244, 'askSize': 80.7, 'vol24h': 96.8, 'volumeQuote': 4109.9678, 'openInterest': 451.3, 'open24h': 41.975, 'indexPrice': 42.193, 'last': 42.873, 'lastTime': '2023-04-04T00:07:33.690Z', 'lastSize': 13.9, 'suspended': False, 'fundingRate': 0.000220714078888884, 'fundingRatePrediction': 6.3914700437486e-05, 'postOnly': False }, ...] } ``` -------------------------------- ### SpotClient Initialization Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Initialize the SpotClient with optional API keys, secret, and URL. The client handles request signing, response parsing, and exception handling. ```APIDOC ## SpotClient ### Description This class is the base for all Spot clients, handles un-/signed requests and returns exception handled results. With this class you can easily interact with the Kraken Spot API, including trading Spot crypto assets, xStocks, and margin trading. ### Parameters * **key** (*str*, *optional*) – Spot API public key (default: `""`) * **secret** (*str*, *optional*) – Spot API secret key (default: `""`) * **url** (*str*, *optional*) – URL to access the Kraken API (default: `https://api.kraken.com`) * **proxy** (*str*, *optional*) – proxy URL, may contain authentication information * **use_custom_exceptions** (*bool*, *optional*) – Whether to use custom exceptions (default: `True`) ``` -------------------------------- ### Get Market Ticker Information Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/spot_rest_examples.md Retrieves ticker information for a specified trading pair. ```python market = Market() print(market.get_ticker(pair="XBTUSD")) ``` -------------------------------- ### get_orders_status Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Get the status of multiple orders. Requires at least the `General API - Read Only` permission. ```APIDOC ## get_orders_status(orderIds: str | list[str] | None = None, cliOrdIds: str | list[str] | None = None, *, extra_params: dict | None = None) -> dict ### Description Retrieves the status for one or more orders, identified by their IDs or client-defined IDs. Requires `General API - Read Only` permission. ### Parameters #### Query Parameters - **orderIds** (str | list[str], optional) - A single order ID or a list of order IDs to query. - **cliOrdIds** (str | list[str], optional) - A single client-defined order ID or a list of client-defined order IDs to query. ### Request Example ```python >>> from kraken.futures import Trade >>> trade = Trade(key="api-key", secret="secret-key") >>> trade.get_orders_status( ... orderIds=[ ... "2c611222-bfe6-42d1-9f55-77bddc01a313", ... "5f204f95-4354-4610-bb3b-c902ad333012" ... ]) ``` ### Response #### Success Response (200) - **result** (dict) - Indicates success or failure. - **serverTime** (str) - The server time at the time of the response. - **orders** (list) - A list of order status objects. The structure of each object depends on the order details. ``` -------------------------------- ### Initialize KrakenFuturesWSClient Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/trading_bot_templates/futures_bot_template.md Initializes the KrakenFuturesWSClient with API credentials. Ensure 'key' and 'secret' are provided in the configuration dictionary. ```python super().__init__( key=config["key"], secret=config["secret"], ) ``` -------------------------------- ### Spot Client - Synchronous Usage Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/README.md Demonstrates how to use the synchronous SpotClient for making API requests. ```APIDOC ## Spot Client - Synchronous Usage ### Description The `SpotClient` provides synchronous access to Kraken's Spot API endpoints. You can use the `request` method to interact with both authenticated and unauthenticated endpoints. ### Setup ```python from kraken.spot import SpotClient client = SpotClient(key="", secret="") ``` ### Example: Get User Balances #### Method ``` POST ``` #### Endpoint ``` /0/private/Balance ``` #### Request Body (Not applicable for this specific request, as it's a simple POST without a body) #### Request Example ```python print(client.request("POST", "/0/private/Balance")) ``` #### Response Example (Success) ```json { "error": [], "result": { "ZUSD": "1000.0000", "XETH": "0.00000000", "XXBT": "0.00000000" } } ``` ``` -------------------------------- ### Get Subaccounts Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Lists the subaccounts owned by the user. Requires 'General API - Read Only' permissions. ```python >>> from kraken.futures import User >>> user = User(key="api-key", secret="secret-key") >>> user.get_subaccounts() { 'result': 'success', 'serverTime': '2023-04-04T18:03:33.696Z', 'masterAccountUid': 'f7d5571c-6d10-4cf1-944a-048d25682ed0', 'subaccounts': [] } ``` -------------------------------- ### Get Market Recent Spreads Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/spot_rest_examples.md Retrieves recent bid-ask spreads for a specified trading pair. ```python market = Market() print(market.get_recent_spreads(pair="XBTUSD")) ``` -------------------------------- ### Initialize Trade and Create Limit Order with Python Kraken SDK Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md This snippet demonstrates initializing the `Trade` object with API credentials and then creating a limit order. Ensure you replace 'api-key' and 'secret-key' with your actual credentials. ```python >>> from kraken.futures import Trade >>> trade = Trade(key="api-key", secret="secret-key") >>> trade.create_order( ... orderType="lmt", ... size=1000, ... symbol="PF_ETHUSD", ... side="buy", ... limitPrice=1200.0, ... ) { 'result': 'success', 'sendStatus': { 'order_id': '2ce038ae-c144-4de7-a0f1-82f7f4fca864', 'status': 'placed', 'receivedTime': '2023-04-07T15:18:04.699Z', 'orderEvents': [ { 'order': { 'orderId': '2ce038ae-c144-4de7-a0f1-82f7f4fca864', 'cliOrdId': None, 'type': 'lmt', 'symbol': 'pi_ethusd', 'side': 'buy', 'quantity': 100, 'filled': 0, 'limitPrice': 1200.0, 'reduceOnly': False, 'timestamp': '2023-04-07T15:18:04.699Z', 'lastUpdateTimestamp': '2023-04-07T15:18:04.699Z' }, 'reducedQuantity': None, 'type': 'PLACE' } ] }, 'serverTime': '2023-04-07T15:18:04.700Z' } ``` -------------------------------- ### Get Market Recent Trades Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/spot_rest_examples.md Retrieves a list of recent trades for a specified trading pair. ```python market = Market() print(market.get_recent_trades(pair="XBTUSD")) ``` -------------------------------- ### SpotWSClient with Async Context Manager Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md This snippet illustrates using the SpotWSClient as an asynchronous context manager, which simplifies connection handling. It shows subscribing to a feed within the `async with` block. ```APIDOC ## SpotWSClient as Async Context Manager ### Description This example demonstrates using the SpotWSClient with an asynchronous context manager (`async with`). This approach simplifies the management of the websocket connection, ensuring it's properly opened and closed. It shows subscribing to the 'ticker' feed for 'BTC/USD' within the context. ### Method: `__aenter__`, `__aexit__`, and `subscribe` ### Example Usage ```python import asyncio from kraken.spot import SpotWSClient async def on_message(message): print(message) async def main(): async with SpotWSClient( key="api-key", secret="secret-key", callback=on_message ) as session: await session.subscribe( params={"channel": "ticker", "symbol": ["BTC/USD"]} ) while True: await asyncio.sleep(6) if __name__ == "__main__": try: asyncio.run(main()) except KeyboardInterrupt: pass ``` ``` -------------------------------- ### Get Unique ID Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Retrieves a unique UUID string, useful for tracking or referencing specific operations. ```python >>> trade.return_unique_id 'a1b2c3d4-e5f6-7890-1234-567890abcdef' ``` -------------------------------- ### Spot Async Client - Context Manager Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/README.md Shows how to use the asynchronous SpotAsyncClient as a context manager, ensuring the client is automatically closed after the request. ```python import asyncio from kraken.spot import SpotAsyncClient async def main(): async with SpotAsyncClient(key="", secret="") as client: response = await client.request("POST", "/0/private/Balance") print(response) if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Get Market Assets Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/spot_rest_examples.md Retrieves information about available assets, optionally filtering by specific asset codes. ```python market = Market() print(market.get_assets(assets=["XBT"])) ``` -------------------------------- ### Use Kraken Spot User Client as Context Manager Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Shows how to use the User client within a context manager for operations that require an authenticated session. Ensures proper session handling. ```python from kraken.spot import User with User(key="api-key", secret="secret-key") as user: print(user.get_account_balances()) ``` -------------------------------- ### FuturesWSClient.start Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/websockets.md Initiates and establishes the WebSocket connection. ```APIDOC ## POST /websocket/start ### Description Starts the WebSocket connection to the Kraken Futures API. This method should be called before attempting to subscribe to any feeds or send other WebSocket messages. ### Method POST ### Endpoint /websocket/start ### Parameters None ### Request Example None ### Response #### Success Response (200) - **status** (str) - Indicates that the WebSocket connection has been initiated. #### Response Example ```json { "status": "WebSocket connection started" } ``` ``` -------------------------------- ### Get Assets Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/rest.md Retrieves information about one or more assets. If no assets are specified, all assets will be returned. This function utilizes caching. ```APIDOC ## GET /assets ### Description Get information about one or more assets. If `assets` is not specified, all assets will be returned. ### Method GET ### Endpoint /assets ### Parameters #### Query Parameters - **assets** (str | list[str] | None) - Optional - Filter by asset(s) - **aclass** (str | None) - Optional - Filter by asset class ### Response #### Success Response (200) - **dict** - Information about the requested assets ``` -------------------------------- ### Get Nonce Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/04_spot/websockets.md Generates and returns a new nonce (a number used once) which is typically required for authenticated API requests. ```APIDOC ## get_nonce() ### Description Return a new nonce. ### Method Signature `def get_nonce() -> str` ``` -------------------------------- ### Use Market Client with Context Manager Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/05_futures/rest.md Demonstrates using the Market client within a `with` statement for automatic resource management. This example calls `get_tick_types`. ```python from kraken.futures import Market with Market() as market: print(market.get_tick_types()) ``` -------------------------------- ### Get Market Asset Pairs Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/doc/03_examples/rest_examples/spot_rest_examples.md Retrieves information about asset pairs, optionally filtering by specific pair codes. ```python market = Market() print(market.get_asset_pairs(pair=["DOTEUR"])) ``` -------------------------------- ### Spot Async Client - Manual Close Source: https://github.com/btschwertfeger/python-kraken-sdk/blob/master/README.md Demonstrates using the asynchronous SpotAsyncClient without a context manager. The client must be manually closed after use. ```python import asyncio from kraken.spot import SpotAsyncClient async def main(): client = SpotAsyncClient(key="", secret="") try: response = await client.request("POST", "/0/private/Balance") print(response) finally: await client.close() if __name__ == "__main__": asyncio.run(main()) ```