Skip to content

Kraken

Connector for Kraken centralized exchange.

almanak.framework.connectors.kraken

Kraken CEX Connector.

This module provides the Kraken CEX adapter for executing trades, deposits, and withdrawals on Kraken exchange.

Supported operations: - Spot trading (market orders) - Multi-chain withdrawals (Arbitrum, Optimism, Ethereum) - Deposit tracking

Key features: - Idempotent execution with userref/refid tracking - Crash recovery for pending operations - Exponential backoff polling - Token/chain resolution for stack-v2 compatibility

Example

from almanak.framework.connectors.kraken import ( KrakenAdapter, KrakenConfig, KrakenCredentials, ExecutionContext, )

Setup

credentials = KrakenCredentials.from_env() config = KrakenConfig(credentials=credentials) adapter = KrakenAdapter(config)

Compile intent

context = ExecutionContext( chain="arbitrum", wallet_address="0x...", token_decimals={"USDC": 6, "ETH": 18}, )

From an intent with venue="kraken"

bundle = adapter.compile_intent(intent, context)

Execute (typically done by orchestrator)

for action in bundle.actions: key, result_id = await adapter.execute_action(action, context) details = await adapter.resolve_action(action, key, context)

Lower-level SDK usage

from almanak.framework.connectors.kraken import KrakenSDK

sdk = KrakenSDK(credentials)

Get balance

balance = sdk.get_balance("USDC", chain="arbitrum")

Execute swap

