### Create API Instance Source: https://context7.com/hartym/krakenex/llms.txt Instantiate the API class for public or authenticated requests, optionally providing a custom connection object. ```python import krakenex # Create API instance without authentication (for public queries only) k = krakenex.API() # Create API instance with inline credentials k = krakenex.API(key='your-api-key', secret='your-api-secret') # Create API instance with existing connection conn = krakenex.Connection(timeout=60) k = krakenex.API(conn=conn) ``` -------------------------------- ### Place Order with Conditional Close Source: https://context7.com/hartym/krakenex/llms.txt Place a limit order and set a conditional close order to automatically sell when the initial order is filled. Ensure the 'close' parameters match the desired exit strategy. ```python order_with_close = k.query_private('AddOrder', { 'pair': 'XXBTZEUR', 'type': 'buy', 'ordertype': 'limit', 'price': '40000', 'volume': '0.1', 'close[pair]': 'XXBTZEUR', 'close[type]': 'sell', 'close[ordertype]': 'limit', 'close[price]': '50000', 'close[volume]': '0.1' }) print(order_with_close) ``` -------------------------------- ### Load Credentials from File Source: https://context7.com/hartym/krakenex/llms.txt Load API credentials from a local file where the key is on the first line and the secret is on the second. ```python import krakenex k = krakenex.API() k.load_key('kraken.key') # kraken.key file format: # your-api-key # your-api-secret # Now you can make authenticated requests balance = k.query_private('Balance') print(balance) # Output: {'error': [], 'result': {'ZUSD': '100.0000', 'XXBT': '0.5000000000'}} ``` -------------------------------- ### Place Orders Source: https://context7.com/hartym/krakenex/llms.txt Submit buy or sell orders to the exchange using the AddOrder endpoint. ```python import krakenex k = krakenex.API() k.load_key('kraken.key') # Place a simple limit buy order order = k.query_private('AddOrder', { 'pair': 'XXBTZUSD', 'type': 'buy', 'ordertype': 'limit', 'price': '45000', 'volume': '0.01' }) print(order) # Output: {'error': [], 'result': {'descr': {'order': 'buy 0.01 XBTUSD @ limit 45000'}, 'txid': ['OXXXXX-XXXXX-XXXXXX']}} ``` -------------------------------- ### Monitor Open Positions Source: https://context7.com/hartym/krakenex/llms.txt Query and summarize open margin positions, calculating latency and aggregating volumes by trading pair. It also reports API errors and the total number of positions. ```python import krakenex k = krakenex.API() k.load_key('kraken.key') # Measure latency start = k.query_public('Time') positions = k.query_private('OpenPositions', {'docalcs': 'true'}) end = k.query_public('Time') latency = end['result']['unixtime'] - start['result']['unixtime'] # Aggregate positions by pair eth_volume = 0 btc_volume = 0 for pos_id, position in positions['result'].items(): if position['pair'] == 'XETHZUSD': eth_volume += float(position['vol']) elif position['pair'] == 'XXBTZUSD': btc_volume += float(position['vol']) print(f"API Errors: {len(positions['error'])}") print(f"Latency: {latency}s") print(f"Open ETH positions: {eth_volume}") print(f"Open BTC positions: {btc_volume}") print(f"Total positions: {len(positions['result'])}") ``` -------------------------------- ### Manage HTTPS Connections Source: https://context7.com/hartym/krakenex/llms.txt Create and manage reusable HTTPS connections with custom timeouts. Pass the connection object to API queries or set it globally for the API instance. ```python import krakenex # Create connection with custom timeout (default is 30 seconds) conn = krakenex.Connection(uri='api.kraken.com', timeout=60) # Use connection with API k = krakenex.API() k.set_connection(conn) # Or pass connection during queries result = k.query_public('Time', conn=conn) print(result) # Close connection when done conn.close() ``` -------------------------------- ### Calculate Available Balance Source: https://context7.com/hartym/krakenex/llms.txt Calculate the available balance by subtracting amounts locked in open orders from the total balance. It processes currency codes by removing 'X' or 'Z' prefixes. ```python import krakenex import pprint k = krakenex.API() k.load_key('kraken.key') # Get balance and open orders balance = k.query_private('Balance')['result'] orders = k.query_private('OpenOrders')['result'] # Process balance - strip X/Z prefixes from currency codes available = {} for currency in balance: clean_name = currency[1:] # Remove 'X' or 'Z' prefix available[clean_name] = float(balance[currency]) # Subtract amounts locked in open orders for order_id, order in orders['open'].items(): volume = float(order['vol']) - float(order['vol_exec']) descr = order['descr'] price = float(descr['price']) pair = descr['pair'] base = pair[:3] quote = pair[3:] if descr['type'] == 'buy': available[quote] -= volume * price elif descr['type'] == 'sell': available[base] -= volume pprint.pprint(available) ``` -------------------------------- ### Query Public Market Data Source: https://context7.com/hartym/krakenex/llms.txt Retrieve public market information such as server time, order books, ticker data, and asset pairs without authentication. ```python import krakenex k = krakenex.API() # Get server time time_result = k.query_public('Time') print(time_result) # Output: {'error': [], 'result': {'unixtime': 1616000000, 'rfc1123': 'Wed, 17 Mar 21 12:00:00 +0000'}} # Get order book depth for BTC/USD pair depth = k.query_public('Depth', {'pair': 'XXBTZUSD', 'count': '10'}) print(depth) # Output: {'error': [], 'result': {'XXBTZUSD': {'asks': [['50000.00', '1.5', 1616000000], ...], 'bids': [...]}}} # Get ticker information for multiple pairs ticker = k.query_public('Ticker', {'pair': 'XXBTZUSD,XETHZUSD'}) print(ticker) # Output: {'error': [], 'result': {'XXBTZUSD': {'a': ['50000.00', '1', '1.000'], 'b': ['49999.00', '2', '2.000'], ...}}} # Get tradeable asset pairs pairs = k.query_public('AssetPairs') print(pairs) # Output: {'error': [], 'result': {'XXBTZUSD': {'altname': 'XBTUSD', 'base': 'XXBT', ...}, ...}} ``` -------------------------------- ### Perform Authenticated Private Queries Source: https://context7.com/hartym/krakenex/llms.txt Execute private API calls such as balance checks, order history, and position management. The library automatically handles nonce generation and request signing. ```python import krakenex k = krakenex.API() k.load_key('kraken.key') # Get account balance balance = k.query_private('Balance') print(balance) # Output: {'error': [], 'result': {'ZUSD': '1000.0000', 'XXBT': '0.5000000000', 'XETH': '10.0000000000'}} # Get open orders orders = k.query_private('OpenOrders') print(orders) # Output: {'error': [], 'result': {'open': {'O5TCV-WSBMX-3KSPCX': {'status': 'open', 'descr': {...}}}}}} # Get trade history with pagination trades = k.query_private('TradesHistory', { 'type': 'all', 'trades': 'true', 'start': '1609459200', # Unix timestamp 'end': '1640995200', 'ofs': '0' # Offset for pagination }) print(trades) # Output: {'error': [], 'result': {'count': 150, 'trades': {'TID1': {...}, 'TID2': {...}}}} # Get open positions with calculations positions = k.query_private('OpenPositions', {'docalcs': 'true'}) print(positions) # Output: {'error': [], 'result': {'POSID1': {'pair': 'XXBTZUSD', 'vol': '1.0', ...}}} ``` -------------------------------- ### API.query_public() Source: https://context7.com/hartym/krakenex/llms.txt Query public Kraken API endpoints that do not require authentication, such as market data, ticker prices, and order book depth. ```APIDOC ## GET /public ### Description Query public market data endpoints. ### Method GET ### Parameters #### Query Parameters - **method** (string) - Required - The specific public API method (e.g., 'Time', 'Depth', 'Ticker', 'AssetPairs') - **params** (dict) - Optional - Dictionary of parameters specific to the method (e.g., {'pair': 'XXBTZUSD', 'count': '10'}) ### Response #### Success Response (200) - **error** (list) - List of error messages - **result** (dict) - The requested market data ``` -------------------------------- ### API.query_private() Source: https://context7.com/hartym/krakenex/llms.txt Query private Kraken API endpoints that require authentication, such as account balance, order history, and placing trades. ```APIDOC ## POST /private ### Description Query private account endpoints. Automatically handles nonce generation and HMAC-SHA512 signing. ### Method POST ### Parameters #### Request Body - **method** (string) - Required - The specific private API method (e.g., 'Balance', 'OpenOrders', 'AddOrder') - **params** (dict) - Optional - Dictionary of parameters specific to the method (e.g., {'pair': 'XXBTZUSD', 'type': 'buy', 'ordertype': 'limit', 'price': '45000', 'volume': '0.01'}) ### Response #### Success Response (200) - **error** (list) - List of error messages - **result** (dict) - The requested account or trade data ``` -------------------------------- ### Export Trade History for Tax Reporting Source: https://context7.com/hartym/krakenex/llms.txt Fetch and export trade history to CSV for tax compliance. It retrieves trades month by month to handle API pagination and rate limits. ```python import krakenex import datetime import calendar import pandas as pd import time def date_nix(date_obj): """Convert datetime to Unix timestamp.""" return calendar.timegm(date_obj.timetuple()) def date_str(nix_time): """Convert Unix timestamp to formatted date string.""" return datetime.datetime.fromtimestamp(nix_time).strftime('%m, %d, %Y') k = krakenex.API() k.load_key('kraken.key') data = [] # Fetch trades month by month to handle pagination for month in range(1, 13): start_date = datetime.datetime(2023, month, 1) if month == 12: end_date = datetime.datetime(2024, 1, 1) else: end_date = datetime.datetime(2023, month + 1, 1) trades_result = k.query_private('TradesHistory', { 'type': 'all', 'trades': 'true', 'start': str(date_nix(start_date)), 'end': str(date_nix(end_date)), 'ofs': '0' }) time.sleep(0.25) # Rate limiting if trades_result['result']['count'] > 0: df = pd.DataFrame.from_dict(trades_result['result']['trades']).transpose() data.append(df) if data: trades = pd.concat(data, axis=0) trades = trades.sort_values(by='time', ascending=True) trades.to_csv('trades_2023.csv') print(f"Exported {len(trades)} trades to trades_2023.csv") ``` -------------------------------- ### Cancel an Order Source: https://context7.com/hartym/krakenex/llms.txt Cancel an existing order using its transaction ID (txid). This is useful for managing open orders that are no longer desired. ```python cancel = k.query_private('CancelOrder', {'txid': 'OXXXXX-XXXXX-XXXXXX'}) print(cancel) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.