203 lines
7.6 KiB
Python
Executable File
203 lines
7.6 KiB
Python
Executable File
"""Minimal async client for the Kraken REST API."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import base64
|
|
import hashlib
|
|
import hmac
|
|
import logging
|
|
import time
|
|
import urllib.parse
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
import httpx
|
|
import pandas as pd
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
API_URL = "https://api.kraken.com"
|
|
USD_ASSETS = {"ZUSD", "USD"}
|
|
VALID_INTERVALS = {1, 5, 15, 30, 60, 240, 1440, 10080, 21600}
|
|
|
|
|
|
class KrakenError(RuntimeError):
|
|
pass
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class PairInfo:
|
|
name: str # canonical key, e.g. XXBTZUSD
|
|
altname: str # e.g. XBTUSD
|
|
base: str
|
|
quote: str
|
|
lot_decimals: int
|
|
pair_decimals: int
|
|
ordermin: float
|
|
costmin: float
|
|
|
|
def round_volume(self, volume: float) -> float:
|
|
"""Round down to the pair's lot precision so we never exceed available funds."""
|
|
factor = 10**self.lot_decimals
|
|
return int(volume * factor) / factor
|
|
|
|
|
|
def sign(urlpath: str, nonce: str, postdata: str, secret: str) -> str:
|
|
message = urlpath.encode() + hashlib.sha256((nonce + postdata).encode()).digest()
|
|
mac = hmac.new(base64.b64decode(secret), message, hashlib.sha512)
|
|
return base64.b64encode(mac.digest()).decode()
|
|
|
|
|
|
class KrakenClient:
|
|
def __init__(
|
|
self,
|
|
api_key: str | None = None,
|
|
api_secret: str | None = None,
|
|
base_url: str = API_URL,
|
|
min_request_interval: float = 1.0,
|
|
):
|
|
self._key = api_key or None
|
|
self._secret = api_secret or None
|
|
self._http = httpx.AsyncClient(
|
|
base_url=base_url, timeout=30, headers={"User-Agent": "kraken-trader/2.0"}
|
|
)
|
|
self._lock = asyncio.Lock()
|
|
self._min_interval = min_request_interval
|
|
self._last_request = 0.0
|
|
self._last_nonce = 0
|
|
self._pairs: dict[str, PairInfo] = {}
|
|
self._pair_alias: dict[str, str] = {}
|
|
self._asset_alias: dict[str, str] = {}
|
|
|
|
@property
|
|
def has_credentials(self) -> bool:
|
|
return bool(self._key and self._secret)
|
|
|
|
async def close(self) -> None:
|
|
await self._http.aclose()
|
|
|
|
async def _throttle(self) -> None:
|
|
wait = self._last_request + self._min_interval - time.monotonic()
|
|
if wait > 0:
|
|
await asyncio.sleep(wait)
|
|
self._last_request = time.monotonic()
|
|
|
|
@staticmethod
|
|
def _unwrap(response: httpx.Response) -> Any:
|
|
response.raise_for_status()
|
|
body = response.json()
|
|
if body.get("error"):
|
|
raise KrakenError(", ".join(body["error"]))
|
|
return body["result"]
|
|
|
|
async def public(self, method: str, params: dict[str, Any] | None = None) -> Any:
|
|
async with self._lock:
|
|
await self._throttle()
|
|
response = await self._http.get(f"/0/public/{method}", params=params)
|
|
return self._unwrap(response)
|
|
|
|
async def private(self, method: str, params: dict[str, Any] | None = None) -> Any:
|
|
if not self.has_credentials:
|
|
raise KrakenError("Kraken API credentials are not configured")
|
|
path = f"/0/private/{method}"
|
|
# Hold the lock while sending so nonces reach Kraken in increasing order.
|
|
async with self._lock:
|
|
await self._throttle()
|
|
self._last_nonce = max(int(time.time() * 1000), self._last_nonce + 1)
|
|
nonce = str(self._last_nonce)
|
|
postdata = urllib.parse.urlencode({"nonce": nonce, **(params or {})})
|
|
headers = {
|
|
"API-Key": self._key,
|
|
"API-Sign": sign(path, nonce, postdata, self._secret),
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
}
|
|
response = await self._http.post(path, content=postdata, headers=headers)
|
|
return self._unwrap(response)
|
|
|
|
# ---- metadata -------------------------------------------------------
|
|
|
|
async def load_metadata(self) -> None:
|
|
assets = await self.public("Assets")
|
|
self._asset_alias = {info["altname"]: key for key, info in assets.items()}
|
|
pairs = await self.public("AssetPairs")
|
|
self._pairs = {}
|
|
self._pair_alias = {}
|
|
for key, info in pairs.items():
|
|
pair = PairInfo(
|
|
name=key,
|
|
altname=info["altname"],
|
|
base=info["base"],
|
|
quote=info["quote"],
|
|
lot_decimals=int(info["lot_decimals"]),
|
|
pair_decimals=int(info["pair_decimals"]),
|
|
ordermin=float(info.get("ordermin", 0) or 0),
|
|
costmin=float(info.get("costmin", 0) or 0),
|
|
)
|
|
self._pairs[key] = pair
|
|
for alias in (key, info["altname"], info.get("wsname")):
|
|
if alias:
|
|
self._pair_alias[alias] = key
|
|
|
|
def pair(self, name: str) -> PairInfo:
|
|
key = self._pair_alias.get(name)
|
|
if key is None:
|
|
raise KrakenError(f"Unknown trading pair: {name}")
|
|
return self._pairs[key]
|
|
|
|
def usd_pair_for_asset(self, asset: str) -> PairInfo | None:
|
|
"""Find the USD-quoted pair for a balance asset like XXBT, XBT.F or SOL."""
|
|
base = asset.split(".")[0]
|
|
base = self._asset_alias.get(base, base)
|
|
for pair in self._pairs.values():
|
|
if pair.base == base and pair.quote in USD_ASSETS and not pair.altname.endswith(".d"):
|
|
return pair
|
|
return None
|
|
|
|
# ---- market data ----------------------------------------------------
|
|
|
|
async def ohlc(self, pair: str, interval: int) -> pd.DataFrame:
|
|
"""Closed candles (oldest first), indexed by UTC candle open time."""
|
|
info = self.pair(pair)
|
|
result = await self.public("OHLC", {"pair": info.name, "interval": interval})
|
|
rows = next(v for k, v in result.items() if k != "last")
|
|
df = pd.DataFrame(
|
|
rows, columns=["time", "open", "high", "low", "close", "vwap", "volume", "count"]
|
|
)
|
|
df["time"] = pd.to_datetime(df["time"], unit="s", utc=True)
|
|
df = df.set_index("time")
|
|
df = df[["open", "high", "low", "close", "vwap", "volume"]].astype(float)
|
|
# The last row is the still-forming candle; strategies only see closed ones.
|
|
return df.iloc[:-1]
|
|
|
|
async def last_prices(self, pairs: list[str]) -> dict[str, float]:
|
|
"""Last trade price keyed by the names passed in."""
|
|
if not pairs:
|
|
return {}
|
|
by_key = {self.pair(p).name: p for p in pairs}
|
|
result = await self.public("Ticker", {"pair": ",".join(by_key)})
|
|
return {by_key[key]: float(t["c"][0]) for key, t in result.items() if key in by_key}
|
|
|
|
# ---- account --------------------------------------------------------
|
|
|
|
async def balance(self) -> dict[str, float]:
|
|
result = await self.private("Balance")
|
|
return {asset: float(amount) for asset, amount in result.items()}
|
|
|
|
async def add_market_order(self, pair: str, side: str, volume: float) -> list[str]:
|
|
info = self.pair(pair)
|
|
result = await self.private(
|
|
"AddOrder",
|
|
{
|
|
"ordertype": "market",
|
|
"type": side,
|
|
"pair": info.name,
|
|
"volume": f"{volume:.{info.lot_decimals}f}",
|
|
},
|
|
)
|
|
log.info("Kraken order placed: %s", result.get("descr", {}).get("order"))
|
|
return result["txid"]
|
|
|
|
async def query_orders(self, txids: list[str]) -> dict[str, dict[str, Any]]:
|
|
return await self.private("QueryOrders", {"txid": ",".join(txids)})
|