userref = sdk.generate_userref() txid = sdk.swap( asset_in="USDC", asset_out="ETH", amount_in=1000_000000, # 1000 USDC decimals_in=6, userref=userref, )

Check status

status = sdk.get_swap_status(txid, userref)

ActionBundle dataclass

ActionBundle(
    actions: list[CEXAction],
    venue_type: VenueType,
    exchange: str = "kraken",
    continue_on_failure: bool = False,
    description: str = "",
    estimated_gas: int = 0,
)

Bundle of actions to execute.

For CEX operations, this typically contains a single action, but supports multiple for future batch operations.

to_dict

to_dict() -> dict

Serialize for state persistence.

ActionType

Bases: str, Enum

CEX action types.

CEXAction dataclass

CEXAction(
    id: str,
    type: ActionType,
    exchange: str,
    asset_in: str | None = None,
    asset_out: str | None = None,
    amount_in: int | None = None,
    decimals_in: int | None = None,
    decimals_out: int | None = None,
    asset: str | None = None,
    amount: int | None = None,
    decimals: int | None = None,
    chain: str | None = None,
    to_address: str | None = None,
    tx_hash: str | None = None,
    from_chain: str | None = None,
    userref: int | None = None,
    metadata: dict = dict(),
)

A single CEX action to execute.

Actions are the atomic units of work in CEX execution.

to_dict

to_dict() -> dict

Serialize for state persistence.

ExecutionContext dataclass

ExecutionContext(
    chain: str = "ethereum",
    wallet_address: str = "",
    strategy_id: str = "",
    token_decimals: dict[str, int] = dict(),
)

Context for CEX execution.

Contains runtime information needed during execution.

get_decimals

get_decimals(token: str, default: int = 18) -> int

Get decimals for a token.

KrakenAdapter

KrakenAdapter(
    config: KrakenConfig | None = None,
    sdk: KrakenSDK | None = None,
    token_resolver: KrakenTokenResolver | None = None,
    chain_mapper: KrakenChainMapper | None = None,
)

Adapter for compiling intents into CEX ActionBundles.

This adapter handles the translation from abstract intents (SwapIntent, WithdrawIntent, DepositIntent) into concrete CEX actions with validation.

Example

adapter = KrakenAdapter(config, sdk)

Compile swap intent

intent = SwapIntent( from_token="USDC", to_token="ETH", amount=Decimal("1000"), venue="kraken", ) bundle = adapter.compile_intent(intent, context)

Execute (handled by orchestrator)

result = await adapter.execute_action(bundle.actions[0], context)

Initialize adapter.

Parameters:

Name Type Description Default
config KrakenConfig | None

Kraken configuration

None
sdk KrakenSDK | None

KrakenSDK instance. If not provided, will be created lazily.

None
token_resolver KrakenTokenResolver | None

Custom token resolver

None
chain_mapper KrakenChainMapper | None

Custom chain mapper

None

sdk property

sdk: KrakenSDK

Get or create SDK instance.

receipt_resolver property

receipt_resolver: KrakenReceiptResolver

Get or create receipt resolver.

compile_intent

compile_intent(
    intent: Any, context: ExecutionContext
) -> ActionBundle

Compile an intent into an ActionBundle.

Parameters:

Name Type Description Default
intent Any

The intent to compile

required
context ExecutionContext

Execution context

required

Returns:

Type Description
ActionBundle

ActionBundle ready for execution

Raises:

Type Description
ValueError

If intent type is not supported

execute_action async

execute_action(
    action: CEXAction, context: ExecutionContext
) -> tuple[CEXIdempotencyKey, str]

Execute a single CEX action.

Parameters:

Name Type Description Default
action CEXAction

The action to execute

required
context ExecutionContext

Execution context

required

Returns:

Type Description
CEXIdempotencyKey

Tuple of (idempotency_key, result_id)

str
  • For swaps: result_id is txid
tuple[CEXIdempotencyKey, str]
  • For withdrawals: result_id is refid
tuple[CEXIdempotencyKey, str]
  • For deposits: result_id is tx_hash

resolve_action async

resolve_action(
    action: CEXAction,
    key: CEXIdempotencyKey,
    context: ExecutionContext,
) -> ExecutionDetails

Wait for action completion and return result.

Parameters:

Name Type Description Default
action CEXAction

The action that was executed

required
key CEXIdempotencyKey

Idempotency key from execution

required
context ExecutionContext

Execution context

required

Returns:

Type Description
ExecutionDetails

ExecutionDetails with operation result

VenueType

Bases: str, Enum

Execution venue type.

KrakenAPIError

KrakenAPIError(errors: list[str])

Bases: KrakenError

Generic Kraken API error with error codes.

Wraps errors returned directly from the Kraken API.

KrakenAuthenticationError

Bases: KrakenError

Authentication failed with Kraken API.

Raised when: - API key is invalid or expired - API secret is incorrect - Insufficient permissions for the requested operation

KrakenChainNotSupportedError

KrakenChainNotSupportedError(chain: str, operation: str)

Bases: KrakenError

Chain is not supported for the requested operation.

KrakenDepositError

Bases: KrakenError

Deposit operation failed or not found.

KrakenError

Bases: Exception

Base exception for all Kraken-related errors.

KrakenInsufficientFundsError

KrakenInsufficientFundsError(
    message: str, asset: str, requested: str, available: str
)

Bases: KrakenError

Insufficient balance for the requested operation.

Raised when trying to trade or withdraw more than available balance.

KrakenMinimumOrderError

KrakenMinimumOrderError(
    message: str, pair: str, amount: str, minimum: str
)

Bases: KrakenError

Order amount is below Kraken's minimum.

Different trading pairs have different minimum order sizes.

KrakenOrderCancelledError

KrakenOrderCancelledError(
    order_id: str, reason: str | None = None
)

Bases: KrakenOrderError

Order was cancelled before completion.

KrakenOrderError

Bases: KrakenError

Order placement or query failed.

KrakenOrderNotFoundError

KrakenOrderNotFoundError(
    order_id: str, userref: int | None = None
)

Bases: KrakenOrderError

Order with given ID not found.

KrakenRateLimitError

KrakenRateLimitError(
    message: str, retry_after: int | None = None
)

Bases: KrakenError

Rate limit exceeded on Kraken API.

Kraken enforces strict rate limits. This error includes information about when to retry.

KrakenTimeoutError

KrakenTimeoutError(
    operation: str,
    timeout_seconds: int,
    identifier: str | None = None,
)

Bases: KrakenError

Operation timed out waiting for completion.

KrakenUnknownAssetError

KrakenUnknownAssetError(asset: str)

Bases: KrakenError

Asset is not supported or not found on Kraken.

KrakenUnknownPairError

KrakenUnknownPairError(pair: str)

Bases: KrakenError

Trading pair does not exist on Kraken.

KrakenWithdrawalAddressNotWhitelistedError

KrakenWithdrawalAddressNotWhitelistedError(
    address: str, asset: str, chain: str
)

Bases: KrakenWithdrawalError

Withdrawal address is not whitelisted on the Kraken account.

For security, Kraken requires withdrawal addresses to be pre-approved in the account settings.

KrakenWithdrawalError

Bases: KrakenError

Withdrawal operation failed.

KrakenWithdrawalLimitExceededError

KrakenWithdrawalLimitExceededError(
    message: str, amount: str, limit: str
)

Bases: KrakenWithdrawalError

Withdrawal exceeds daily or account limits.

CEXIdempotencyKey dataclass

CEXIdempotencyKey(
    action_id: str,
    exchange: str,
    operation_type: CEXOperationType,
    userref: int | None = None,
    refid: str | None = None,
    order_id: str | None = None,
    status: str = "pending",
    created_at: datetime = (lambda: datetime.now(UTC))(),
    last_poll: datetime | None = None,
)

Tracks CEX operation for idempotency and crash recovery.

This is persisted in ExecutionSession to enable: - Resuming pending operations after restart - Avoiding duplicate orders with the same userref - Tracking withdrawal refids for status polling

Attributes:

Name Type Description
action_id str

Unique identifier for the action in the bundle

exchange str

Exchange name (e.g., "kraken")

operation_type CEXOperationType

Type of operation (swap, withdraw, deposit)

userref int | None

Client order ID for swaps (int32, set at compile time)

refid str | None

Kraken withdrawal reference (set after API call)

order_id str | None

Kraken order/transaction ID (txid)

status str

Current status of the operation

created_at datetime

When the operation was initiated

last_poll datetime | None

Last time status was polled

to_dict

to_dict() -> dict

Serialize for state persistence.

from_dict classmethod

from_dict(data: dict) -> CEXIdempotencyKey

Deserialize from state.

CEXOperationType

Bases: str, Enum

Type of CEX operation.

CEXRiskConfig

Bases: BaseModel

CEX-specific risk parameters.

Used by RiskGuard to validate CEX operations.

lowercase_chains classmethod

lowercase_chains(v: list[str]) -> list[str]

Normalize chain names to lowercase.

KrakenBalance

Bases: BaseModel

Balance information for an asset on Kraken.

from_kraken_response classmethod

from_kraken_response(
    asset: str, data: dict
) -> KrakenBalance

Create from Kraken balance response.

KrakenConfig

Bases: BaseModel

Configuration for Kraken connector.

Example

config = KrakenConfig( credentials=KrakenCredentials.from_env(), default_slippage_bps=50, )

get_credentials

get_credentials() -> KrakenCredentials

Get credentials, loading from env if not configured.

KrakenCredentials

Bases: BaseModel

Kraken API credentials.

Security notes: - Credentials are stored using SecretStr to prevent accidental logging - Use from_env() to load from environment variables - Never commit credentials to version control

from_env classmethod

from_env(
    key_env: str = "KRAKEN_API_KEY",
    secret_env: str = "KRAKEN_API_SECRET",
) -> KrakenCredentials

Load credentials from environment variables.

Parameters:

Name Type Description Default
key_env str

Environment variable name for API key

'KRAKEN_API_KEY'
secret_env str

Environment variable name for API secret

'KRAKEN_API_SECRET'

Returns:

Type Description
KrakenCredentials

KrakenCredentials instance

Raises:

Type Description
ValueError

If environment variables are not set

model_post_init

model_post_init(__context: Any) -> None

Validate that credentials are not empty.

KrakenDepositStatus

Bases: str, Enum

Kraken deposit status values.

KrakenMarketInfo

Bases: BaseModel

Information about a Kraken trading pair.

Contains precision, minimum sizes, and fee information needed for order validation.

from_kraken_response classmethod

from_kraken_response(
    pair: str, data: dict
) -> KrakenMarketInfo

Create from Kraken API response.

Parameters:

Name Type Description Default
pair str

Trading pair name

required
data dict

Response from get_asset_pairs API

required

Returns:

Type Description
KrakenMarketInfo

KrakenMarketInfo instance

get_min_order_base

get_min_order_base(decimals: int) -> int

Get minimum order size in base asset wei units.

Parameters:

Name Type Description Default
decimals int

Token decimals

required

Returns:

Type Description
int

Minimum order in wei

get_min_cost_quote

get_min_cost_quote(decimals: int) -> int

Get minimum order cost in quote asset wei units.

Parameters:

Name Type Description Default
decimals int

Token decimals

required

Returns:

Type Description
int

Minimum cost in wei

KrakenOrderStatus

Bases: str, Enum

Kraken order status values.

KrakenWithdrawStatus

Bases: str, Enum

Kraken withdrawal status values.

ExecutionDetails dataclass

ExecutionDetails(
    success: bool,
    venue: str,
    operation_type: str,
    amounts_in: list[TokenAmount] = list(),
    amounts_out: list[TokenAmount] = list(),
    fees: list[TokenAmount] = list(),
    source_id: str = "",
    timestamp: datetime | None = None,
    cex_metadata: dict | None = None,
)

Standardized execution result for CEX and on-chain operations.

This provides a common interface for strategies to process results regardless of whether execution happened on-chain or CEX.

to_dict

to_dict() -> dict

Serialize to dict for state persistence.

from_dict classmethod

from_dict(data: dict) -> ExecutionDetails

Deserialize from dict.

KrakenReceiptResolver

KrakenReceiptResolver(
    sdk: KrakenSDK, config: KrakenConfig | None = None
)

Resolves CEX operation results with polling and retry logic.

This class handles: - Polling for operation completion with exponential backoff - Converting raw API responses to ExecutionDetails - Detecting stuck operations and generating alerts

Example

resolver = KrakenReceiptResolver(sdk, config)

Poll for swap completion

details = await resolver.resolve_swap( txid="OXXXXX-XXXXX", userref=12345, asset_in="USDC", asset_out="ETH", decimals_in=6, decimals_out=18, )

Poll for withdrawal completion

details = await resolver.resolve_withdrawal( refid="FXXXXX-XXXXX", asset="ETH", chain="arbitrum", decimals=18, )

Initialize receipt resolver.

Parameters:

Name Type Description Default
sdk KrakenSDK

KrakenSDK instance

required
config KrakenConfig | None

Optional configuration for timeouts and polling

None

resolve_swap async

resolve_swap(
    txid: str,
    userref: int,
    asset_in: str,
    asset_out: str,
    decimals_in: int,
    decimals_out: int,
    chain: str = "ethereum",
    idempotency_key: CEXIdempotencyKey | None = None,
) -> ExecutionDetails

Poll for swap completion and return execution details.

Parameters:

Name Type Description Default
txid str

Order transaction ID

required
userref int

Order reference for idempotency

required
asset_in str

Input asset symbol

required
asset_out str

Output asset symbol

required
decimals_in int

Input asset decimals

required
decimals_out int

Output asset decimals

required
chain str

Chain for token resolution

'ethereum'
idempotency_key CEXIdempotencyKey | None

Optional key for tracking last poll time

None

Returns:

Type Description
ExecutionDetails

ExecutionDetails with swap result

Raises:

Type Description
KrakenTimeoutError

If operation times out

resolve_withdrawal async

resolve_withdrawal(
    refid: str,
    asset: str,
    chain: str,
    decimals: int,
    to_address: str,
    amount: int,
    idempotency_key: CEXIdempotencyKey | None = None,
) -> ExecutionDetails

Poll for withdrawal completion and return execution details.

Parameters:

Name Type Description Default
refid str

Kraken withdrawal reference ID

required
asset str

Asset symbol

required
chain str

Target chain

required
decimals int

Asset decimals

required
to_address str

Destination address

required
amount int

Withdrawal amount in wei

required
idempotency_key CEXIdempotencyKey | None

Optional key for tracking

None

Returns:

Type Description
ExecutionDetails

ExecutionDetails with withdrawal result

Raises:

Type Description
KrakenTimeoutError

If operation times out

resolve_deposit async

resolve_deposit(
    tx_hash: str,
    asset: str,
    chain: str,
    decimals: int,
    amount: int,
    idempotency_key: CEXIdempotencyKey | None = None,
) -> ExecutionDetails

Poll for deposit confirmation on Kraken.

Parameters:

Name Type Description Default
tx_hash str

On-chain transaction hash of deposit

required
asset str

Asset symbol

required
chain str

Source chain

required
decimals int

Asset decimals

required
amount int

Deposit amount in wei

required
idempotency_key CEXIdempotencyKey | None

Optional key for tracking

None

Returns:

Type Description
ExecutionDetails

ExecutionDetails with deposit result

Raises:

Type Description
KrakenTimeoutError

If operation times out

resume_operation async

resume_operation(
    key: CEXIdempotencyKey, **context
) -> ExecutionDetails | None

Resume a pending operation after restart.

Uses the idempotency key to check operation status and either return the result or resume polling.

Parameters:

Name Type Description Default
key CEXIdempotencyKey

Idempotency key from persisted state

required
**context

Additional context (asset names, decimals, etc.)

{}

Returns:

Type Description
ExecutionDetails | None

ExecutionDetails if operation completed, None if still pending

TokenAmount dataclass

TokenAmount(token: str, amount: int, decimals: int = 18)

Amount of a specific token.

KrakenSDK

KrakenSDK(
    credentials: KrakenCredentials | None = None,
    config: KrakenConfig | None = None,
    token_resolver: KrakenTokenResolver | None = None,
    chain_mapper: KrakenChainMapper | None = None,
)

SDK for Kraken exchange operations.

Wraps the python-kraken-sdk library with additional functionality: - Token resolution (stack-v2 symbols -> Kraken symbols) - Chain mapping for deposits/withdrawals - Amount validation and precision handling - Status polling for async operations

Thread Safety

This class is NOT thread-safe. Use separate instances per thread or implement proper synchronization.

Example

sdk = KrakenSDK(KrakenCredentials.from_env())

Get available balance

balances = sdk.get_balances(["USDC", "ETH"]) print(f"USDC available: {balances['USDC'].available}")

Execute a swap

userref = sdk.generate_userref() txid = sdk.swap( asset_in="USDC", asset_out="ETH", amount_in=1000_000000, # 1000 USDC decimals_in=6, userref=userref, )

Initialize Kraken SDK.

Parameters:

Name Type Description Default
credentials KrakenCredentials | None

API credentials. If not provided, loads from env.

None
config KrakenConfig | None

SDK configuration. Uses defaults if not provided.

None
token_resolver KrakenTokenResolver | None

Custom token resolver. Uses default if not provided.

None
chain_mapper KrakenChainMapper | None

Custom chain mapper. Uses default if not provided.

None

get_all_balances

get_all_balances() -> dict[str, KrakenBalance]

Get all account balances.

Returns:

Type Description
dict[str, KrakenBalance]

Dict mapping Kraken asset symbol to KrakenBalance

get_balances

get_balances(
    assets: list[str], chain: str = "ethereum"
) -> dict[str, KrakenBalance]

Get balance information for specified assets.

Parameters:

Name Type Description Default
assets list[str]

List of token symbols (e.g., ["USDC", "ETH"])

required
chain str

Chain for token resolution

'ethereum'

Returns:

Type Description
dict[str, KrakenBalance]

Dict mapping asset symbol to KrakenBalance

get_balance

get_balance(
    asset: str, chain: str = "ethereum"
) -> KrakenBalance

Get balance for a single asset.

Parameters:

Name Type Description Default
asset str

Token symbol

required
chain str

Chain for token resolution

'ethereum'

Returns:

Type Description
KrakenBalance

KrakenBalance for the asset

get_market_info cached

get_market_info(
    base_asset: str,
    quote_asset: str,
    chain: str = "ethereum",
) -> KrakenMarketInfo

Get market information for a trading pair.

Parameters:

Name Type Description Default
base_asset str

Base token symbol

required
quote_asset str

Quote token symbol

required
chain str

Chain for token resolution

'ethereum'

Returns:

Type Description
KrakenMarketInfo

KrakenMarketInfo with pair details

Raises:

Type Description
KrakenUnknownPairError

If pair doesn't exist

market_exists

market_exists(
    base_asset: str,
    quote_asset: str,
    chain: str = "ethereum",
) -> bool

Check if a trading pair exists.

Also checks the inverse pair (quote/base).

Parameters:

Name Type Description Default
base_asset str

Base token symbol

required
quote_asset str

Quote token symbol

required
chain str

Chain for token resolution

'ethereum'

Returns:

Type Description
bool

True if pair exists (in either direction)

is_market_inverted

is_market_inverted(
    asset_in: str, asset_out: str, chain: str = "ethereum"
) -> bool

Check if market pair is inverted from asset_in/asset_out order.

Kraken markets have a specific base/quote ordering. This checks if the natural order (asset_in first) matches Kraken's order.

Parameters:

Name Type Description Default
asset_in str

Input asset symbol

required
asset_out str

Output asset symbol

required
chain str

Chain for token resolution

'ethereum'

Returns:

Type Description
bool

True if Kraken's base/quote is opposite to asset_in/asset_out

generate_userref staticmethod

generate_userref() -> int

Generate a unique userref for order idempotency.

The userref is a 32-bit signed integer that identifies an order for idempotency. It must be persisted before submitting the order.

Returns:

Type Description
int

Unique userref (int32)

validate_swap_amount

validate_swap_amount(
    asset_in: str,
    asset_out: str,
    amount_in: int,
    decimals_in: int,
    chain: str = "ethereum",
) -> int

Validate and floor swap amount to Kraken precision.

Parameters:

Name Type Description Default
asset_in str

Input asset symbol

required
asset_out str

Output asset symbol

required
amount_in int

Amount in wei units

required
decimals_in int

Decimals of input asset

required
chain str

Chain for token resolution

'ethereum'

Returns:

Type Description
int

Floored amount that meets Kraken requirements

Raises:

Type Description
KrakenMinimumOrderError

If amount is below minimum

KrakenInsufficientFundsError

If balance is insufficient

swap

swap(
    asset_in: str,
    asset_out: str,
    amount_in: int,
    decimals_in: int,
    userref: int,
    chain: str = "ethereum",
    deadline: int | None = None,
) -> str

Execute a market swap on Kraken.

Parameters:

Name Type Description Default
asset_in str

Input asset symbol (e.g., "USDC")

required
asset_out str

Output asset symbol (e.g., "ETH")

required
amount_in int

Amount in wei units

required
decimals_in int

Decimals of input asset

required
userref int

Unique order reference for idempotency

required
chain str

Chain for token resolution

'ethereum'
deadline int | None

Optional deadline timestamp

None

Returns:

Type Description
str

Order transaction ID (txid)

Raises:

Type Description
KrakenMinimumOrderError

If amount is below minimum

KrakenInsufficientFundsError

If balance is insufficient

KrakenAPIError

If API call fails

get_swap_status

get_swap_status(txid: str, userref: int) -> str

Get status of a swap order.

Parameters:

Name Type Description Default
txid str

Order transaction ID

required
userref int

Order reference

required

Returns:

Type Description
str

Status string: "pending", "success", "failed",

str

"partial", "cancelled", "unknown"

get_swap_result

get_swap_result(
    txid: str,
    userref: int,
    asset_in: str,
    asset_out: str,
    decimals_in: int,
    decimals_out: int,
    chain: str = "ethereum",
) -> dict[str, Any]

Get detailed result of a completed swap.

Parameters:

Name Type Description Default
txid str

Order transaction ID

required
userref int

Order reference

required
asset_in str

Input asset symbol

required
asset_out str

Output asset symbol

required
decimals_in int

Input asset decimals

required
decimals_out int

Output asset decimals

required
chain str

Chain for token resolution

'ethereum'

Returns:

Type Description
dict[str, Any]

Dict with: amount_in, amount_out, fee, average_price, timestamp

get_withdrawal_addresses

get_withdrawal_addresses(
    asset: str, chain: str
) -> set[str]

Get whitelisted withdrawal addresses.

Parameters:

Name Type Description Default
asset str

Asset symbol

required
chain str

Target chain

required

Returns:

Type Description
set[str]

Set of whitelisted addresses (checksummed)

get_withdrawal_key

get_withdrawal_key(
    asset: str, chain: str, address: str
) -> str

Get Kraken withdrawal key for an address.

Kraken requires a "key" (label) for withdrawals, not the address.

Parameters:

Name Type Description Default
asset str

Asset symbol

required
chain str

Target chain

required
address str

Destination address

required

Returns:

Type Description
str

Kraken withdrawal key

Raises:

Type Description
KrakenWithdrawalAddressNotWhitelistedError

If address not found

withdraw

withdraw(
    asset: str,
    chain: str,
    amount: int,
    decimals: int,
    to_address: str,
) -> str

Initiate a withdrawal from Kraken.

Parameters:

Name Type Description Default
asset str

Asset symbol

required
chain str

Target chain

required
amount int

Amount in wei units

required
decimals int

Asset decimals

required
to_address str

Destination address (must be whitelisted)

required

Returns:

Type Description
str

Withdrawal reference ID (refid)

Raises:

Type Description
KrakenWithdrawalAddressNotWhitelistedError

If address not whitelisted

KrakenInsufficientFundsError

If balance insufficient

get_withdrawal_status

get_withdrawal_status(
    asset: str,
    chain: str,
    refid: str | None = None,
    tx_hash: str | None = None,
) -> str | None

Get status of a withdrawal.

Parameters:

Name Type Description Default
asset str

Asset symbol

required
chain str

Target chain

required
refid str | None

Kraken reference ID (from withdraw())

None
tx_hash str | None

On-chain transaction hash (if available)

None

Returns:

Name Type Description
Status str | None

"pending", "success", "failed", or None if not found

get_withdrawal_tx_hash

get_withdrawal_tx_hash(
    asset: str, chain: str, refid: str
) -> str | None

Get on-chain transaction hash for a withdrawal.

Parameters:

Name Type Description Default
asset str

Asset symbol

required
chain str

Target chain

required
refid str

Kraken reference ID

required

Returns:

Type Description
str | None

On-chain tx hash if available, None otherwise

get_deposit_addresses

get_deposit_addresses(asset: str, chain: str) -> set[str]

Get Kraken deposit addresses for an asset.

Parameters:

Name Type Description Default
asset str

Asset symbol

required
chain str

Source chain

required

Returns:

Type Description
set[str]

Set of deposit addresses (checksummed)

get_deposit_status

get_deposit_status(
    tx_hash: str,
    asset: str | None = None,
    chain: str | None = None,
) -> str | None

Get status of a deposit by transaction hash.

Parameters:

Name Type Description Default
tx_hash str

On-chain transaction hash

required
asset str | None

Optional asset for filtering

None
chain str | None

Optional chain for filtering

None

Returns:

Name Type Description
Status str | None

"pending", "success", "failed", or None if not found

KrakenChainMapper

Maps stack-v2 chains to Kraken deposit/withdrawal method names.

Kraken uses specific method strings for deposits and withdrawals that include the chain name and sometimes the asset.

Example

mapper = KrakenChainMapper()

Get deposit method

method = mapper.get_deposit_method("arbitrum", "ETH")

Returns: "ETH - Arbitrum One (Unified)"

Get withdrawal method

method = mapper.get_withdraw_method("arbitrum")

Returns: "Arbitrum One"

get_deposit_method

get_deposit_method(chain: str, asset: str) -> str

Get Kraken deposit method name for a chain and asset.

Parameters:

Name Type Description Default
chain str

Chain name (e.g., "arbitrum")

required
asset str

Asset symbol (e.g., "ETH", "USDC")

required

Returns:

Type Description
str

Kraken deposit method string

Raises:

Type Description
KrakenChainNotSupportedError

If chain is not supported

get_withdraw_method

get_withdraw_method(chain: str) -> str

Get Kraken withdrawal method name for a chain.

Parameters:

Name Type Description Default
chain str

Chain name (e.g., "arbitrum")

required

Returns:

Type Description
str

Kraken withdrawal method string

Raises:

Type Description
KrakenChainNotSupportedError

If chain is not supported

get_supported_chains

get_supported_chains() -> list[str]

Get list of supported chains for deposits/withdrawals.

chain_from_network

chain_from_network(network_string: str) -> str | None

Parse Kraken network string to chain name.

Used when parsing deposit/withdrawal status responses.

Parameters:

Name Type Description Default
network_string str

Kraken network string from API response

required

Returns:

Type Description
str | None

Chain name or None if not recognized

parse_deposit_method

parse_deposit_method(
    method_string: str, expected_asset: str | None = None
) -> str | None

Parse deposit method string to extract chain.

Parameters:

Name Type Description Default
method_string str

Kraken deposit method (e.g., "ETH - Arbitrum One (Unified)")

required
expected_asset str | None

If provided, verify the asset matches

None

Returns:

Type Description
str | None

Chain name or None if parsing fails

KrakenTokenResolver

Maps stack-v2 tokens to Kraken symbols.

Kraken uses non-standard symbols for some assets: - ETH -> XETH (internal) - BTC -> XXBT (internal) - USD -> ZUSD (for some pairs)

This resolver handles the mapping in both directions.

Example

resolver = KrakenTokenResolver()

Convert to Kraken format

kraken_sym = resolver.to_kraken_symbol("arbitrum", "ETH") # "ETH" kraken_sym = resolver.to_kraken_symbol("arbitrum", "USDC.e") # "USDC"

Convert from Kraken format

standard = resolver.from_kraken_symbol("XETH") # "ETH"

to_kraken_symbol

to_kraken_symbol(chain: str, token: str) -> str

Convert stack-v2 token to Kraken symbol.

Parameters:

Name Type Description Default
chain str

Blockchain name (e.g., "arbitrum")

required
token str

Token symbol (e.g., "USDC.e", "ETH")

required

Returns:

Type Description
str

Kraken symbol for the token

from_kraken_symbol

from_kraken_symbol(symbol: str) -> str

Convert Kraken symbol to standard token symbol.

Parameters:

Name Type Description Default
symbol str

Kraken symbol (e.g., "XETH", "XXBT")

required

Returns:

Type Description
str

Standard token symbol

get_trading_pair

get_trading_pair(
    base_token: str,
    quote_token: str,
    chain: str = "ethereum",
) -> str

Get Kraken trading pair symbol.

Parameters:

Name Type Description Default
base_token str

Base asset symbol

required
quote_token str

Quote asset symbol

required
chain str

Chain for token resolution

'ethereum'

Returns:

Type Description
str

Trading pair (e.g., "ETHUSD")