hibachi_xyz package

Subpackages

Submodules

hibachi_xyz.api module

HTTP API client for Hibachi XYZ exchange.

This module provides the main HibachiApiClient class for interacting with the Hibachi exchange REST API, including market data queries, account management, and order operations.

class hibachi_xyz.api.HibachiApiClient(api_url: str = 'https://api.hibachi.xyz', data_api_url: str = 'https://data-api.hibachi.xyz', account_id: int | None = None, api_key: str | None = None, private_key: str | None = None, executor: HttpExecutor | None = None)[source][source]

Bases: object

Hibachi API client for trading operations.

Examples

from hibachi_xyz import HibachiApiClient
from dotenv import load_dotenv
import os

load_dotenv()

hibachi = HibachiApiClient(
    api_key=os.environ.get('HIBACHI_API_KEY', "your-api-key"),
    account_id=os.environ.get('HIBACHI_ACCOUNT_ID', "your-account-id"),
    private_key=os.environ.get('HIBACHI_PRIVATE_KEY', "your-private"),
)

account_info = hibachi.get_account_info()
print(f"Account Balance: {account_info.balance}")
print(f"Total Position Notional: {account_info.totalPositionNotional}")

exchange_info = hibachi.get_exchange_info()
print(exchange_info)
property account_id: int[source]

Get the current account ID.

Returns:

The account ID

Return type:

int

Raises:

ValidationError – If account_id has not been set

property api_key: str[source]

Get the current API key.

Returns:

The API key

Return type:

str

Raises:

ValidationError – If api_key has not been set

batch_orders(orders: list[CreateOrder | UpdateOrder | CancelOrder]) BatchResponse[source][source]

Submit multiple order operations in a single batch request.

Creates, updates, and cancels orders atomically in a single API call. All order details must be provided explicitly (no shortcuts for updates).

Parameters:

orders – List of order operations (CreateOrder, UpdateOrder, or CancelOrder)

Returns:

Response containing results for each order operation

Return type:

BatchResponse

Raises:

Example:

response = client.batch_orders([
    # Simple market order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent),
    # Simple limit order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent, price=90_000),
    # Trigger market order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent, trigger_price=85_000),
    # Trigger limit order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent, price=84_750, trigger_price=85_000),
    # TWAP order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent, twap_config=TWAPConfig(5, TWAPQuantityMode.FIXED)),
    # Update limit order (need all relevant optional parameters)
    UpdateOrder(limit_order_id, "BTC/USDT-P", Side.BUY, 0.001, max_fees_percent, price=60_000),
    # Cancel order
    CancelOrder(order_id=limit_order_id),
])
Endpoint:

POST /trade/orders

cancel_all_orders(contractId: int | None = None) dict[str, JsonValue][source][source]

Cancel all pending orders.

Cancels all currently pending orders for the account. Currently uses a workaround that individually cancels each order.

Parameters:

contractId – Contract ID to filter orders (optional, currently unused)

Returns:

The API response (empty dict when using workaround)

Return type:

Json

Example

client.cancel_all_orders()
Endpoint:

DELETE /trade/orders

cancel_order(order_id: int | None = None, nonce: int | None = None) dict[str, JsonValue][source][source]

Cancel an existing order.

Cancels an order using either the order ID or the nonce used when creating the order. At least one identifier must be provided.

Parameters:
  • order_id – The order ID to cancel (optional)

  • nonce – The nonce used when creating the order (optional)

Returns:

The API response

Return type:

Json

Raises:

ValidationError – If neither order_id nor nonce is provided

Example

client.cancel_order(order_id=123)
client.cancel_order(nonce=1234567)
Endpoint:

DELETE /trade/order

property future_contracts: dict[str, FutureContract][source]

Get the cached future contracts metadata.

Returns:

Dictionary mapping contract symbols to their metadata

Return type:

dict[str, FutureContract]

Raises:

ValidationError – If contracts have not been loaded yet (call get_exchange_info() first)

get_account_info() AccountInfo[source][source]

Get detailed account information.

Retrieves comprehensive account information including balance, positions, assets, fee rates, and withdrawal limits.

Returns:

Account details including balance, positions, assets,

order notional, unrealized PnL, and fee rates

Return type:

AccountInfo

Raises:

DeserializationError – If the API response cannot be parsed

Example

account_info = client.get_account_info()
print(account_info.balance)
Endpoint:

GET /trade/account/info

get_account_trades() AccountTradesResponse[source][source]

Get account trade history.

Retrieves the most recent trade history for your account, up to 100 records.

Returns:

List of recent trades with details including price,

quantity, side, fees, realized PnL, and timestamps

Return type:

AccountTradesResponse

Raises:

DeserializationError – If the API response cannot be parsed

Example

account_trades = client.get_account_trades()
Endpoint:

GET /trade/account/trades

get_capital_balance() CapitalBalance[source][source]

Get account balance including unrealized PnL.

Retrieves the net equity balance for your account, which includes unrealized profit and loss from open positions.

Returns:

Account balance as a string

Return type:

CapitalBalance

Raises:

DeserializationError – If the API response cannot be parsed

Example

capital_balance = client.get_capital_balance()
print(capital_balance.balance)
Endpoint:

GET /capital/balance

get_capital_history() CapitalHistory[source][source]

Get deposit and withdrawal history for your account.

Retrieves the most recent deposit and withdrawal transactions, up to 100 of each transaction type.

Returns:

List of transactions including deposits and withdrawals

Return type:

CapitalHistory

Raises:

DeserializationError – If the API response cannot be parsed

Example

capital_history = client.get_capital_history()
Endpoint:

GET /capital/history

get_deposit_info(public_key: str) DepositInfo[source][source]

Get deposit address information for a public key.

Retrieves the EVM deposit address associated with the specified public key.

Parameters:

public_key – The public key to get deposit info for

Returns:

Deposit address information containing the EVM deposit address

Return type:

DepositInfo

Raises:

DeserializationError – If the API response cannot be parsed

Endpoint:

GET /capital/deposit-info

get_exchange_info() ExchangeInfo[source][source]

Get exchange metadata and maintenance information.

Retrieves all available future contracts, fee configuration, withdrawal limits, and maintenance windows. The maintenance status can be “NORMAL”, “UNSCHEDULED_MAINTENANCE”, or “SCHEDULED_MAINTENANCE”.

Returns:

Exchange metadata including fee config, future contracts,

withdrawal limits, maintenance windows, and current status

Return type:

ExchangeInfo

Raises:

DeserializationError – If the API response cannot be parsed

Example

exchange_info = client.get_exchange_info()
print(exchange_info)
Endpoint:

GET /market/exchange-info

get_inventory() InventoryResponse[source][source]

Get market inventory with contract metadata and latest price information.

Similar to get_exchange_info, but includes current price data for all contracts, cross-chain assets, fee configuration, and trading tiers.

Returns:

Market inventory including cross-chain assets, fee config,

markets with contract and price info, and trading tiers

Return type:

InventoryResponse

Raises:

DeserializationError – If the API response cannot be parsed

Endpoint:

GET /market/inventory

get_klines(symbol: str, interval: Interval) KlinesResponse[source][source]

Get candlestick (K-line) data for a trading symbol.

Retrieves historical candlestick data at the specified time interval.

Parameters:
  • symbol – The trading symbol (e.g., “BTC/USDT-P”)

  • interval – The time interval for candlesticks (e.g., Interval.ONE_MINUTE)

Returns:

List of candlestick data with OHLCV information

Return type:

KlinesResponse

Raises:
Endpoint:

GET /market/data/klines

get_open_interest(symbol: str) OpenInterestResponse[source][source]

Get open interest for a trading symbol.

Retrieves the current open interest (total outstanding contracts) for the specified symbol.

Parameters:

symbol – The trading symbol (e.g., “BTC/USDT-P”)

Returns:

The open interest data

Return type:

OpenInterestResponse

Raises:
Endpoint:

GET /market/data/open-interest

get_order_details(order_id: int | None = None, nonce: int | None = None) Order[source][source]

Get detailed information for a specific order.

Retrieves order details using either the order ID or the nonce used when creating the order. At least one identifier must be provided.

Parameters:
  • order_id – The order ID to query (optional)

  • nonce – The nonce used when creating the order (optional)

Returns:

Order details including ID, type, side, price, quantity, status,

and timestamps

Return type:

Order

Raises:

Example

order_details = client.get_order_details(order_id=123)
# or
order_details = client.get_order_details(nonce=1234567)
Endpoint:

GET /trade/order

get_orderbook(symbol: str, depth: int, granularity: float) OrderBook[source][source]

Get orderbook price levels for a trading symbol.

Retrieves aggregated bid and ask price levels from the orderbook. Price levels are aggregated based on the specified granularity.

Parameters:
  • symbol – The trading symbol (e.g., “BTC/USDT-P”)

  • depth – Number of price levels to return on each side (1-100)

  • granularity – Price level granularity for aggregation (e.g., 0.01)

Returns:

Orderbook with bid and ask price levels containing price and quantity

Return type:

OrderBook

Raises:
Endpoint:

GET /market/data/orderbook

get_pending_orders() PendingOrdersResponse[source][source]

Get all pending orders for your account.

Retrieves all currently active orders including open, partially filled, and triggered orders.

Returns:

List of pending orders with details including order ID,

type, side, price, quantity, status, and timestamps

Return type:

PendingOrdersResponse

Raises:

DeserializationError – If the API response cannot be parsed

Example

pending_orders = client.get_pending_orders()
Endpoint:

GET /trade/orders

get_prices(symbol: str) PriceResponse[source][source]

Get current price information for a trading symbol.

Retrieves mark price, index price, and funding rate estimation for the specified symbol.

Parameters:

symbol – The trading symbol (e.g., “BTC/USDT-P”)

Returns:

Price information including mark price, index price, and funding rates

Return type:

PriceResponse

Raises:
Endpoint:

GET /market/data/prices

get_settlements_history() SettlementsResponse[source][source]

Get settlement history for your account.

Retrieves the history of settled trades, including position settlements and funding rate settlements.

Returns:

List of settlements with direction, price, quantity,

settled amount, symbol, and timestamp

Return type:

SettlementsResponse

Raises:

DeserializationError – If the API response cannot be parsed

Example

settlements = client.get_settlements_history()
Endpoint:

GET /trade/account/settlements_history

get_stats(symbol: str) StatsResponse[source][source]

Get 24-hour statistics for a trading symbol.

Retrieves 24-hour trading statistics including volume, high/low prices, and price changes.

Parameters:

symbol – The trading symbol (e.g., “BTC/USDT-P”)

Returns:

24-hour trading statistics

Return type:

StatsResponse

Raises:
Endpoint:

GET /market/data/stats

get_trades(symbol: str) TradesResponse[source][source]

Get recent trades for a trading symbol.

Retrieves the most recent executed trades for the specified symbol.

Parameters:

symbol – The trading symbol (e.g., “BTC/USDT-P”)

Returns:

List of recent trades with price, quantity, taker side, and timestamp

Return type:

TradesResponse

Raises:
Endpoint:

GET /market/data/trades

place_limit_order(symbol: str, quantity: Decimal | str | float | int, price: Decimal | str | float | int, side: Side, max_fees_percent: Decimal | str | float | int, trigger_price: Decimal | str | float | int | None = None, creation_deadline: Decimal | str | float | int | None = None, order_flags: OrderFlags | None = None, tpsl: TPSLConfig | None = None) tuple[int, int][source][source]

Place a limit order.

Submits a limit order that executes only at the specified price or better. Supports trigger prices and take-profit/stop-loss configurations.

Parameters:
  • symbol – The trading symbol (e.g., “BTC/USDT-P”)

  • quantity – The order quantity

  • price – The limit price

  • side – Order side (BUY, SELL, BID, or ASK)

  • max_fees_percent – Maximum fees as a percentage

  • trigger_price – Price to trigger order execution (optional)

  • creation_deadline – Deadline in seconds for order creation (optional)

  • order_flags – Additional order flags (optional)

  • tpsl – Take-profit/stop-loss configuration (optional)

Returns:

Tuple containing the nonce (defaults to current epoch timestamp in μs) and order ID

Return type:

tuple[Nonce, OrderId]

Raises:

DeserializationError – If the API response cannot be parsed

Example

(nonce, order_id) = client.place_limit_order("BTC/USDT-P", 0.0001, 80_000, Side.BUY, max_fees_percent)
(nonce, order_id) = client.place_limit_order("BTC/USDT-P", 0.0001, 80_000, Side.SELL, max_fees_percent)
(nonce, order_id) = client.place_limit_order("BTC/USDT-P", 0.0001, 80_000, Side.BID, max_fees_percent, creation_deadline=2)
(nonce, order_id) = client.place_limit_order("BTC/USDT-P", 0.0001, 1_001_000, Side.ASK, max_fees_percent, trigger_price=1_000_000)
(nonce, limit_order_id) = client.place_limit_order("BTC/USDT-P", 0.001, 6_000, Side.BID, max_fees_percent)
Endpoint:

POST /trade/order

place_market_order(symbol: str, quantity: Decimal | str | float | int, side: Side, max_fees_percent: Decimal | str | float | int, trigger_price: Decimal | str | float | int | None = None, twap_config: TWAPConfig | None = None, creation_deadline: Decimal | str | float | int | None = None, order_flags: OrderFlags | None = None, tpsl: TPSLConfig | None = None) tuple[int, int][source][source]

Place a market order.

Submits a market order that executes immediately at the current market price. Supports trigger prices, TWAP execution, and take-profit/stop-loss configurations.

Parameters:
  • symbol – The trading symbol (e.g., “BTC/USDT-P”)

  • quantity – The order quantity

  • side – Order side (BUY, SELL, BID, or ASK)

  • max_fees_percent – Maximum fees as a percentage

  • trigger_price – Price to trigger order execution (optional)

  • twap_config – Time-weighted average price configuration (optional)

  • creation_deadline – Deadline in seconds for order creation (optional)

  • order_flags – Additional order flags (optional)

  • tpsl – Take-profit/stop-loss configuration (optional)

Returns:

Tuple containing the nonce (defaults to current epoch timestamp in μs) and order ID

Return type:

tuple[Nonce, OrderId]

Raises:
  • ValueError – If both twap_config and trigger_price are set, or if twap_config and tpsl are set

  • DeserializationError – If the API response cannot be parsed

Example

(nonce, order_id) = client.place_market_order("BTC/USDT-P", 0.0001, Side.BUY, max_fees_percent)
(nonce, order_id) = client.place_market_order("BTC/USDT-P", 0.0001, Side.SELL, max_fees_percent)
(nonce, order_id) = client.place_market_order("BTC/USDT-P", 0.0001, Side.BID, max_fees_percent, creation_deadline=2)
(nonce, order_id) = client.place_market_order("BTC/USDT-P", 0.0001, Side.ASK, max_fees_percent, trigger_price=1_000_000)
(nonce, order_id) = client.place_market_order("SOL/USDT-P", 1, Side.BID, max_fees_percent, twap_config=twap_config)
Endpoint:

POST /trade/order

set_account_id(account_id: int | None) None[source][source]

Set the account ID for API requests.

Parameters:

account_id – The account ID (int, numeric string, or None)

Raises:

ValidationError – If the account_id is an invalid type or format

set_api_key(api_key: str | None) None[source][source]

Set the API key for authenticated requests.

Parameters:

api_key – The API key string (or None to clear)

Raises:

ValidationError – If the api_key is an invalid type

set_private_key(private_key: str) None[source][source]

Set the private key for signing requests.

Supports two formats:
  • Ethereum private key (hex string with or without 0x prefix) for wallet accounts

  • HMAC key (non-hex string) for web accounts

Parameters:

private_key – The private key as a hex string (with/without 0x) or HMAC key

transfer(coin: str, quantity: Decimal | str | float | int, dstPublicKey: str, max_fees: Decimal | str | float | int) TransferResponse[source][source]

Request fund transfer to another account.

Transfers funds from your account to another account identified by its public key.

Parameters:
  • coin – The coin to transfer (e.g., “USDT”)

  • quantity – The amount to transfer

  • dstPublicKey – Destination account’s public key

  • max_fees – Maximum fees as a percentage

Returns:

Response containing the transfer details

Return type:

TransferResponse

Raises:

DeserializationError – If the API response cannot be parsed

Endpoint:

POST /capital/transfer

update_order(order_id: int, max_fees_percent: Decimal | str | float | int, quantity: Decimal | str | float | int | None = None, price: Decimal | str | float | int | None = None, trigger_price: Decimal | str | float | int | None = None, creation_deadline: Decimal | str | float | int | None = None) dict[str, JsonValue][source][source]

Update an existing order.

Modifies the parameters of an existing order including quantity, price, and trigger price. The order is retrieved first to maintain unmodified fields.

Parameters:
  • order_id – The ID of the order to update

  • max_fees_percent – Maximum fees as a percentage

  • quantity – Updated order quantity (optional)

  • price – Updated limit price (optional)

  • trigger_price – Updated trigger price (optional)

  • creation_deadline – Deadline in seconds for update (optional)

Returns:

The API response

Return type:

Json

Raises:

Example

max_fees_percent = 0.0005
client.update_order(order_id, max_fees_percent, quantity=0.002)
client.update_order(order_id, max_fees_percent, price=1_050_000)
client.update_order(order_id, max_fees_percent, trigger_price=1_100_000)
client.update_order(order_id, max_fees_percent, quantity=0.001, price=1_210_000, trigger_price=1_250_000)
Endpoint:

PUT /trade/order

withdraw(coin: str, withdraw_address: str, quantity: str, max_fees: str, network: str = 'arbitrum') WithdrawResponse[source][source]

Submit a withdrawal request.

Submits a request to withdraw funds to an external address. The quantity must not exceed the maximalWithdraw value returned by get_account_info().

Parameters:
  • coin – The coin to withdraw (e.g., “USDT”)

  • withdraw_address – The destination withdrawal address

  • quantity – Amount to withdraw (must not exceed maximalWithdraw)

  • max_fees – Maximum fees allowed for the withdrawal

  • network – The blockchain network to withdraw on (default: “arbitrum”)

Returns:

Response containing the withdrawal order ID

Return type:

WithdrawResponse

Raises:

DeserializationError – If the API response cannot be parsed

Endpoint:

POST /capital/withdraw

hibachi_xyz.api.price_to_bytes(price: Decimal | str | float | int, contract: FutureContract) bytes[source][source]

Convert price to bytes representation for signing.

Converts a price value to an 8-byte representation adjusted for contract decimals and scaled by 2^32 for fixed-point representation.

Parameters:
  • price – The price value to convert

  • contract – The future contract containing decimal precision info

Returns:

8-byte big-endian representation of the scaled price

Return type:

bytes

hibachi_xyz.api.raise_response_errors(response: HttpResponse) None[source][source]

Check HTTP response status and raise appropriate errors.

Validates the response status code and raises pre-defined exceptions for non-2XX status codes with detailed error messages extracted from the response body.

Parameters:

response – The HTTP response to validate

Raises:

hibachi_xyz.api_ws_account module

WebSocket client for account data streams.

This module provides the HibachiWSAccountClient for streaming real-time account updates including balance changes and position updates via WebSocket.

class hibachi_xyz.api_ws_account.HibachiWSAccountClient(api_key: str, account_id: str, api_endpoint: str = 'https://api.hibachi.xyz', executor: WsExecutor | None = None)[source][source]

Bases: object

WebSocket client for streaming Hibachi account data.

Provides real-time updates for account balances and positions via WebSocket connection.

async connect() None[source][source]

Establish a WebSocket connection to the account data stream.

Creates an authenticated WebSocket connection with automatic retry logic using the provided API key and account ID.

Raises:

WebSocketConnectionError – If connection fails after retry attempts.

async disconnect() None[source][source]

Close the WebSocket connection and clean up resources.

Closes the WebSocket connection and resets the internal state. After calling this method, the client must call connect() and stream_start() again before listening for messages.

async listen() dict[str, JsonValue] | None[source][source]

Listen for and process a single message from the account stream.

Waits for a message from the WebSocket with a 15-second timeout. If a timeout occurs, automatically sends a ping to keep the stream alive. Dispatches received messages to registered event handlers based on topic.

Returns:

The parsed message as a JSON dictionary, or None if a timeout occurred or the connection was closed.

Raises:
  • ValidationError – If WebSocket connection is not established.

  • WebSocketConnectionError – If the WebSocket connection is closed unexpectedly.

  • Exception – For any other errors during message processing.

on(topic: str, handler: Callable[[dict[str, JsonValue]], Coroutine[None, None, None]]) None[source][source]

Register an event handler for a specific topic.

Registers a callback function that will be invoked when messages with the specified topic are received from the WebSocket.

Parameters:
  • topic – The topic name to listen for (e.g., ‘account_update’, ‘position_change’).

  • handler – An async callback function that accepts a message dictionary.

async ping() None[source][source]

Send a ping message to keep the account stream alive.

Sends a stream.ping request with the current listen key to prevent the server from closing the stream due to inactivity.

Raises:
  • ValueError – If listenKey is not initialized. Must call stream_start() first.

  • ValidationError – If WebSocket connection is not established.

async stream_start() AccountStreamStartResult[source][source]

Start the account data stream and retrieve the initial snapshot.

Sends a stream.start request to the WebSocket server and waits for the response containing the initial account snapshot and listen key. The listen key is stored for subsequent ping operations.

Returns:

AccountStreamStartResult containing the account snapshot (balance and positions) and the listen key for maintaining the stream.

Raises:
  • ValidationError – If WebSocket connection is not established.

  • KeyError – If the response format is unexpected or missing required fields.

property websocket: WsConnection[source]

Get the active WebSocket connection.

Returns:

The active WebSocket connection.

Raises:

ValidationError – If no WebSocket connection exists. Must call connect() first.

hibachi_xyz.api_ws_market module

WebSocket client for market data streams.

This module provides the HibachiWSMarketClient for subscribing to real-time market data including prices, order books, and trades via WebSocket.

class hibachi_xyz.api_ws_market.HibachiWSMarketClient(api_endpoint: str = 'https://data-api.hibachi.xyz', executor: WsExecutor | None = None)[source][source]

Bases: object

WebSocket client for streaming Hibachi market data.

Provides real-time market data including mark prices, order books, and trades.

async connect() Self[source][source]

Establish a WebSocket connection to the market data stream.

Creates a WebSocket connection with automatic retry logic and starts the receive loop task to handle incoming messages.

Returns:

This instance for method chaining.

Return type:

Self

Raises:

WebSocketConnectionError – If connection fails after retry attempts.

async disconnect() None[source][source]

Close the WebSocket connection and clean up resources.

Cancels the receive loop task, waits for it to complete, and closes the WebSocket connection. After calling this method, the client must call connect() again before subscribing to topics.

on(topic: str, handler: Callable[[dict[str, JsonValue]], Coroutine[None, None, None]]) None[source][source]

Register a callback for raw topic name (e.g., ‘mark_price’).

async subscribe(subscriptions: list[WebSocketSubscription]) None[source][source]

Subscribe to one or more market data topics.

Sends a subscribe request to the WebSocket server for the specified market data subscriptions (e.g., mark price, order book, trades).

Parameters:

subscriptions – List of WebSocketSubscription objects defining the topics and parameters to subscribe to.

Raises:

ValidationError – If WebSocket connection is not established.

async unsubscribe(subscriptions: list[WebSocketSubscription]) None[source][source]

Unsubscribe from one or more market data topics.

Sends an unsubscribe request to the WebSocket server to stop receiving updates for the specified market data subscriptions.

Parameters:

subscriptions – List of WebSocketSubscription objects defining the topics and parameters to unsubscribe from.

Raises:

ValidationError – If WebSocket connection is not established.

property websocket: WsConnection[source]

Get the active WebSocket connection.

Returns:

The active WebSocket connection.

Raises:

ValidationError – If no WebSocket connection exists. Must call connect() first.

hibachi_xyz.api_ws_trade module

WebSocket client for trade operations.

This module provides the HibachiWSTradeClient for placing, modifying, and canceling orders via WebSocket connections with lower latency than HTTP.

class hibachi_xyz.api_ws_trade.HibachiWSTradeClient(api_key: str, account_id: int | str, account_public_key: str, api_url: str = 'https://api.hibachi.xyz', data_api_url: str = 'https://data-api.hibachi.xyz', private_key: str | None = None, executor: WsExecutor | None = None)[source][source]

Bases: object

Trade Websocket Client is used to place, modify and cancel orders.

Examples

import asyncio
import os
from hibachi_xyz import HibachiWSTradeClient, print_data
from dotenv import load_dotenv

load_dotenv()

account_id = int(os.environ.get('HIBACHI_ACCOUNT_ID', "your-account-id"))
private_key = os.environ.get('HIBACHI_PRIVATE_KEY', "your-private")
api_key = os.environ.get('HIBACHI_API_KEY', "your-api-key")
public_key = os.environ.get('HIBACHI_PUBLIC_KEY', "your-public")

async def main():
    client = HibachiWSTradeClient(
        api_key=api_key,
        account_id=account_id,
        account_public_key=public_key,
        private_key=private_key
    )

    await client.connect()
    orders = await client.get_orders_status()
    first_order = orders.result[0]

    # single order
    order = await client.get_order_status(first_order.orderId)
    print_data(order)

    modify_result = await client.modify_order(
        order=order.result,
        quantity=float("0.002"),
        price=str(float("93500.0")),
        side=order.result.side,
        maxFeesPercent=float("0.00045"),
    )

    print_data(modify_result)

asyncio.run(main())
async batch_orders(params: OrdersBatchParams) WebSocketResponse[source][source]

Execute multiple order operations in a single request.

async cancel_all_orders() bool[source][source]

Cancel all orders.

async cancel_order(orderId: int | None, nonce: int | None) WebSocketResponse[source][source]

Cancel an existing order.

async connect() Self[source][source]

Establish WebSocket connection with retry logic.

async disconnect() None[source][source]

Close the WebSocket connection.

async enable_cancel_on_disconnect(params: EnableCancelOnDisconnectParams) WebSocketResponse[source][source]

Enable automatic order cancellation on WebSocket disconnect.

async get_order_status(orderId: int) OrderStatusResponse[source][source]

Get status of a specific order.

async get_orders_status() OrdersStatusResponse[source][source]

Get status of all orders.

async modify_order(order: Order, quantity: float, price: str, side: Side, maxFeesPercent: float, nonce: int | None = None) WebSocketResponse[source][source]

Modify an existing order.

async place_order(params: OrderPlaceParams) tuple[int, int][source][source]

Place a new order.

property websocket: WsConnection[source]

Get the WebSocket connection.

Returns:

Active WebSocket connection.

Raises:

ValidationError – If no connection exists. Call connect() first.

hibachi_xyz.connection module

Connection utilities for WebSocket connections.

async hibachi_xyz.connection.connect_with_retry(web_url: str, headers: list[tuple[str, str]] | None = None, executor: WsExecutor | None = None, max_retries: int = 10, retry_delay: float = 1, backoff_factor: float = 1.5) WsConnection[source][source]

Establish WebSocket connection with exponential backoff retry logic.

Attempts to connect up to max_retries times with exponentially increasing delays between attempts (starting at retry_delay seconds, doubling each time).

Parameters:
  • web_url – WebSocket URL to connect to

  • headers – Optional list of header tuples to send

  • executor – Optional WebSocket executor to use for connection

  • max_retries – Maximum number of connection attempts (default: 10)

  • retry_delay – Initial retry delay in seconds (default: 1)

  • backoff_factor – Factor to increase retry_delay with each retry

Returns:

Established WebSocket connection

Raises:

Exception – If connection fails after all retry attempts

hibachi_xyz.env_setup module

Environment configuration setup utilities.

This module provides functions for loading environment variables from .env files and configuring the SDK for local development.

hibachi_xyz.env_setup.setup_environment() tuple[str, str, str, int, str, str, str][source][source]

Load and return environment variables for Hibachi API configuration.

Loads environment variables from a .env file if present, otherwise falls back to system environment variables. Reads environment-specific variables based on the ENVIRONMENT variable (defaults to ‘production’).

Returns:

  • api_endpoint: The main API endpoint URL

  • data_api_endpoint: The data API endpoint URL

  • api_key: The API authentication key

  • account_id: The account ID as an integer

  • private_key: The private key for signing

  • public_key: The public key

  • dst_public_key: The destination public key for transfers

Return type:

Tuple

hibachi_xyz.errors module

Exception hierarchy for the Hibachi SDK.

This module defines the public exception hierarchy for the entire SDK. All exceptions raised by this library inherit from BaseError.

Exception Hierarchy

BaseError
  • ExchangeError - API server returned an error response.

  • TransportError - Network/protocol-level errors during transmission.

  • ValidationError - Client-side input validation failures.

exception hibachi_xyz.errors.BadGateway(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 502 Bad Gateway error.

exception hibachi_xyz.errors.BadHttpStatus(status_code: int, message: str)[source][source]

Bases: ExchangeError, HibachiApiError

Raised when response status from exchange is not 2XX.

message: str[source]
status_code: int[source]
exception hibachi_xyz.errors.BadRequest(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 400 Bad Request error.

exception hibachi_xyz.errors.BadWebsocketResponse[source][source]

Bases: ExchangeError

Raised when the server sends a websocket message indicating an error.

This is specifically an error in the action requested of the exchange. It is not an error with the websocket connection or protocol

exception hibachi_xyz.errors.BaseError[source][source]

Bases: Exception

Base exception for all Hibachi SDK errors.

All exceptions raised by this library inherit from this class, allowing users to catch all SDK-related errors with a single except clause.

This exception should not be raised directly. Use one of the specific subclasses instead (ExchangeError, TransportError, ValidationError).

exception hibachi_xyz.errors.DeserializationError(message: str)[source][source]

Bases: TransportError

Raised when response data cannot be deserialized/decoded.

exception hibachi_xyz.errors.ExchangeError[source][source]

Bases: BaseError

Exception raised when the API server returns an error response.

This exception is raised when a request successfully reaches the API server and the server returns a valid response, but that response indicates an error condition (e.g., invalid request, rate limit exceeded, authorization failure).

ExchangeError indicates that:
  • The network connection succeeded

  • The request was properly formatted and transmitted

  • A server processed the request and returned an error response

exception hibachi_xyz.errors.Forbidden(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 403 Forbidden error.

exception hibachi_xyz.errors.GatewayTimeout(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 504 Gateway Timeout error.

exception hibachi_xyz.errors.HibachiApiError[source][source]

Bases: Exception

Deprecated - use hibachi_xyz.errors.BadHttpStatus and subclasses.

exception hibachi_xyz.errors.HttpConnectionError(message: str, url: str | None = None)[source][source]

Bases: TransportError

Raised when a connection cannot be established or is lost.

exception hibachi_xyz.errors.InternalServerError(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 500 Internal Server Error.

exception hibachi_xyz.errors.MaintenanceOutage(message: str)[source][source]

Bases: ExchangeError

Raised when exchange cannot handle response due to maintenance.

exception hibachi_xyz.errors.MissingCredentialsError(credential_type: str = 'API key')[source][source]

Bases: ValidationError

Raised when required authentication credentials are missing.

exception hibachi_xyz.errors.NotFound(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 404 Not Found error.

exception hibachi_xyz.errors.RateLimited(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 429 Rate Limited error.

exception hibachi_xyz.errors.SerializationError(message: str)[source][source]

Bases: TransportError

Raised when request data cannot be serialized/encoded.

exception hibachi_xyz.errors.ServiceUnavailable(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 503 Service Unavailable error.

exception hibachi_xyz.errors.TransportError[source][source]

Bases: BaseError

Exception raised for errors in the process of transporting data to/from the API server.

This exception is raised when there’s a problem in the process of transporting data to or from the API server, either in the local networking stack before data is sent, during transmission over the network, or when receiving and processing data.

TransportError indicates that:
  • The error occurred in the process of transporting data

  • Valid application-level data was not successfully exchanged

  • The error could be transient and may succeed on retry

Common causes include:

Local stack errors (before transmission):
  • Serialization failures (unable to encode data)

  • TLS/SSL certificate errors

  • Local socket/file descriptor exhaustion

  • DNS resolution failures

  • Proxy configuration errors

Network errors (during transmission):
  • Connection timeouts

  • Connection refused or dropped

  • Network unreachable

  • TLS/SSL handshake failures

  • Read/write timeouts

Protocol/data handling errors (after transmission):
  • Malformed protocol responses

  • Unexpected connection closure

  • WebSocket connection drops

  • Deserialization failures (malformed or corrupt data)

exception hibachi_xyz.errors.TransportTimeoutError(message: str, timeout_seconds: float | None = None)[source][source]

Bases: TransportError

Raised when a request or connection times out.

exception hibachi_xyz.errors.Unauthorized(status_code: int, message: str)[source][source]

Bases: BadHttpStatus

Raised when the server returns a 401 Unauthorized error.

exception hibachi_xyz.errors.ValidationError[source][source]

Bases: BaseError

Exception raised for client-side input validation failures.

This exception is raised when input parameters fail validation checks before any request is sent to the API server. ValidationError indicates a problem with the arguments provided to SDK methods, such as missing required fields, invalid types, out-of-range values, or malformed data.

ValidationError indicates that:
  • No network request was attempted

  • The error is due to invalid input from the caller

  • The error can be fixed by correcting the input parameters

Common causes include:
  • Missing required parameters

  • Invalid parameter types (e.g., string instead of number)

  • Out-of-range values

  • Malformed identifiers or formats

  • Mutually exclusive parameters specified together

exception hibachi_xyz.errors.WebSocketConnectionError(message: str, url: str | None = None)[source][source]

Bases: TransportError

Raised when WebSocket connection fails or is closed unexpectedly.

exception hibachi_xyz.errors.WebSocketMessageError(message: str)[source][source]

Bases: TransportError

Raised when there’s an error processing a WebSocket message.

hibachi_xyz.helpers module

Helper utilities for the Hibachi Python SDK.

This module contains utility functions for serialization, deserialization, API response handling, WebSocket management, and display formatting.

hibachi_xyz.helpers.absolute_creation_deadline(relative_creation_deadline: Decimal) int[source][source]

Convert a relative creation deadline (in seconds) to an absolute timestamp.

Note: This is based on wall time and can drift. Server-side uses NTP with chrony AWS Time Sync Service. If client time is significantly off from server time, this may not function as expected.

TODO: This should be able to return a float but API server currently can’t handle that

Parameters:

relative_creation_deadline – Deadline in seconds from now

Returns:

Unix timestamp as integer

hibachi_xyz.helpers.check_maintenance_window(response: dict[str, JsonValue]) None[source][source]

Check API response for maintenance status and raise exception if found.

This function inspects an API response for a status field indicating exchange health. The exchange can be in one of three states:

  • NORMAL: Exchange is operating normally (no exception raised)

  • SCHEDULED_MAINTENANCE: Exchange is undergoing scheduled maintenance with known timing

  • UNSCHEDULED_MAINTENANCE: Exchange is undergoing unscheduled maintenance

When any MAINTENANCE status is detected, a MaintenanceOutage exception is raised with details about the maintenance window timing (if available for scheduled maintenance).

Parameters:

response – JSON response from the API containing potential maintenance information

Raises:

MaintenanceOutage – If status is anything other than “NORMAL”, with a message containing human-readable UTC timestamps for scheduled windows

hibachi_xyz.helpers.create_with(func: Callable[[...], T], data: Dict[str, Any], *, implicit_null: bool = False) T[source][source]

Create an object from a dictionary, filtering to only valid parameters.

This allows constructing objects from API responses that may contain additional fields beyond what the constructor expects, making the SDK more resilient to API changes.

Parameters:
  • func – Constructor or factory function to call

  • data – Dictionary of data to pass as kwargs

  • implicit_null – If True, add explicit None values for required nullable fields

Returns:

Instance created by calling func with filtered data

hibachi_xyz.helpers.decimal_as_str(obj: object) str[source][source]

Serialize Decimal objects to JSON strings.

Converts Decimal to string to preserve precision in JSON serialization.

hibachi_xyz.helpers.deserialize_batch_response_order(data: dict[str, JsonValue]) CreateOrderBatchResponse | UpdateOrderBatchResponse | CancelOrderBatchResponse | ErrorBatchResponse[source][source]

Deserialize a batch response order based on which fields are present.

Logic:
  • If ‘errorCode’ is present -> ErrorBatchResponse

  • If both ‘nonce’ and ‘orderId’ are present -> CreateOrderBatchResponse

  • If only ‘orderId’ is present -> UpdateOrderBatchResponse

  • If only ‘nonce’ is present -> CancelOrderBatchResponse

Parameters:

data – JSON object to deserialize

Returns:

Appropriate batch response type

Raises:

DeserializationError – If the data cannot be deserialized into any known type

hibachi_xyz.helpers.deserialize_response(response_body: bytes, url: str) dict[str, JsonValue][source][source]

Deserialize a JSON response body.

Parameters:
  • response_body – Response bytes to deserialize

  • url – URL that was requested (for error messages)

Returns:

Deserialized JSON object or array

Raises:

DeserializationError – If deserialization fails

hibachi_xyz.helpers.format_maintenance_window(window_info: MaintenanceWindow | None) str[source][source]

Format maintenance window information into a user-friendly string.

Parameters:

window_info – Maintenance window information from get_next_maintenance_window

Returns:

Formatted string with maintenance window details

hibachi_xyz.helpers.get_hibachi_client() str[source][source]

Get the Hibachi client identification string.

hibachi_xyz.helpers.get_next_maintenance_window(exchange_info: ExchangeInfo) MaintenanceWindow | None[source][source]

Get the next scheduled maintenance window if any exists.

Parameters:

exchange_info – The exchange information containing maintenance windows

Returns:

Details about the next maintenance window or None if none exists

hibachi_xyz.helpers.get_withdrawal_fee_for_amount(exchange_info: ExchangeInfo, amount: Decimal | str | float | int) int | float[source][source]

Calculate the instant withdrawal fee for a given amount.

Fees are tiered based on withdrawal amount. This function finds the appropriate fee tier for the given amount.

Parameters:
  • exchange_info – The exchange information containing fee tiers

  • amount – Withdrawal amount

Returns:

Fee percentage/amount for the withdrawal

hibachi_xyz.helpers.print_data(response: Any) None[source][source]

Pretty-print response data, handling dataclasses specially.

Dataclass instances are converted to dictionaries before printing for better formatting.

Parameters:

response – Data to print

hibachi_xyz.helpers.serialize_request(request: dict[str, JsonValue] | None) bytes | None[source][source]

Serialize a request object to JSON bytes.

Uses orjson for fast serialization with custom Decimal handling.

Parameters:

request – Request data to serialize

Returns:

JSON bytes or None if request is None

Raises:

SerializationError – If serialization fails

hibachi_xyz.types module

Type definitions for the Hibachi Python SDK.

This module contains type definitions, enums, and dataclasses used throughout the SDK, organized into logical sections for clarity.

class hibachi_xyz.types.AccountInfo(assets: List[Asset], balance: str, maximalWithdraw: str, numFreeTransfersRemaining: int, positions: List[Position], totalOrderNotional: str, totalPositionNotional: str, totalUnrealizedFundingPnl: str, totalUnrealizedPnl: str, totalUnrealizedTradingPnl: str, tradeMakerFeeRate: str, tradeTakerFeeRate: str)[source][source]

Bases: object

Complete account information.

assets: List[Asset][source]
balance: str[source]
maximalWithdraw: str[source]
numFreeTransfersRemaining: int[source]
positions: List[Position][source]
totalOrderNotional: str[source]
totalPositionNotional: str[source]
totalUnrealizedFundingPnl: str[source]
totalUnrealizedPnl: str[source]
totalUnrealizedTradingPnl: str[source]
tradeMakerFeeRate: str[source]
tradeTakerFeeRate: str[source]
class hibachi_xyz.types.AccountSnapshot(account_id: int, balance: str, positions: List[Position])[source][source]

Bases: object

Snapshot of account state.

account_id: int[source]
balance: str[source]
positions: List[Position][source]
class hibachi_xyz.types.AccountStreamStartResult(accountSnapshot: AccountSnapshot, listenKey: str)[source][source]

Bases: object

Result from starting account stream.

accountSnapshot: AccountSnapshot[source]
listenKey: str[source]
class hibachi_xyz.types.AccountTrade(askAccountId: int, askOrderId: int, bidAccountId: int, bidOrderId: int, fee: str, id: int, orderType: str, price: str, quantity: str, realizedPnl: str, side: str, symbol: str, timestamp: int)[source][source]

Bases: object

Individual account trade record.

askAccountId: int[source]
askOrderId: int[source]
bidAccountId: int[source]
bidOrderId: int[source]
fee: str[source]
id: int[source]
orderType: str[source]
price: str[source]
quantity: str[source]
realizedPnl: str[source]
side: str[source]
symbol: str[source]
timestamp: int[source]
class hibachi_xyz.types.AccountTradesResponse(trades: List[AccountTrade])[source][source]

Bases: object

Response containing account trades.

trades: List[AccountTrade][source]
class hibachi_xyz.types.Asset(quantity: str, symbol: str)[source][source]

Bases: object

Asset balance information.

quantity: str[source]
symbol: str[source]
class hibachi_xyz.types.BatchOrder(action: str, nonce: int, symbol: str | None = None, orderType: OrderType | None = None, side: Side | None = None, quantity: str | None = None, price: str | None = None, maxFeesPercent: str | None = None, orderId: str | None = None, updatedQuantity: str | None = None, updatedPrice: str | None = None, signature: str | None = None)[source][source]

Bases: object

Batch order operation.

action: str[source]
maxFeesPercent: str | None = None[source]
nonce: int[source]
orderId: str | None = None[source]
orderType: OrderType | None = None[source]
price: str | None = None[source]
quantity: str | None = None[source]
side: Side | None = None[source]
signature: str | None = None[source]
symbol: str | None = None[source]
updatedPrice: str | None = None[source]
updatedQuantity: str | None = None[source]
class hibachi_xyz.types.BatchResponse(orders: list[CreateOrderBatchResponse | UpdateOrderBatchResponse | CancelOrderBatchResponse | ErrorBatchResponse])[source][source]

Bases: object

Response containing multiple order operations.

orders: list[CreateOrderBatchResponse | UpdateOrderBatchResponse | CancelOrderBatchResponse | ErrorBatchResponse][source]
class hibachi_xyz.types.CancelOrder(order_id: int | None = None, nonce: int | None = None)[source][source]

Bases: object

Request to cancel an order.

action: str = 'cancel'[source]
nonce: int | None[source]
order_id: int | None[source]
class hibachi_xyz.types.CancelOrderBatchResponse(nonce: str)[source][source]

Bases: object

Success response to a cancel order request.

nonce: str[source]
class hibachi_xyz.types.CapitalBalance(balance: str)[source][source]

Bases: object

Account capital balance.

balance: str[source]
class hibachi_xyz.types.CapitalHistory(transactions: List[Transaction])[source][source]

Bases: object

Transaction history.

transactions: List[Transaction][source]
class hibachi_xyz.types.CreateOrder(symbol: str, side: Side, quantity: Decimal | str | float | int, max_fees_percent: Decimal | str | float | int, price: Decimal | str | float | int | None = None, trigger_price: Decimal | str | float | int | None = None, twap_config: TWAPConfig | None = None, creation_deadline: Decimal | str | float | int | None = None, parent_order: OrderIdVariant | None = None, order_flags: OrderFlags | None = None, trigger_direction: TriggerDirection | None = None)[source][source]

Bases: object

Request to create a new order.

action: str = 'place'[source]
creation_deadline: Decimal | None[source]
max_fees_percent: Decimal[source]
order_flags: OrderFlags | None[source]
parent_order: OrderIdVariant | None[source]
price: Decimal | None[source]
quantity: Decimal[source]
side: Side[source]
symbol: str[source]
trigger_direction: TriggerDirection | None[source]
trigger_price: Decimal | None[source]
twap_config: TWAPConfig | None[source]
class hibachi_xyz.types.CreateOrderBatchResponse(nonce: int, orderId: str, creationTime: str, creationTimeNsPartial: str)[source][source]

Bases: object

Success response to a create order request.

creationTime: str[source]
creationTimeNsPartial: str[source]
nonce: int[source]
orderId: str[source]
class hibachi_xyz.types.CrossChainAsset(chain: str, exchangeRateFromUSDT: str, exchangeRateToUSDT: str, instantWithdrawalLowerLimitInUSDT: str, instantWithdrawalUpperLimitInUSDT: str, token: str)[source][source]

Bases: object

Cross-chain asset information.

chain: str[source]
exchangeRateFromUSDT: str[source]
exchangeRateToUSDT: str[source]
instantWithdrawalLowerLimitInUSDT: str[source]
instantWithdrawalUpperLimitInUSDT: str[source]
token: str[source]
class hibachi_xyz.types.DepositInfo(depositAddressEvm: str)[source][source]

Bases: object

Deposit information.

depositAddressEvm: str[source]
class hibachi_xyz.types.EnableCancelOnDisconnectParams(nonce: int)[source][source]

Bases: object

Parameters to enable cancel-on-disconnect.

nonce: int[source]
class hibachi_xyz.types.ErrorBatchResponse(errorCode: int, message: str, status: str)[source][source]

Bases: object

Error response for batch operations.

as_exception() ExchangeError[source][source]

Convert error response to an ExchangeError exception.

Returns:

ExchangeError instance with formatted error details.

errorCode: int[source]
message: str[source]
status: str[source]
class hibachi_xyz.types.ExchangeInfo(feeConfig: FeeConfig, futureContracts: List[FutureContract], instantWithdrawalLimit: WithdrawalLimit, maintenanceWindow: List[MaintenanceWindow], status: str)[source][source]

Bases: object

Exchange configuration and status information.

feeConfig: FeeConfig[source]
futureContracts: List[FutureContract][source]
instantWithdrawalLimit: WithdrawalLimit[source]
maintenanceWindow: List[MaintenanceWindow][source]
status: str[source]
class hibachi_xyz.types.FeeConfig(depositFees: str, instantWithdrawDstPublicKey: str, instantWithdrawalFees: List[List[int | float]], tradeMakerFeeRate: str, tradeTakerFeeRate: str, transferFeeRate: str, withdrawalFees: str)[source][source]

Bases: object

Fee configuration for the exchange.

depositFees: str[source]
instantWithdrawDstPublicKey: str[source]
instantWithdrawalFees: List[List[int | float]][source]
tradeMakerFeeRate: str[source]
tradeTakerFeeRate: str[source]
transferFeeRate: str[source]
withdrawalFees: str[source]
class hibachi_xyz.types.FundingRateEstimation(estimatedFundingRate: str, nextFundingTimestamp: int)[source][source]

Bases: object

Estimated funding rate information.

estimatedFundingRate: str[source]
nextFundingTimestamp: int[source]
class hibachi_xyz.types.FutureContract(displayName: str, id: int, minNotional: str, minOrderSize: str, orderbookGranularities: List[str], initialMarginRate: str, maintenanceMarginRate: str, settlementDecimals: int, settlementSymbol: str, status: str, stepSize: str, symbol: str, tickSize: str, underlyingDecimals: int, underlyingSymbol: str, marketCloseTimestamp: str | None = None, marketOpenTimestamp: str | None = None, marketCreationTimestamp: str | None = None)[source][source]

Bases: object

Future contract specification.

displayName: str[source]
id: int[source]
initialMarginRate: str[source]
maintenanceMarginRate: str[source]
marketCloseTimestamp: str | None = None[source]
marketCreationTimestamp: str | None = None[source]
marketOpenTimestamp: str | None = None[source]
minNotional: str[source]
minOrderSize: str[source]
orderbookGranularities: List[str][source]
settlementDecimals: int[source]
settlementSymbol: str[source]
status: str[source]
stepSize: str[source]
symbol: str[source]
tickSize: str[source]
underlyingDecimals: int[source]
underlyingSymbol: str[source]
class hibachi_xyz.types.Interval(*values)[source][source]

Bases: Enum

Time intervals for klines/candlestick data.

FIFTEEN_MINUTES = '15min'[source]
FIVE_MINUTES = '5min'[source]
FOUR_HOURS = '4h'[source]
ONE_DAY = '1d'[source]
ONE_HOUR = '1h'[source]
ONE_MINUTE = '1min'[source]
ONE_WEEK = '1w'[source]
class hibachi_xyz.types.InventoryResponse(crossChainAssets: List[CrossChainAsset], feeConfig: FeeConfig, markets: List[Market], tradingTiers: List[TradingTier])[source][source]

Bases: object

Complete inventory information response.

crossChainAssets: List[CrossChainAsset][source]
feeConfig: FeeConfig[source]
markets: List[Market][source]
tradingTiers: List[TradingTier][source]
class hibachi_xyz.types.Kline(close: str, high: str, low: str, open: str, interval: str, timestamp: int, volumeNotional: str)[source][source]

Bases: object

Candlestick/kline data.

close: str[source]
high: str[source]
interval: str[source]
low: str[source]
open: str[source]
timestamp: int[source]
volumeNotional: str[source]
class hibachi_xyz.types.KlinesResponse(klines: List[Kline])[source][source]

Bases: object

Response containing kline data.

klines: List[Kline][source]
class hibachi_xyz.types.MaintenanceWindow(begin: float, end: float, note: str)[source][source]

Bases: object

Scheduled maintenance window.

begin: float[source]
end: float[source]
note: str[source]
class hibachi_xyz.types.Market(contract: FutureContract, info: MarketInfo)[source][source]

Bases: object

Market combining contract and info.

contract: FutureContract[source]
info: MarketInfo[source]
class hibachi_xyz.types.MarketInfo(category: str, markPrice: str, price24hAgo: str, priceLatest: str, tags: List[str])[source][source]

Bases: object

Market information for a specific contract.

category: str[source]
markPrice: str[source]
price24hAgo: str[source]
priceLatest: str[source]
tags: List[str][source]
class hibachi_xyz.types.OpenInterestResponse(totalQuantity: str)[source][source]

Bases: object

Open interest information.

totalQuantity: str[source]
class hibachi_xyz.types.Order(accountId: int, availableQuantity: str, orderId: str | int, orderType: str, side: str, status: str, symbol: str, numOrdersRemaining: int | None = None, numOrdersTotal: int | None = None, quantityMode: str | None = None, finishTime: int | None = None, price: str | None = None, totalQuantity: str | None = None, creationTime: int | None = None, contractId: int | None = None, orderFlags: str | None = None, triggerPrice: str | None = None)[source][source]

Bases: object

Represents an order in the exchange.

accountId: int[source]
availableQuantity: str[source]
contractId: int | None[source]
creationTime: int | None[source]
finishTime: int | None[source]
numOrdersRemaining: int | None[source]
numOrdersTotal: int | None[source]
orderFlags: OrderFlags | None[source]
orderId: int[source]
orderType: OrderType[source]
price: str | None[source]
quantityMode: str | None[source]
side: Side[source]
status: OrderStatus[source]
symbol: str[source]
totalQuantity: str | None[source]
triggerPrice: str | None[source]
class hibachi_xyz.types.OrderBook(ask: List[OrderBookLevel], bid: List[OrderBookLevel])[source][source]

Bases: object

Orderbook containing bid and ask levels.

ask: List[OrderBookLevel][source]
bid: List[OrderBookLevel][source]
class hibachi_xyz.types.OrderBookLevel(price: str, quantity: str)[source][source]

Bases: object

Single orderbook price level.

price: str[source]
quantity: str[source]
class hibachi_xyz.types.OrderCancelParams(orderId: str, accountId: str, nonce: int)[source][source]

Bases: object

Parameters for canceling an order.

accountId: str[source]
nonce: int[source]
orderId: str[source]
class hibachi_xyz.types.OrderFlags(*values)[source][source]

Bases: Enum

Order execution flags.

Ioc = 'IOC'[source]
PostOnly = 'POST_ONLY'[source]
ReduceOnly = 'REDUCE_ONLY'[source]
class hibachi_xyz.types.OrderIdVariant(nonce: int | None, order_id: int | None)[source][source]

Bases: object

Represents either a nonce or order_id for order identification.

classmethod from_nonce(nonce: int) Self[source][source]

Create an OrderIdVariant from a nonce.

Parameters:

nonce – The nonce value to use for order identification.

Returns:

OrderIdVariant instance with nonce set and order_id as None.

Raises:

ValueError – If nonce is None.

classmethod from_order_id(order_id: int) Self[source][source]

Create an OrderIdVariant from an order_id.

Parameters:

order_id – The order ID value to use for order identification.

Returns:

OrderIdVariant instance with order_id set and nonce as None.

Raises:

ValueError – If order_id is None.

nonce: int | None[source]
order_id: int | None[source]
to_dict() Dict[str, Any][source][source]

Convert OrderIdVariant to dictionary representation.

Returns:

Dictionary with either ‘nonce’ or ‘orderId’ key and string value.

Raises:

ValueError – If both nonce and order_id are None.

class hibachi_xyz.types.OrderModifyParams(orderId: str, accountId: int, symbol: str, quantity: Decimal | str | float | int, price: Decimal | str | float | int, side: Side, maxFeesPercent: Decimal | str | float | int, nonce: int | None = None)[source][source]

Bases: object

Parameters for modifying an order.

accountId: int[source]
maxFeesPercent: Decimal[source]
nonce: int | None[source]
orderId: str[source]
price: Decimal[source]
quantity: Decimal[source]
side: Side[source]
symbol: str[source]
class hibachi_xyz.types.OrderPlaceParams(symbol: str, quantity: Decimal | str | float | int, side: Side, orderType: OrderType, maxFeesPercent: Decimal | str | float | int, price: Decimal | str | float | int | None = None, trigger_price: Decimal | str | float | int | None = None, twap_config: TWAPConfig | None = None, orderFlags: str | None = None, creation_deadline: int | None = None, trigger_direction: TriggerDirection | None = None)[source][source]

Bases: object

Parameters for placing an order via REST.

creation_deadline: Decimal | None[source]
maxFeesPercent: Decimal[source]
orderFlags: str | None[source]
orderType: OrderType[source]
price: Decimal | None[source]
quantity: Decimal[source]
side: Side[source]
symbol: str[source]
trigger_direction: TriggerDirection | None[source]
trigger_price: Decimal | None[source]
twap_config: TWAPConfig | None[source]
class hibachi_xyz.types.OrderPlaceResponse(id: int, result: OrderPlaceResponseResult, status: int)[source][source]

Bases: object

Response from placing an order.

id: int[source]
result: OrderPlaceResponseResult[source]
status: int[source]
class hibachi_xyz.types.OrderPlaceResponseResult(orderId: str)[source][source]

Bases: object

Result of order placement.

orderId: str[source]
class hibachi_xyz.types.OrderResponse(accountId: str, availableQuantity: str, orderId: str, orderType: OrderType, price: str, side: Side, status: OrderStatus, symbol: str, totalQuantity: str)[source][source]

Bases: object

Order information in response.

accountId: str[source]
availableQuantity: str[source]
orderId: str[source]
orderType: OrderType[source]
price: str[source]
side: Side[source]
status: OrderStatus[source]
symbol: str[source]
totalQuantity: str[source]
class hibachi_xyz.types.OrderStatus(*values)[source][source]

Bases: Enum

Order status.

CANCELLED = 'CANCELLED'[source]
CHILD_PENDING = 'CHILD_PENDING'[source]
FILLED = 'FILLED'[source]
PARTIALLY_FILLED = 'PARTIALLY_FILLED'[source]
PENDING = 'PENDING'[source]
PLACED = 'PLACED'[source]
REJECTED = 'REJECTED'[source]
SCHEDULED_TWAP = 'SCHEDULED_TWAP'[source]
class hibachi_xyz.types.OrderStatusParams(orderId: str, accountId: str)[source][source]

Bases: object

Parameters for querying order status.

accountId: str[source]
orderId: str[source]
class hibachi_xyz.types.OrderStatusResponse(id: int, result: Order, status: int | None)[source][source]

Bases: object

Response containing single order status.

id: int[source]
result: Order[source]
status: int | None[source]
class hibachi_xyz.types.OrderType(*values)[source][source]

Bases: Enum

Order type.

LIMIT = 'LIMIT'[source]
MARKET = 'MARKET'[source]
class hibachi_xyz.types.OrdersBatchParams(accountId: str, orders: List[BatchOrder])[source][source]

Bases: object

Parameters for batch order operations.

accountId: str[source]
orders: List[BatchOrder][source]
class hibachi_xyz.types.OrdersCancelParams(accountId: str, nonce: str, contractId: int | None = None)[source][source]

Bases: object

Parameters for bulk order cancellation.

accountId: str[source]
contractId: int | None = None[source]
nonce: str[source]
class hibachi_xyz.types.OrdersStatusParams(accountId: int)[source][source]

Bases: object

Parameters for querying all orders status.

accountId: int[source]
class hibachi_xyz.types.OrdersStatusResponse(id: int, result: List[Order], status: int | None)[source][source]

Bases: object

Response containing multiple order statuses.

id: int[source]
result: List[Order][source]
status: int | None[source]
class hibachi_xyz.types.PendingOrdersResponse(orders: List[Order])[source][source]

Bases: object

Response containing pending orders.

orders: List[Order][source]
class hibachi_xyz.types.Position(direction: str, entryNotional: str, markPrice: str, notionalValue: str, openPrice: str, quantity: str, symbol: str, unrealizedFundingPnl: str, unrealizedTradingPnl: str)[source][source]

Bases: object

Position information.

direction: str[source]
entryNotional: str[source]
markPrice: str[source]
notionalValue: str[source]
openPrice: str[source]
quantity: str[source]
symbol: str[source]
unrealizedFundingPnl: str[source]
unrealizedTradingPnl: str[source]
class hibachi_xyz.types.PriceResponse(askPrice: str, bidPrice: str, fundingRateEstimation: FundingRateEstimation, markPrice: str, spotPrice: str, symbol: str, tradePrice: str)[source][source]

Bases: object

Price information for a symbol.

askPrice: str[source]
bidPrice: str[source]
fundingRateEstimation: FundingRateEstimation[source]
markPrice: str[source]
spotPrice: str[source]
symbol: str[source]
tradePrice: str[source]
class hibachi_xyz.types.Settlement(direction: str, indexPrice: str, quantity: str, settledAmount: str, symbol: str, timestamp: int)[source][source]

Bases: object

Settlement information.

direction: str[source]
indexPrice: str[source]
quantity: str[source]
settledAmount: str[source]
symbol: str[source]
timestamp: int[source]
class hibachi_xyz.types.SettlementsResponse(settlements: List[Settlement])[source][source]

Bases: object

Response containing settlements.

settlements: List[Settlement][source]
class hibachi_xyz.types.Side(*values)[source][source]

Bases: Enum

Order side (buy/sell).

ASK = 'ASK'[source]
BID = 'BID'[source]
BUY = 'BUY'[source]
SELL = 'SELL'[source]
class hibachi_xyz.types.StatsResponse(high24h: str, low24h: str, symbol: str, volume24h: str)[source][source]

Bases: object

24-hour statistics for a symbol.

high24h: str[source]
low24h: str[source]
symbol: str[source]
volume24h: str[source]
class hibachi_xyz.types.TPSLConfig[source][source]

Bases: object

Configuration for Take-Profit/Stop-Loss orders.

class Leg(order_type: Type, price: Decimal, quantity: Decimal | None)[source][source]

Bases: object

Individual TP/SL leg configuration.

order_type: Type[source]
price: Decimal[source]
quantity: Decimal | None[source]
class Type(*values)[source][source]

Bases: Enum

TP/SL order type.

SL = 'SL'[source]
TP = 'TP'[source]
add_stop_loss(price: Decimal | str | float | int, quantity: Decimal | str | float | int | None = None) Self[source][source]

Add a stop-loss leg to the configuration.

add_take_profit(price: Decimal | str | float | int, quantity: Decimal | str | float | int | None = None) Self[source][source]

Add a take-profit leg to the configuration.

class hibachi_xyz.types.TWAPConfig(duration_minutes: int, quantity_mode: TWAPQuantityMode)[source][source]

Bases: object

Configuration for TWAP (Time-Weighted Average Price) orders.

duration_minutes: int[source]
quantity_mode: TWAPQuantityMode[source]
to_dict() Dict[str, Any][source][source]

Convert TWAP configuration to dictionary representation.

Returns:

Dictionary with ‘twapDurationMinutes’ and ‘twapQuantityMode’ keys.

class hibachi_xyz.types.TWAPQuantityMode(*values)[source][source]

Bases: Enum

TWAP quantity distribution mode.

FIXED = 'FIXED'[source]
RANDOM = 'RANDOM'[source]
class hibachi_xyz.types.TakerSide(*values)[source][source]

Bases: Enum

Taker side in a trade.

Buy = 'Buy'[source]
Sell = 'Sell'[source]
class hibachi_xyz.types.Trade(price: str, quantity: str, takerSide: str | TakerSide, timestamp: int)[source][source]

Bases: object

Individual trade information.

price: str[source]
quantity: str[source]
takerSide: TakerSide[source]
timestamp: int[source]
class hibachi_xyz.types.TradesResponse(trades: List[Trade])[source][source]

Bases: object

Response containing recent trades.

trades: List[Trade][source]
class hibachi_xyz.types.TradingTier(level: int, lowerThreshold: str, title: str, upperThreshold: str)[source][source]

Bases: object

Trading tier information.

level: int[source]
lowerThreshold: str[source]
title: str[source]
upperThreshold: str[source]
class hibachi_xyz.types.Transaction(id: int, assetId: int, quantity: str, status: str, timestampSec: int, transactionType: str, transactionHash: str | None = None, token: str | None = None, etaTsSec: int | None = None, blockNumber: int | None = None, chain: str | None = None, instantWithdrawalChain: str | None = None, instantWithdrawalToken: str | None = None, isInstantWithdrawal: bool | None = None, withdrawalAddress: str | None = None, receivingAddress: str | None = None, receivingAccountId: int | None = None, srcAccountId: int | None = None, srcAddress: str | None = None)[source][source]

Bases: object

Transaction record.

assetId: int[source]
blockNumber: int | None[source]
chain: str | None[source]
etaTsSec: int | None[source]
id: int[source]
instantWithdrawalChain: str | None[source]
instantWithdrawalToken: str | None[source]
isInstantWithdrawal: bool | None[source]
quantity: str[source]
receivingAccountId: int | None[source]
receivingAddress: str | None[source]
srcAccountId: int | None[source]
srcAddress: str | None[source]
status: str[source]
timestampSec: int[source]
token: str | None[source]
transactionHash: str | None[source]
transactionType: str[source]
withdrawalAddress: str | None[source]
class hibachi_xyz.types.TransferRequest(accountId: int, coin: str, fees: Decimal | str | float | int, nonce: int, quantity: Decimal | str | float | int, dstPublicKey: str, signature: str)[source][source]

Bases: object

Transfer request.

accountId: int[source]
coin: str[source]
dstPublicKey: str[source]
fees: Decimal[source]
nonce: int[source]
quantity: Decimal[source]
signature: str[source]
class hibachi_xyz.types.TransferResponse(status: str)[source][source]

Bases: object

Transfer response.

status: str[source]
class hibachi_xyz.types.TriggerDirection(*values)[source][source]

Bases: Enum

Trigger direction for conditional orders.

HIGH = 'HIGH'[source]
LOW = 'LOW'[source]
class hibachi_xyz.types.UpdateOrder(order_id: int, symbol: str, side: Side, quantity: Decimal | str | float | int, max_fees_percent: Decimal | str | float | int, price: Decimal | str | float | int | None = None, trigger_price: Decimal | str | float | int | None = None, creation_deadline: Decimal | str | float | int | None = None, parent_order: OrderIdVariant | None = None, order_flags: OrderFlags | None = None)[source][source]

Bases: object

Request to update an existing order.

action: str = 'modify'[source]
creation_deadline: Decimal | None[source]
max_fees_percent: Decimal[source]
order_flags: OrderFlags | None[source]
order_id: int[source]
parent_order: OrderIdVariant | None[source]
price: Decimal | None[source]
quantity: Decimal[source]
side: Side[source]
symbol: str[source]
trigger_price: Decimal | None[source]
class hibachi_xyz.types.UpdateOrderBatchResponse(orderId: str)[source][source]

Bases: object

Success response to an update order request.

orderId: str[source]
class hibachi_xyz.types.WebSocketBatchOrder(action: str, nonce: int, symbol: str, orderType: str, side: str, quantity: str, price: str, maxFeesPercent: str, signature: str, orderId: str | None = None, updatedQuantity: str | None = None, updatedPrice: str | None = None)[source][source]

Bases: object

WebSocket batch order operation.

action: str[source]
maxFeesPercent: str[source]
nonce: int[source]
orderId: str | None = None[source]
orderType: str[source]
price: str[source]
quantity: str[source]
side: str[source]
signature: str[source]
symbol: str[source]
updatedPrice: str | None = None[source]
updatedQuantity: str | None = None[source]
class hibachi_xyz.types.WebSocketEvent(account: str, event: str, data: Dict[str, Any])[source][source]

Bases: object

WebSocket event notification.

account: str[source]
data: Dict[str, Any][source]
event: str[source]
class hibachi_xyz.types.WebSocketMarketSubscriptionListResponse(subscriptions: List[WebSocketSubscription])[source][source]

Bases: object

List of WebSocket subscriptions.

subscriptions: List[WebSocketSubscription][source]
class hibachi_xyz.types.WebSocketOrderCancelParams(orderId: str, accountId: str, nonce: int)[source][source]

Bases: object

Parameters for WebSocket order cancellation.

accountId: str[source]
nonce: int[source]
orderId: str[source]
class hibachi_xyz.types.WebSocketOrderModifyParams(orderId: str, accountId: str, symbol: str, quantity: str, price: str, maxFeesPercent: str)[source][source]

Bases: object

Parameters for WebSocket order modification.

accountId: str[source]
maxFeesPercent: str[source]
orderId: str[source]
price: str[source]
quantity: str[source]
symbol: str[source]
class hibachi_xyz.types.WebSocketOrderStatusParams(orderId: str, accountId: str)[source][source]

Bases: object

Parameters for WebSocket order status query.

accountId: str[source]
orderId: str[source]
class hibachi_xyz.types.WebSocketOrdersBatchParams(accountId: str, orders: List[WebSocketBatchOrder])[source][source]

Bases: object

Parameters for WebSocket batch order operations.

accountId: str[source]
orders: List[WebSocketBatchOrder][source]
class hibachi_xyz.types.WebSocketOrdersCancelParams(accountId: str, nonce: str, contractId: int | None = None)[source][source]

Bases: object

Parameters for WebSocket bulk order cancellation.

accountId: str[source]
contractId: int | None = None[source]
nonce: str[source]
class hibachi_xyz.types.WebSocketOrdersStatusParams(accountId: str)[source][source]

Bases: object

Parameters for WebSocket orders status query.

accountId: str[source]
class hibachi_xyz.types.WebSocketResponse(id: int | None, result: Dict[str, Any] | None, status: int | None, subscriptions: List[WebSocketSubscription] | None)[source][source]

Bases: object

Generic WebSocket response.

id: int | None[source]
result: Dict[str, Any] | None[source]
status: int | None[source]
subscriptions: List[WebSocketSubscription] | None[source]
class hibachi_xyz.types.WebSocketStreamPingParams(accountId: str, listenKey: str, timestamp: int)[source][source]

Bases: object

Parameters for WebSocket stream ping.

accountId: str[source]
listenKey: str[source]
timestamp: int[source]
class hibachi_xyz.types.WebSocketStreamStartParams(accountId: str)[source][source]

Bases: object

Parameters to start WebSocket stream.

accountId: str[source]
class hibachi_xyz.types.WebSocketStreamStopParams(accountId: str, listenKey: str, timestamp: int)[source][source]

Bases: object

Parameters to stop WebSocket stream.

accountId: str[source]
listenKey: str[source]
timestamp: int[source]
class hibachi_xyz.types.WebSocketSubscription(symbol: str, topic: WebSocketSubscriptionTopic)[source][source]

Bases: object

WebSocket subscription configuration.

symbol: str[source]
topic: WebSocketSubscriptionTopic[source]
class hibachi_xyz.types.WebSocketSubscriptionTopic(*values)[source][source]

Bases: Enum

WebSocket subscription topics.

ASK_BID_PRICE = 'ask_bid_price'[source]
FUNDING_RATE_ESTIMATION = 'funding_rate_estimation'[source]
KLINES = 'klines'[source]
MARK_PRICE = 'mark_price'[source]
ORDERBOOK = 'orderbook'[source]
SPOT_PRICE = 'spot_price'[source]
TRADES = 'trades'[source]
class hibachi_xyz.types.WithdrawRequest(accountId: int, coin: str, withdrawAddress: str, network: str, quantity: Decimal | str | float | int, maxFees: Decimal | str | float | int, signature: str)[source][source]

Bases: object

Withdrawal request.

accountId: int[source]
coin: str[source]
maxFees: Decimal[source]
network: str[source]
quantity: Decimal[source]
signature: str[source]
withdrawAddress: str[source]
class hibachi_xyz.types.WithdrawResponse(orderId: str)[source][source]

Bases: object

Withdrawal response.

orderId: str[source]
class hibachi_xyz.types.WithdrawalLimit(lowerLimit: str, upperLimit: str)[source][source]

Bases: object

Withdrawal limits.

lowerLimit: str[source]
upperLimit: str[source]
hibachi_xyz.types.deserialize_batch_response_order(data: dict[str, None | bool | int | float | str | dict[str, JsonValue] | list[JsonValue]]) CreateOrderBatchResponse | UpdateOrderBatchResponse | CancelOrderBatchResponse | ErrorBatchResponse[source][source]

Deserialize a batch response order based on which fields are present.

Logic:
  • If ‘errorCode’ is present -> ErrorBatchResponse

  • If both ‘nonce’ and ‘orderId’ are present -> CreateOrderBatchResponse

  • If only ‘orderId’ is present -> UpdateOrderBatchResponse

  • If only ‘nonce’ is present -> CancelOrderBatchResponse

Parameters:

data – JSON object containing the batch response order data.

Returns:

Appropriate batch response type based on the fields present in data.

Raises:

DeserializationError – If the data cannot be deserialized into any known type.

hibachi_xyz.types.full_precision_string(n: Decimal | str | float | int) str[source][source]

Convert a numeric input to a full precision string representation.

hibachi_xyz.types.numeric_to_decimal(n: Decimal | str | float | int) Decimal[source][source]
hibachi_xyz.types.numeric_to_decimal(n: None) None

Convert various numeric input types to Decimal, or None if input is None.

Module contents

Hibachi Python SDK.

This module provides a Python SDK for interacting with the Hibachi XYZ cryptocurrency exchange API, including HTTP and WebSocket clients for trading, market data, and account management.

class hibachi_xyz.AccountInfo(assets: List[Asset], balance: str, maximalWithdraw: str, numFreeTransfersRemaining: int, positions: List[Position], totalOrderNotional: str, totalPositionNotional: str, totalUnrealizedFundingPnl: str, totalUnrealizedPnl: str, totalUnrealizedTradingPnl: str, tradeMakerFeeRate: str, tradeTakerFeeRate: str)[source][source]

Bases: object

Complete account information.

assets: List[Asset][source]
balance: str[source]
maximalWithdraw: str[source]
numFreeTransfersRemaining: int[source]
positions: List[Position][source]
totalOrderNotional: str[source]
totalPositionNotional: str[source]
totalUnrealizedFundingPnl: str[source]
totalUnrealizedPnl: str[source]
totalUnrealizedTradingPnl: str[source]
tradeMakerFeeRate: str[source]
tradeTakerFeeRate: str[source]
class hibachi_xyz.AccountSnapshot(account_id: int, balance: str, positions: List[Position])[source][source]

Bases: object

Snapshot of account state.

account_id: int[source]
balance: str[source]
positions: List[Position][source]
class hibachi_xyz.AccountStreamStartResult(accountSnapshot: AccountSnapshot, listenKey: str)[source][source]

Bases: object

Result from starting account stream.

accountSnapshot: AccountSnapshot[source]
listenKey: str[source]
class hibachi_xyz.AccountTrade(askAccountId: int, askOrderId: int, bidAccountId: int, bidOrderId: int, fee: str, id: int, orderType: str, price: str, quantity: str, realizedPnl: str, side: str, symbol: str, timestamp: int)[source][source]

Bases: object

Individual account trade record.

askAccountId: int[source]
askOrderId: int[source]
bidAccountId: int[source]
bidOrderId: int[source]
fee: str[source]
id: int[source]
orderType: str[source]
price: str[source]
quantity: str[source]
realizedPnl: str[source]
side: str[source]
symbol: str[source]
timestamp: int[source]
class hibachi_xyz.AccountTradesResponse(trades: List[AccountTrade])[source][source]

Bases: object

Response containing account trades.

trades: List[AccountTrade][source]
class hibachi_xyz.Asset(quantity: str, symbol: str)[source][source]

Bases: object

Asset balance information.

quantity: str[source]
symbol: str[source]
exception hibachi_xyz.BaseError[source][source]

Bases: Exception

Base exception for all Hibachi SDK errors.

All exceptions raised by this library inherit from this class, allowing users to catch all SDK-related errors with a single except clause.

This exception should not be raised directly. Use one of the specific subclasses instead (ExchangeError, TransportError, ValidationError).

class hibachi_xyz.BatchOrder(action: str, nonce: int, symbol: str | None = None, orderType: OrderType | None = None, side: Side | None = None, quantity: str | None = None, price: str | None = None, maxFeesPercent: str | None = None, orderId: str | None = None, updatedQuantity: str | None = None, updatedPrice: str | None = None, signature: str | None = None)[source][source]

Bases: object

Batch order operation.

action: str[source]
maxFeesPercent: str | None = None[source]
nonce: int[source]
orderId: str | None = None[source]
orderType: OrderType | None = None[source]
price: str | None = None[source]
quantity: str | None = None[source]
side: Side | None = None[source]
signature: str | None = None[source]
symbol: str | None = None[source]
updatedPrice: str | None = None[source]
updatedQuantity: str | None = None[source]
class hibachi_xyz.BatchResponse(orders: list[CreateOrderBatchResponse | UpdateOrderBatchResponse | CancelOrderBatchResponse | ErrorBatchResponse])[source][source]

Bases: object

Response containing multiple order operations.

orders: list[CreateOrderBatchResponse | UpdateOrderBatchResponse | CancelOrderBatchResponse | ErrorBatchResponse][source]
class hibachi_xyz.CancelOrder(order_id: int | None = None, nonce: int | None = None)[source][source]

Bases: object

Request to cancel an order.

action: str = 'cancel'[source]
nonce: int | None[source]
order_id: int | None[source]
class hibachi_xyz.CapitalBalance(balance: str)[source][source]

Bases: object

Account capital balance.

balance: str[source]
class hibachi_xyz.CapitalHistory(transactions: List[Transaction])[source][source]

Bases: object

Transaction history.

transactions: List[Transaction][source]
class hibachi_xyz.CreateOrder(symbol: str, side: Side, quantity: Decimal | str | float | int, max_fees_percent: Decimal | str | float | int, price: Decimal | str | float | int | None = None, trigger_price: Decimal | str | float | int | None = None, twap_config: TWAPConfig | None = None, creation_deadline: Decimal | str | float | int | None = None, parent_order: OrderIdVariant | None = None, order_flags: OrderFlags | None = None, trigger_direction: TriggerDirection | None = None)[source][source]

Bases: object

Request to create a new order.

action: str = 'place'[source]
creation_deadline: Decimal | None[source]
max_fees_percent: Decimal[source]
order_flags: OrderFlags | None[source]
parent_order: OrderIdVariant | None[source]
price: Decimal | None[source]
quantity: Decimal[source]
side: Side[source]
symbol: str[source]
trigger_direction: TriggerDirection | None[source]
trigger_price: Decimal | None[source]
twap_config: TWAPConfig | None[source]
class hibachi_xyz.CrossChainAsset(chain: str, exchangeRateFromUSDT: str, exchangeRateToUSDT: str, instantWithdrawalLowerLimitInUSDT: str, instantWithdrawalUpperLimitInUSDT: str, token: str)[source][source]

Bases: object

Cross-chain asset information.

chain: str[source]
exchangeRateFromUSDT: str[source]
exchangeRateToUSDT: str[source]
instantWithdrawalLowerLimitInUSDT: str[source]
instantWithdrawalUpperLimitInUSDT: str[source]
token: str[source]
class hibachi_xyz.DepositInfo(depositAddressEvm: str)[source][source]

Bases: object

Deposit information.

depositAddressEvm: str[source]
exception hibachi_xyz.DeserializationError(message: str)[source][source]

Bases: TransportError

Raised when response data cannot be deserialized/decoded.

class hibachi_xyz.EnableCancelOnDisconnectParams(nonce: int)[source][source]

Bases: object

Parameters to enable cancel-on-disconnect.

nonce: int[source]
exception hibachi_xyz.ExchangeError[source][source]

Bases: BaseError

Exception raised when the API server returns an error response.

This exception is raised when a request successfully reaches the API server and the server returns a valid response, but that response indicates an error condition (e.g., invalid request, rate limit exceeded, authorization failure).

ExchangeError indicates that:
  • The network connection succeeded

  • The request was properly formatted and transmitted

  • A server processed the request and returned an error response

class hibachi_xyz.ExchangeInfo(feeConfig: FeeConfig, futureContracts: List[FutureContract], instantWithdrawalLimit: WithdrawalLimit, maintenanceWindow: List[MaintenanceWindow], status: str)[source][source]

Bases: object

Exchange configuration and status information.

feeConfig: FeeConfig[source]
futureContracts: List[FutureContract][source]
instantWithdrawalLimit: WithdrawalLimit[source]
maintenanceWindow: List[MaintenanceWindow][source]
status: str[source]
class hibachi_xyz.FeeConfig(depositFees: str, instantWithdrawDstPublicKey: str, instantWithdrawalFees: List[List[int | float]], tradeMakerFeeRate: str, tradeTakerFeeRate: str, transferFeeRate: str, withdrawalFees: str)[source][source]

Bases: object

Fee configuration for the exchange.

depositFees: str[source]
instantWithdrawDstPublicKey: str[source]
instantWithdrawalFees: List[List[int | float]][source]
tradeMakerFeeRate: str[source]
tradeTakerFeeRate: str[source]
transferFeeRate: str[source]
withdrawalFees: str[source]
class hibachi_xyz.FundingRateEstimation(estimatedFundingRate: str, nextFundingTimestamp: int)[source][source]

Bases: object

Estimated funding rate information.

estimatedFundingRate: str[source]
nextFundingTimestamp: int[source]
class hibachi_xyz.FutureContract(displayName: str, id: int, minNotional: str, minOrderSize: str, orderbookGranularities: List[str], initialMarginRate: str, maintenanceMarginRate: str, settlementDecimals: int, settlementSymbol: str, status: str, stepSize: str, symbol: str, tickSize: str, underlyingDecimals: int, underlyingSymbol: str, marketCloseTimestamp: str | None = None, marketOpenTimestamp: str | None = None, marketCreationTimestamp: str | None = None)[source][source]

Bases: object

Future contract specification.

displayName: str[source]
id: int[source]
initialMarginRate: str[source]
maintenanceMarginRate: str[source]
marketCloseTimestamp: str | None = None[source]
marketCreationTimestamp: str | None = None[source]
marketOpenTimestamp: str | None = None[source]
minNotional: str[source]
minOrderSize: str[source]
orderbookGranularities: List[str][source]
settlementDecimals: int[source]
settlementSymbol: str[source]
status: str[source]
stepSize: str[source]
symbol: str[source]
tickSize: str[source]
underlyingDecimals: int[source]
underlyingSymbol: str[source]
class hibachi_xyz.HibachiApiClient(api_url: str = 'https://api.hibachi.xyz', data_api_url: str = 'https://data-api.hibachi.xyz', account_id: int | None = None, api_key: str | None = None, private_key: str | None = None, executor: HttpExecutor | None = None)[source][source]

Bases: object

Hibachi API client for trading operations.

Examples

from hibachi_xyz import HibachiApiClient
from dotenv import load_dotenv
import os

load_dotenv()

hibachi = HibachiApiClient(
    api_key=os.environ.get('HIBACHI_API_KEY', "your-api-key"),
    account_id=os.environ.get('HIBACHI_ACCOUNT_ID', "your-account-id"),
    private_key=os.environ.get('HIBACHI_PRIVATE_KEY', "your-private"),
)

account_info = hibachi.get_account_info()
print(f"Account Balance: {account_info.balance}")
print(f"Total Position Notional: {account_info.totalPositionNotional}")

exchange_info = hibachi.get_exchange_info()
print(exchange_info)
property account_id: int[source]

Get the current account ID.

Returns:

The account ID

Return type:

int

Raises:

ValidationError – If account_id has not been set

property api_key: str[source]

Get the current API key.

Returns:

The API key

Return type:

str

Raises:

ValidationError – If api_key has not been set

batch_orders(orders: list[CreateOrder | UpdateOrder | CancelOrder]) BatchResponse[source][source]

Submit multiple order operations in a single batch request.

Creates, updates, and cancels orders atomically in a single API call. All order details must be provided explicitly (no shortcuts for updates).

Parameters:

orders – List of order operations (CreateOrder, UpdateOrder, or CancelOrder)

Returns:

Response containing results for each order operation

Return type:

BatchResponse

Raises:

Example:

response = client.batch_orders([
    # Simple market order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent),
    # Simple limit order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent, price=90_000),
    # Trigger market order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent, trigger_price=85_000),
    # Trigger limit order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent, price=84_750, trigger_price=85_000),
    # TWAP order
    CreateOrder("BTC/USDT-P", Side.SELL, 0.001, max_fees_percent, twap_config=TWAPConfig(5, TWAPQuantityMode.FIXED)),
    # Update limit order (need all relevant optional parameters)
    UpdateOrder(limit_order_id, "BTC/USDT-P", Side.BUY, 0.001, max_fees_percent, price=60_000),
    # Cancel order
    CancelOrder(order_id=limit_order_id),
])
Endpoint:

POST /trade/orders

cancel_all_orders(contractId: int | None = None) dict[str, JsonValue][source][source]

Cancel all pending orders.

Cancels all currently pending orders for the account. Currently uses a workaround that individually cancels each order.

Parameters:

contractId – Contract ID to filter orders (optional, currently unused)

Returns:

The API response (empty dict when using workaround)

Return type:

Json

Example

client.cancel_all_orders()
Endpoint:

DELETE /trade/orders

cancel_order(order_id: int | None = None, nonce: int | None = None) dict[str, JsonValue][source][source]

Cancel an existing order.

Cancels an order using either the order ID or the nonce used when creating the order. At least one identifier must be provided.

Parameters:
  • order_id – The order ID to cancel (optional)

  • nonce – The nonce used when creating the order (optional)

Returns:

The API response

Return type:

Json

Raises:

ValidationError – If neither order_id nor nonce is provided

Example

client.cancel_order(order_id=123)
client.cancel_order(nonce=1234567)
Endpoint:

DELETE /trade/order

property future_contracts: dict[str, FutureContract][source]

Get the cached future contracts metadata.

Returns:

Dictionary mapping contract symbols to their metadata

Return type:

dict[str, FutureContract]

Raises:

ValidationError – If contracts have not been loaded yet (call get_exchange_info() first)

get_account_info() AccountInfo[source][source]

Get detailed account information.

Retrieves comprehensive account information including balance, positions, assets, fee rates, and withdrawal limits.

Returns:

Account details including balance, positions, assets,

order notional, unrealized PnL, and fee rates

Return type:

AccountInfo

Raises:

DeserializationError – If the API response cannot be parsed

Example

account_info = client.get_account_info()
print(account_info.balance)
Endpoint:

GET /trade/account/info

get_account_trades() AccountTradesResponse[source][source]

Get account trade history.

Retrieves the most recent trade history for your account, up to 100 records.

Returns:

List of recent trades with details including price,

quantity, side, fees, realized PnL, and timestamps

Return type:

AccountTradesResponse

Raises:

DeserializationError – If the API response cannot be parsed

Example

account_trades = client.get_account_trades()
Endpoint:

GET /trade/account/trades

get_capital_balance() CapitalBalance[source][source]

Get account balance including unrealized PnL.

Retrieves the net equity balance for your account, which includes unrealized profit and loss from open positions.

Returns:

Account balance as a string

Return type:

CapitalBalance

Raises:

DeserializationError – If the API response cannot be parsed

Example

capital_balance = client.get_capital_balance()
print(capital_balance.balance)
Endpoint:

GET /capital/balance

get_capital_history() CapitalHistory[source][source]

Get deposit and withdrawal history for your account.

Retrieves the most recent deposit and withdrawal transactions, up to 100 of each transaction type.

Returns:

List of transactions including deposits and withdrawals

Return type:

CapitalHistory

Raises:

DeserializationError – If the API response cannot be parsed

Example

capital_history = client.get_capital_history()
Endpoint:

GET /capital/history

get_deposit_info(public_key: str) DepositInfo[source][source]

Get deposit address information for a public key.

Retrieves the EVM deposit address associated with the specified public key.

Parameters:

public_key – The public key to get deposit info for

Returns:

Deposit address information containing the EVM deposit address

Return type:

DepositInfo

Raises:

DeserializationError – If the API response cannot be parsed

Endpoint:

GET /capital/deposit-info

get_exchange_info() ExchangeInfo[source][source]

Get exchange metadata and maintenance information.

Retrieves all available future contracts, fee configuration, withdrawal limits, and maintenance windows. The maintenance status can be “NORMAL”, “UNSCHEDULED_MAINTENANCE”, or “SCHEDULED_MAINTENANCE”.

Returns:

Exchange metadata including fee config, future contracts,

withdrawal limits, maintenance windows, and current status

Return type:

ExchangeInfo

Raises:

DeserializationError – If the API response cannot be parsed

Example

exchange_info = client.get_exchange_info()
print(exchange_info)
Endpoint:

GET /market/exchange-info

get_inventory() InventoryResponse[source][source]

Get market inventory with contract metadata and latest price information.

Similar to get_exchange_info, but includes current price data for all contracts, cross-chain assets, fee configuration, and trading tiers.

Returns:

Market inventory including cross-chain assets, fee config,

markets with contract and price info, and trading tiers

Return type:

InventoryResponse

Raises:

DeserializationError – If the API response cannot be parsed

Endpoint:

GET /market/inventory

get_klines(symbol: str, interval: Interval) KlinesResponse[source][source]

Get candlestick (K-line) data for a trading symbol.

Retrieves historical candlestick data at the specified time interval.

Parameters:
  • symbol – The trading symbol (e.g., “BTC/USDT-P”)

  • interval – The time interval for candlesticks (e.g., Interval.ONE_MINUTE)

Returns:

List of candlestick data with OHLCV information

Return type:

KlinesResponse

Raises:
Endpoint:

GET /market/data/klines

get_open_interest(symbol: str) OpenInterestResponse[source][source]

Get open interest for a trading symbol.

Retrieves the current open interest (total outstanding contracts) for the specified symbol.

Parameters:

symbol – The trading symbol (e.g., “BTC/USDT-P”)

Returns:

The open interest data

Return type:

OpenInterestResponse

Raises:
Endpoint:

GET /market/data/open-interest

get_order_details(order_id: int | None = None, nonce: int | None = None) Order[source][source]

Get detailed information for a specific order.

Retrieves order details using either the order ID or the nonce used when creating the order. At least one identifier must be provided.

Parameters:
  • order_id – The order ID to query (optional)

  • nonce – The nonce used when creating the order (optional)

Returns:

Order details including ID, type, side, price, quantity, status,

and timestamps

Return type:

Order

Raises:

Example

order_details = client.get_order_details(order_id=123)
# or
order_details = client.get_order_details(nonce=1234567)
Endpoint:

GET /trade/order

get_orderbook(symbol: str, depth: int, granularity: float) OrderBook[source][source]

Get orderbook price levels for a trading symbol.

Retrieves aggregated bid and ask price levels from the orderbook. Price levels are aggregated based on the specified granularity.

Parameters:
  • symbol – The trading symbol (e.g., “BTC/USDT-P”)

  • depth – Number of price levels to return on each side (1-100)

  • granularity – Price level granularity for aggregation (e.g., 0.01)

Returns:

Orderbook with bid and ask price levels containing price and quantity

Return type:

OrderBook

Raises:
Endpoint:

GET /market/data/orderbook

get_pending_orders() PendingOrdersResponse[source][source]

Get all pending orders for your account.

Retrieves all currently active orders including open, partially filled, and triggered orders.

Returns:

List of pending orders with details including order ID,

type, side, price, quantity, status, and timestamps

Return type:

PendingOrdersResponse

Raises:

DeserializationError – If the API response cannot be parsed

Example

pending_orders = client.get_pending_orders()
Endpoint:

GET /trade/orders

get_prices(symbol: str) PriceResponse[source][source]

Get current price information for a trading symbol.

Retrieves mark price, index price, and funding rate estimation for the specified symbol.

Parameters:

symbol – The trading symbol (e.g., “BTC/USDT-P”)

Returns:

Price information including mark price, index price, and funding rates

Return type:

PriceResponse

Raises:
Endpoint:

GET /market/data/prices

get_settlements_history() SettlementsResponse[source][source]

Get settlement history for your account.

Retrieves the history of settled trades, including position settlements and funding rate settlements.

Returns:

List of settlements with direction, price, quantity,

settled amount, symbol, and timestamp

Return type:

SettlementsResponse

Raises:

DeserializationError – If the API response cannot be parsed

Example

settlements = client.get_settlements_history()
Endpoint:

GET /trade/account/settlements_history

get_stats(symbol: str) StatsResponse[source][source]

Get 24-hour statistics for a trading symbol.

Retrieves 24-hour trading statistics including volume, high/low prices, and price changes.

Parameters:

symbol – The trading symbol (e.g., “BTC/USDT-P”)

Returns:

24-hour trading statistics

Return type:

StatsResponse

Raises:
Endpoint:

GET /market/data/stats

get_trades(symbol: str) TradesResponse[source][source]

Get recent trades for a trading symbol.

Retrieves the most recent executed trades for the specified symbol.

Parameters:

symbol – The trading symbol (e.g., “BTC/USDT-P”)

Returns:

List of recent trades with price, quantity, taker side, and timestamp

Return type:

TradesResponse

Raises:
Endpoint:

GET /market/data/trades

place_limit_order(symbol: str, quantity: Decimal | str | float | int, price: Decimal | str | float | int, side: Side, max_fees_percent: Decimal | str | float | int, trigger_price: Decimal | str | float | int | None = None, creation_deadline: Decimal | str | float | int | None = None, order_flags: OrderFlags | None = None, tpsl: TPSLConfig | None = None) tuple[int, int][source][source]

Place a limit order.

Submits a limit order that executes only at the specified price or better. Supports trigger prices and take-profit/stop-loss configurations.

Parameters:
  • symbol – The trading symbol (e.g., “BTC/USDT-P”)

  • quantity – The order quantity

  • price – The limit price

  • side – Order side (BUY, SELL, BID, or ASK)

  • max_fees_percent – Maximum fees as a percentage

  • trigger_price – Price to trigger order execution (optional)

  • creation_deadline – Deadline in seconds for order creation (optional)

  • order_flags – Additional order flags (optional)

  • tpsl – Take-profit/stop-loss configuration (optional)

Returns:

Tuple containing the nonce (defaults to current epoch timestamp in μs) and order ID

Return type:

tuple[Nonce, OrderId]

Raises:

DeserializationError – If the API response cannot be parsed

Example

(nonce, order_id) = client.place_limit_order("BTC/USDT-P", 0.0001, 80_000, Side.BUY, max_fees_percent)
(nonce, order_id) = client.place_limit_order("BTC/USDT-P", 0.0001, 80_000, Side.SELL, max_fees_percent)
(nonce, order_id) = client.place_limit_order("BTC/USDT-P", 0.0001, 80_000, Side.BID, max_fees_percent, creation_deadline=2)
(nonce, order_id) = client.place_limit_order("BTC/USDT-P", 0.0001, 1_001_000, Side.ASK, max_fees_percent, trigger_price=1_000_000)
(nonce, limit_order_id) = client.place_limit_order("BTC/USDT-P", 0.001, 6_000, Side.BID, max_fees_percent)
Endpoint:

POST /trade/order

place_market_order(symbol: str, quantity: Decimal | str | float | int, side: Side, max_fees_percent: Decimal | str | float | int, trigger_price: Decimal | str | float | int | None = None, twap_config: TWAPConfig | None = None, creation_deadline: Decimal | str | float | int | None = None, order_flags: OrderFlags | None = None, tpsl: TPSLConfig | None = None) tuple[int, int][source][source]

Place a market order.

Submits a market order that executes immediately at the current market price. Supports trigger prices, TWAP execution, and take-profit/stop-loss configurations.

Parameters:
  • symbol – The trading symbol (e.g., “BTC/USDT-P”)

  • quantity – The order quantity

  • side – Order side (BUY, SELL, BID, or ASK)

  • max_fees_percent – Maximum fees as a percentage

  • trigger_price – Price to trigger order execution (optional)

  • twap_config – Time-weighted average price configuration (optional)

  • creation_deadline – Deadline in seconds for order creation (optional)

  • order_flags – Additional order flags (optional)

  • tpsl – Take-profit/stop-loss configuration (optional)

Returns:

Tuple containing the nonce (defaults to current epoch timestamp in μs) and order ID

Return type:

tuple[Nonce, OrderId]

Raises:
  • ValueError – If both twap_config and trigger_price are set, or if twap_config and tpsl are set

  • DeserializationError – If the API response cannot be parsed

Example

(nonce, order_id) = client.place_market_order("BTC/USDT-P", 0.0001, Side.BUY, max_fees_percent)
(nonce, order_id) = client.place_market_order("BTC/USDT-P", 0.0001, Side.SELL, max_fees_percent)
(nonce, order_id) = client.place_market_order("BTC/USDT-P", 0.0001, Side.BID, max_fees_percent, creation_deadline=2)
(nonce, order_id) = client.place_market_order("BTC/USDT-P", 0.0001, Side.ASK, max_fees_percent, trigger_price=1_000_000)
(nonce, order_id) = client.place_market_order("SOL/USDT-P", 1, Side.BID, max_fees_percent, twap_config=twap_config)
Endpoint:

POST /trade/order

set_account_id(account_id: int | None) None[source][source]

Set the account ID for API requests.

Parameters:

account_id – The account ID (int, numeric string, or None)

Raises:

ValidationError – If the account_id is an invalid type or format

set_api_key(api_key: str | None) None[source][source]

Set the API key for authenticated requests.

Parameters:

api_key – The API key string (or None to clear)

Raises:

ValidationError – If the api_key is an invalid type

set_private_key(private_key: str) None[source][source]

Set the private key for signing requests.

Supports two formats:
  • Ethereum private key (hex string with or without 0x prefix) for wallet accounts

  • HMAC key (non-hex string) for web accounts

Parameters:

private_key – The private key as a hex string (with/without 0x) or HMAC key

transfer(coin: str, quantity: Decimal | str | float | int, dstPublicKey: str, max_fees: Decimal | str | float | int) TransferResponse[source][source]

Request fund transfer to another account.

Transfers funds from your account to another account identified by its public key.

Parameters:
  • coin – The coin to transfer (e.g., “USDT”)

  • quantity – The amount to transfer

  • dstPublicKey – Destination account’s public key

  • max_fees – Maximum fees as a percentage

Returns:

Response containing the transfer details

Return type:

TransferResponse

Raises:

DeserializationError – If the API response cannot be parsed

Endpoint:

POST /capital/transfer

update_order(order_id: int, max_fees_percent: Decimal | str | float | int, quantity: Decimal | str | float | int | None = None, price: Decimal | str | float | int | None = None, trigger_price: Decimal | str | float | int | None = None, creation_deadline: Decimal | str | float | int | None = None) dict[str, JsonValue][source][source]

Update an existing order.

Modifies the parameters of an existing order including quantity, price, and trigger price. The order is retrieved first to maintain unmodified fields.

Parameters:
  • order_id – The ID of the order to update

  • max_fees_percent – Maximum fees as a percentage

  • quantity – Updated order quantity (optional)

  • price – Updated limit price (optional)

  • trigger_price – Updated trigger price (optional)

  • creation_deadline – Deadline in seconds for update (optional)

Returns:

The API response

Return type:

Json

Raises:

Example

max_fees_percent = 0.0005
client.update_order(order_id, max_fees_percent, quantity=0.002)
client.update_order(order_id, max_fees_percent, price=1_050_000)
client.update_order(order_id, max_fees_percent, trigger_price=1_100_000)
client.update_order(order_id, max_fees_percent, quantity=0.001, price=1_210_000, trigger_price=1_250_000)
Endpoint:

PUT /trade/order

withdraw(coin: str, withdraw_address: str, quantity: str, max_fees: str, network: str = 'arbitrum') WithdrawResponse[source][source]

Submit a withdrawal request.

Submits a request to withdraw funds to an external address. The quantity must not exceed the maximalWithdraw value returned by get_account_info().

Parameters:
  • coin – The coin to withdraw (e.g., “USDT”)

  • withdraw_address – The destination withdrawal address

  • quantity – Amount to withdraw (must not exceed maximalWithdraw)

  • max_fees – Maximum fees allowed for the withdrawal

  • network – The blockchain network to withdraw on (default: “arbitrum”)

Returns:

Response containing the withdrawal order ID

Return type:

WithdrawResponse

Raises:

DeserializationError – If the API response cannot be parsed

Endpoint:

POST /capital/withdraw

exception hibachi_xyz.HibachiApiError[source][source]

Bases: Exception

Deprecated - use hibachi_xyz.errors.BadHttpStatus and subclasses.

class hibachi_xyz.HibachiWSAccountClient(api_key: str, account_id: str, api_endpoint: str = 'https://api.hibachi.xyz', executor: WsExecutor | None = None)[source][source]

Bases: object

WebSocket client for streaming Hibachi account data.

Provides real-time updates for account balances and positions via WebSocket connection.

async connect() None[source][source]

Establish a WebSocket connection to the account data stream.

Creates an authenticated WebSocket connection with automatic retry logic using the provided API key and account ID.

Raises:

WebSocketConnectionError – If connection fails after retry attempts.

async disconnect() None[source][source]

Close the WebSocket connection and clean up resources.

Closes the WebSocket connection and resets the internal state. After calling this method, the client must call connect() and stream_start() again before listening for messages.

async listen() dict[str, JsonValue] | None[source][source]

Listen for and process a single message from the account stream.

Waits for a message from the WebSocket with a 15-second timeout. If a timeout occurs, automatically sends a ping to keep the stream alive. Dispatches received messages to registered event handlers based on topic.

Returns:

The parsed message as a JSON dictionary, or None if a timeout occurred or the connection was closed.

Raises:
  • ValidationError – If WebSocket connection is not established.

  • WebSocketConnectionError – If the WebSocket connection is closed unexpectedly.

  • Exception – For any other errors during message processing.

on(topic: str, handler: Callable[[dict[str, JsonValue]], Coroutine[None, None, None]]) None[source][source]

Register an event handler for a specific topic.

Registers a callback function that will be invoked when messages with the specified topic are received from the WebSocket.

Parameters:
  • topic – The topic name to listen for (e.g., ‘account_update’, ‘position_change’).

  • handler – An async callback function that accepts a message dictionary.

async ping() None[source][source]

Send a ping message to keep the account stream alive.

Sends a stream.ping request with the current listen key to prevent the server from closing the stream due to inactivity.

Raises:
  • ValueError – If listenKey is not initialized. Must call stream_start() first.

  • ValidationError – If WebSocket connection is not established.

async stream_start() AccountStreamStartResult[source][source]

Start the account data stream and retrieve the initial snapshot.

Sends a stream.start request to the WebSocket server and waits for the response containing the initial account snapshot and listen key. The listen key is stored for subsequent ping operations.

Returns:

AccountStreamStartResult containing the account snapshot (balance and positions) and the listen key for maintaining the stream.

Raises:
  • ValidationError – If WebSocket connection is not established.

  • KeyError – If the response format is unexpected or missing required fields.

property websocket: WsConnection[source]

Get the active WebSocket connection.

Returns:

The active WebSocket connection.

Raises:

ValidationError – If no WebSocket connection exists. Must call connect() first.

class hibachi_xyz.HibachiWSMarketClient(api_endpoint: str = 'https://data-api.hibachi.xyz', executor: WsExecutor | None = None)[source][source]

Bases: object

WebSocket client for streaming Hibachi market data.

Provides real-time market data including mark prices, order books, and trades.

async connect() Self[source][source]

Establish a WebSocket connection to the market data stream.

Creates a WebSocket connection with automatic retry logic and starts the receive loop task to handle incoming messages.

Returns:

This instance for method chaining.

Return type:

Self

Raises:

WebSocketConnectionError – If connection fails after retry attempts.

async disconnect() None[source][source]

Close the WebSocket connection and clean up resources.

Cancels the receive loop task, waits for it to complete, and closes the WebSocket connection. After calling this method, the client must call connect() again before subscribing to topics.

on(topic: str, handler: Callable[[dict[str, JsonValue]], Coroutine[None, None, None]]) None[source][source]

Register a callback for raw topic name (e.g., ‘mark_price’).

async subscribe(subscriptions: list[WebSocketSubscription]) None[source][source]

Subscribe to one or more market data topics.

Sends a subscribe request to the WebSocket server for the specified market data subscriptions (e.g., mark price, order book, trades).

Parameters:

subscriptions – List of WebSocketSubscription objects defining the topics and parameters to subscribe to.

Raises:

ValidationError – If WebSocket connection is not established.

async unsubscribe(subscriptions: list[WebSocketSubscription]) None[source][source]

Unsubscribe from one or more market data topics.

Sends an unsubscribe request to the WebSocket server to stop receiving updates for the specified market data subscriptions.

Parameters:

subscriptions – List of WebSocketSubscription objects defining the topics and parameters to unsubscribe from.

Raises:

ValidationError – If WebSocket connection is not established.

property websocket: WsConnection[source]

Get the active WebSocket connection.

Returns:

The active WebSocket connection.

Raises:

ValidationError – If no WebSocket connection exists. Must call connect() first.

class hibachi_xyz.HibachiWSTradeClient(api_key: str, account_id: int | str, account_public_key: str, api_url: str = 'https://api.hibachi.xyz', data_api_url: str = 'https://data-api.hibachi.xyz', private_key: str | None = None, executor: WsExecutor | None = None)[source][source]

Bases: object

Trade Websocket Client is used to place, modify and cancel orders.

Examples

import asyncio
import os
from hibachi_xyz import HibachiWSTradeClient, print_data
from dotenv import load_dotenv

load_dotenv()

account_id = int(os.environ.get('HIBACHI_ACCOUNT_ID', "your-account-id"))
private_key = os.environ.get('HIBACHI_PRIVATE_KEY', "your-private")
api_key = os.environ.get('HIBACHI_API_KEY', "your-api-key")
public_key = os.environ.get('HIBACHI_PUBLIC_KEY', "your-public")

async def main():
    client = HibachiWSTradeClient(
        api_key=api_key,
        account_id=account_id,
        account_public_key=public_key,
        private_key=private_key
    )

    await client.connect()
    orders = await client.get_orders_status()
    first_order = orders.result[0]

    # single order
    order = await client.get_order_status(first_order.orderId)
    print_data(order)

    modify_result = await client.modify_order(
        order=order.result,
        quantity=float("0.002"),
        price=str(float("93500.0")),
        side=order.result.side,
        maxFeesPercent=float("0.00045"),
    )

    print_data(modify_result)

asyncio.run(main())
async batch_orders(params: OrdersBatchParams) WebSocketResponse[source][source]

Execute multiple order operations in a single request.

async cancel_all_orders() bool[source][source]

Cancel all orders.

async cancel_order(orderId: int | None, nonce: int | None) WebSocketResponse[source][source]

Cancel an existing order.

async connect() Self[source][source]

Establish WebSocket connection with retry logic.

async disconnect() None[source][source]

Close the WebSocket connection.

async enable_cancel_on_disconnect(params: EnableCancelOnDisconnectParams) WebSocketResponse[source][source]

Enable automatic order cancellation on WebSocket disconnect.

async get_order_status(orderId: int) OrderStatusResponse[source][source]

Get status of a specific order.

async get_orders_status() OrdersStatusResponse[source][source]

Get status of all orders.

async modify_order(order: Order, quantity: float, price: str, side: Side, maxFeesPercent: float, nonce: int | None = None) WebSocketResponse[source][source]

Modify an existing order.

async place_order(params: OrderPlaceParams) tuple[int, int][source][source]

Place a new order.

property websocket: WsConnection[source]

Get the WebSocket connection.

Returns:

Active WebSocket connection.

Raises:

ValidationError – If no connection exists. Call connect() first.

exception hibachi_xyz.HttpConnectionError(message: str, url: str | None = None)[source][source]

Bases: TransportError

Raised when a connection cannot be established or is lost.

class hibachi_xyz.Interval(*values)[source][source]

Bases: Enum

Time intervals for klines/candlestick data.

FIFTEEN_MINUTES = '15min'[source]
FIVE_MINUTES = '5min'[source]
FOUR_HOURS = '4h'[source]
ONE_DAY = '1d'[source]
ONE_HOUR = '1h'[source]
ONE_MINUTE = '1min'[source]
ONE_WEEK = '1w'[source]
class hibachi_xyz.InventoryResponse(crossChainAssets: List[CrossChainAsset], feeConfig: FeeConfig, markets: List[Market], tradingTiers: List[TradingTier])[source][source]

Bases: object

Complete inventory information response.

crossChainAssets: List[CrossChainAsset][source]
feeConfig: FeeConfig[source]
markets: List[Market][source]
tradingTiers: List[TradingTier][source]
class hibachi_xyz.Kline(close: str, high: str, low: str, open: str, interval: str, timestamp: int, volumeNotional: str)[source][source]

Bases: object

Candlestick/kline data.

close: str[source]
high: str[source]
interval: str[source]
low: str[source]
open: str[source]
timestamp: int[source]
volumeNotional: str[source]
class hibachi_xyz.KlinesResponse(klines: List[Kline])[source][source]

Bases: object

Response containing kline data.

klines: List[Kline][source]
class hibachi_xyz.MaintenanceWindow(begin: float, end: float, note: str)[source][source]

Bases: object

Scheduled maintenance window.

begin: float[source]
end: float[source]
note: str[source]
class hibachi_xyz.Market(contract: FutureContract, info: MarketInfo)[source][source]

Bases: object

Market combining contract and info.

contract: FutureContract[source]
info: MarketInfo[source]
class hibachi_xyz.MarketInfo(category: str, markPrice: str, price24hAgo: str, priceLatest: str, tags: List[str])[source][source]

Bases: object

Market information for a specific contract.

category: str[source]
markPrice: str[source]
price24hAgo: str[source]
priceLatest: str[source]
tags: List[str][source]
exception hibachi_xyz.MissingCredentialsError(credential_type: str = 'API key')[source][source]

Bases: ValidationError

Raised when required authentication credentials are missing.

hibachi_xyz.Nonce[source]

alias of int

class hibachi_xyz.OpenInterestResponse(totalQuantity: str)[source][source]

Bases: object

Open interest information.

totalQuantity: str[source]
class hibachi_xyz.Order(accountId: int, availableQuantity: str, orderId: str | int, orderType: str, side: str, status: str, symbol: str, numOrdersRemaining: int | None = None, numOrdersTotal: int | None = None, quantityMode: str | None = None, finishTime: int | None = None, price: str | None = None, totalQuantity: str | None = None, creationTime: int | None = None, contractId: int | None = None, orderFlags: str | None = None, triggerPrice: str | None = None)[source][source]

Bases: object

Represents an order in the exchange.

accountId: int[source]
availableQuantity: str[source]
contractId: int | None[source]
creationTime: int | None[source]
finishTime: int | None[source]
numOrdersRemaining: int | None[source]
numOrdersTotal: int | None[source]
orderFlags: OrderFlags | None[source]
orderId: int[source]
orderType: OrderType[source]
price: str | None[source]
quantityMode: str | None[source]
side: Side[source]
status: OrderStatus[source]
symbol: str[source]
totalQuantity: str | None[source]
triggerPrice: str | None[source]
class hibachi_xyz.OrderBook(ask: List[OrderBookLevel], bid: List[OrderBookLevel])[source][source]

Bases: object

Orderbook containing bid and ask levels.

ask: List[OrderBookLevel][source]
bid: List[OrderBookLevel][source]
class hibachi_xyz.OrderBookLevel(price: str, quantity: str)[source][source]

Bases: object

Single orderbook price level.

price: str[source]
quantity: str[source]
class hibachi_xyz.OrderCancelParams(orderId: str, accountId: str, nonce: int)[source][source]

Bases: object

Parameters for canceling an order.

accountId: str[source]
nonce: int[source]
orderId: str[source]
class hibachi_xyz.OrderFlags(*values)[source][source]

Bases: Enum

Order execution flags.

Ioc = 'IOC'[source]
PostOnly = 'POST_ONLY'[source]
ReduceOnly = 'REDUCE_ONLY'[source]
hibachi_xyz.OrderId[source]

alias of int

class hibachi_xyz.OrderIdVariant(nonce: int | None, order_id: int | None)[source][source]

Bases: object

Represents either a nonce or order_id for order identification.

classmethod from_nonce(nonce: int) Self[source][source]

Create an OrderIdVariant from a nonce.

Parameters:

nonce – The nonce value to use for order identification.

Returns:

OrderIdVariant instance with nonce set and order_id as None.

Raises:

ValueError – If nonce is None.

classmethod from_order_id(order_id: int) Self[source][source]

Create an OrderIdVariant from an order_id.

Parameters:

order_id – The order ID value to use for order identification.

Returns:

OrderIdVariant instance with order_id set and nonce as None.

Raises:

ValueError – If order_id is None.

nonce: int | None[source]
order_id: int | None[source]
to_dict() Dict[str, Any][source][source]

Convert OrderIdVariant to dictionary representation.

Returns:

Dictionary with either ‘nonce’ or ‘orderId’ key and string value.

Raises:

ValueError – If both nonce and order_id are None.

class hibachi_xyz.OrderModifyParams(orderId: str, accountId: int, symbol: str, quantity: Decimal | str | float | int, price: Decimal | str | float | int, side: Side, maxFeesPercent: Decimal | str | float | int, nonce: int | None = None)[source][source]

Bases: object

Parameters for modifying an order.

accountId: int[source]
maxFeesPercent: Decimal[source]
nonce: int | None[source]
orderId: str[source]
price: Decimal[source]
quantity: Decimal[source]
side: Side[source]
symbol: str[source]
class hibachi_xyz.OrderPlaceParams(symbol: str, quantity: Decimal | str | float | int, side: Side, orderType: OrderType, maxFeesPercent: Decimal | str | float | int, price: Decimal | str | float | int | None = None, trigger_price: Decimal | str | float | int | None = None, twap_config: TWAPConfig | None = None, orderFlags: str | None = None, creation_deadline: int | None = None, trigger_direction: TriggerDirection | None = None)[source][source]

Bases: object

Parameters for placing an order via REST.

creation_deadline: Decimal | None[source]
maxFeesPercent: Decimal[source]
orderFlags: str | None[source]
orderType: OrderType[source]
price: Decimal | None[source]
quantity: Decimal[source]
side: Side[source]
symbol: str[source]
trigger_direction: TriggerDirection | None[source]
trigger_price: Decimal | None[source]
twap_config: TWAPConfig | None[source]
class hibachi_xyz.OrderPlaceResponse(id: int, result: OrderPlaceResponseResult, status: int)[source][source]

Bases: object

Response from placing an order.

id: int[source]
result: OrderPlaceResponseResult[source]
status: int[source]
class hibachi_xyz.OrderPlaceResponseResult(orderId: str)[source][source]

Bases: object

Result of order placement.

orderId: str[source]
class hibachi_xyz.OrderResponse(accountId: str, availableQuantity: str, orderId: str, orderType: OrderType, price: str, side: Side, status: OrderStatus, symbol: str, totalQuantity: str)[source][source]

Bases: object

Order information in response.

accountId: str[source]
availableQuantity: str[source]
orderId: str[source]
orderType: OrderType[source]
price: str[source]
side: Side[source]
status: OrderStatus[source]
symbol: str[source]
totalQuantity: str[source]
class hibachi_xyz.OrderStatus(*values)[source][source]

Bases: Enum

Order status.

CANCELLED = 'CANCELLED'[source]
CHILD_PENDING = 'CHILD_PENDING'[source]
FILLED = 'FILLED'[source]
PARTIALLY_FILLED = 'PARTIALLY_FILLED'[source]
PENDING = 'PENDING'[source]
PLACED = 'PLACED'[source]
REJECTED = 'REJECTED'[source]
SCHEDULED_TWAP = 'SCHEDULED_TWAP'[source]
class hibachi_xyz.OrderStatusParams(orderId: str, accountId: str)[source][source]

Bases: object

Parameters for querying order status.

accountId: str[source]
orderId: str[source]
class hibachi_xyz.OrderStatusResponse(id: int, result: Order, status: int | None)[source][source]

Bases: object

Response containing single order status.

id: int[source]
result: Order[source]
status: int | None[source]
class hibachi_xyz.OrderType(*values)[source][source]

Bases: Enum

Order type.

LIMIT = 'LIMIT'[source]
MARKET = 'MARKET'[source]
class hibachi_xyz.OrdersBatchParams(accountId: str, orders: List[BatchOrder])[source][source]

Bases: object

Parameters for batch order operations.

accountId: str[source]
orders: List[BatchOrder][source]
class hibachi_xyz.OrdersCancelParams(accountId: str, nonce: str, contractId: int | None = None)[source][source]

Bases: object

Parameters for bulk order cancellation.

accountId: str[source]
contractId: int | None = None[source]
nonce: str[source]
class hibachi_xyz.OrdersStatusParams(accountId: int)[source][source]

Bases: object

Parameters for querying all orders status.

accountId: int[source]
class hibachi_xyz.OrdersStatusResponse(id: int, result: List[Order], status: int | None)[source][source]

Bases: object

Response containing multiple order statuses.

id: int[source]
result: List[Order][source]
status: int | None[source]
class hibachi_xyz.PendingOrdersResponse(orders: List[Order])[source][source]

Bases: object

Response containing pending orders.

orders: List[Order][source]
class hibachi_xyz.Position(direction: str, entryNotional: str, markPrice: str, notionalValue: str, openPrice: str, quantity: str, symbol: str, unrealizedFundingPnl: str, unrealizedTradingPnl: str)[source][source]

Bases: object

Position information.

direction: str[source]
entryNotional: str[source]
markPrice: str[source]
notionalValue: str[source]
openPrice: str[source]
quantity: str[source]
symbol: str[source]
unrealizedFundingPnl: str[source]
unrealizedTradingPnl: str[source]
class hibachi_xyz.PriceResponse(askPrice: str, bidPrice: str, fundingRateEstimation: FundingRateEstimation, markPrice: str, spotPrice: str, symbol: str, tradePrice: str)[source][source]

Bases: object

Price information for a symbol.

askPrice: str[source]
bidPrice: str[source]
fundingRateEstimation: FundingRateEstimation[source]
markPrice: str[source]
spotPrice: str[source]
symbol: str[source]
tradePrice: str[source]
exception hibachi_xyz.SerializationError(message: str)[source][source]

Bases: TransportError

Raised when request data cannot be serialized/encoded.

class hibachi_xyz.Settlement(direction: str, indexPrice: str, quantity: str, settledAmount: str, symbol: str, timestamp: int)[source][source]

Bases: object

Settlement information.

direction: str[source]
indexPrice: str[source]
quantity: str[source]
settledAmount: str[source]
symbol: str[source]
timestamp: int[source]
class hibachi_xyz.SettlementsResponse(settlements: List[Settlement])[source][source]

Bases: object

Response containing settlements.

settlements: List[Settlement][source]
class hibachi_xyz.Side(*values)[source][source]

Bases: Enum

Order side (buy/sell).

ASK = 'ASK'[source]
BID = 'BID'[source]
BUY = 'BUY'[source]
SELL = 'SELL'[source]
class hibachi_xyz.StatsResponse(high24h: str, low24h: str, symbol: str, volume24h: str)[source][source]

Bases: object

24-hour statistics for a symbol.

high24h: str[source]
low24h: str[source]
symbol: str[source]
volume24h: str[source]
class hibachi_xyz.TPSLConfig[source][source]

Bases: object

Configuration for Take-Profit/Stop-Loss orders.

class Leg(order_type: Type, price: Decimal, quantity: Decimal | None)[source][source]

Bases: object

Individual TP/SL leg configuration.

order_type: Type[source]
price: Decimal[source]
quantity: Decimal | None[source]
class Type(*values)[source][source]

Bases: Enum

TP/SL order type.

SL = 'SL'[source]
TP = 'TP'[source]
add_stop_loss(price: Decimal | str | float | int, quantity: Decimal | str | float | int | None = None) Self[source][source]

Add a stop-loss leg to the configuration.

add_take_profit(price: Decimal | str | float | int, quantity: Decimal | str | float | int | None = None) Self[source][source]

Add a take-profit leg to the configuration.

class hibachi_xyz.TWAPConfig(duration_minutes: int, quantity_mode: TWAPQuantityMode)[source][source]

Bases: object

Configuration for TWAP (Time-Weighted Average Price) orders.

duration_minutes: int[source]
quantity_mode: TWAPQuantityMode[source]
to_dict() Dict[str, Any][source][source]

Convert TWAP configuration to dictionary representation.

Returns:

Dictionary with ‘twapDurationMinutes’ and ‘twapQuantityMode’ keys.

class hibachi_xyz.TWAPQuantityMode(*values)[source][source]

Bases: Enum

TWAP quantity distribution mode.

FIXED = 'FIXED'[source]
RANDOM = 'RANDOM'[source]
class hibachi_xyz.TakerSide(*values)[source][source]

Bases: Enum

Taker side in a trade.

Buy = 'Buy'[source]
Sell = 'Sell'[source]
class hibachi_xyz.Trade(price: str, quantity: str, takerSide: str | TakerSide, timestamp: int)[source][source]

Bases: object

Individual trade information.

price: str[source]
quantity: str[source]
takerSide: TakerSide[source]
timestamp: int[source]
class hibachi_xyz.TradesResponse(trades: List[Trade])[source][source]

Bases: object

Response containing recent trades.

trades: List[Trade][source]
class hibachi_xyz.TradingTier(level: int, lowerThreshold: str, title: str, upperThreshold: str)[source][source]

Bases: object

Trading tier information.

level: int[source]
lowerThreshold: str[source]
title: str[source]
upperThreshold: str[source]
class hibachi_xyz.Transaction(id: int, assetId: int, quantity: str, status: str, timestampSec: int, transactionType: str, transactionHash: str | None = None, token: str | None = None, etaTsSec: int | None = None, blockNumber: int | None = None, chain: str | None = None, instantWithdrawalChain: str | None = None, instantWithdrawalToken: str | None = None, isInstantWithdrawal: bool | None = None, withdrawalAddress: str | None = None, receivingAddress: str | None = None, receivingAccountId: int | None = None, srcAccountId: int | None = None, srcAddress: str | None = None)[source][source]

Bases: object

Transaction record.

assetId: int[source]
blockNumber: int | None[source]
chain: str | None[source]
etaTsSec: int | None[source]
id: int[source]
instantWithdrawalChain: str | None[source]
instantWithdrawalToken: str | None[source]
isInstantWithdrawal: bool | None[source]
quantity: str[source]
receivingAccountId: int | None[source]
receivingAddress: str | None[source]
srcAccountId: int | None[source]
srcAddress: str | None[source]
status: str[source]
timestampSec: int[source]
token: str | None[source]
transactionHash: str | None[source]
transactionType: str[source]
withdrawalAddress: str | None[source]
class hibachi_xyz.TransferRequest(accountId: int, coin: str, fees: Decimal | str | float | int, nonce: int, quantity: Decimal | str | float | int, dstPublicKey: str, signature: str)[source][source]

Bases: object

Transfer request.

accountId: int[source]
coin: str[source]
dstPublicKey: str[source]
fees: Decimal[source]
nonce: int[source]
quantity: Decimal[source]
signature: str[source]
class hibachi_xyz.TransferResponse(status: str)[source][source]

Bases: object

Transfer response.

status: str[source]
exception hibachi_xyz.TransportError[source][source]

Bases: BaseError

Exception raised for errors in the process of transporting data to/from the API server.

This exception is raised when there’s a problem in the process of transporting data to or from the API server, either in the local networking stack before data is sent, during transmission over the network, or when receiving and processing data.

TransportError indicates that:
  • The error occurred in the process of transporting data

  • Valid application-level data was not successfully exchanged

  • The error could be transient and may succeed on retry

Common causes include:

Local stack errors (before transmission):
  • Serialization failures (unable to encode data)

  • TLS/SSL certificate errors

  • Local socket/file descriptor exhaustion

  • DNS resolution failures

  • Proxy configuration errors

Network errors (during transmission):
  • Connection timeouts

  • Connection refused or dropped

  • Network unreachable

  • TLS/SSL handshake failures

  • Read/write timeouts

Protocol/data handling errors (after transmission):
  • Malformed protocol responses

  • Unexpected connection closure

  • WebSocket connection drops

  • Deserialization failures (malformed or corrupt data)

exception hibachi_xyz.TransportTimeoutError(message: str, timeout_seconds: float | None = None)[source][source]

Bases: TransportError

Raised when a request or connection times out.

class hibachi_xyz.TriggerDirection(*values)[source][source]

Bases: Enum

Trigger direction for conditional orders.

HIGH = 'HIGH'[source]
LOW = 'LOW'[source]
class hibachi_xyz.UpdateOrder(order_id: int, symbol: str, side: Side, quantity: Decimal | str | float | int, max_fees_percent: Decimal | str | float | int, price: Decimal | str | float | int | None = None, trigger_price: Decimal | str | float | int | None = None, creation_deadline: Decimal | str | float | int | None = None, parent_order: OrderIdVariant | None = None, order_flags: OrderFlags | None = None)[source][source]

Bases: object

Request to update an existing order.

action: str = 'modify'[source]
creation_deadline: Decimal | None[source]
max_fees_percent: Decimal[source]
order_flags: OrderFlags | None[source]
order_id: int[source]
parent_order: OrderIdVariant | None[source]
price: Decimal | None[source]
quantity: Decimal[source]
side: Side[source]
symbol: str[source]
trigger_price: Decimal | None[source]
exception hibachi_xyz.ValidationError[source][source]

Bases: BaseError

Exception raised for client-side input validation failures.

This exception is raised when input parameters fail validation checks before any request is sent to the API server. ValidationError indicates a problem with the arguments provided to SDK methods, such as missing required fields, invalid types, out-of-range values, or malformed data.

ValidationError indicates that:
  • No network request was attempted

  • The error is due to invalid input from the caller

  • The error can be fixed by correcting the input parameters

Common causes include:
  • Missing required parameters

  • Invalid parameter types (e.g., string instead of number)

  • Out-of-range values

  • Malformed identifiers or formats

  • Mutually exclusive parameters specified together

class hibachi_xyz.WebSocketBatchOrder(action: str, nonce: int, symbol: str, orderType: str, side: str, quantity: str, price: str, maxFeesPercent: str, signature: str, orderId: str | None = None, updatedQuantity: str | None = None, updatedPrice: str | None = None)[source][source]

Bases: object

WebSocket batch order operation.

action: str[source]
maxFeesPercent: str[source]
nonce: int[source]
orderId: str | None = None[source]
orderType: str[source]
price: str[source]
quantity: str[source]
side: str[source]
signature: str[source]
symbol: str[source]
updatedPrice: str | None = None[source]
updatedQuantity: str | None = None[source]
exception hibachi_xyz.WebSocketConnectionError(message: str, url: str | None = None)[source][source]

Bases: TransportError

Raised when WebSocket connection fails or is closed unexpectedly.

class hibachi_xyz.WebSocketEvent(account: str, event: str, data: Dict[str, Any])[source][source]

Bases: object

WebSocket event notification.

account: str[source]
data: Dict[str, Any][source]
event: str[source]
class hibachi_xyz.WebSocketMarketSubscriptionListResponse(subscriptions: List[WebSocketSubscription])[source][source]

Bases: object

List of WebSocket subscriptions.

subscriptions: List[WebSocketSubscription][source]
exception hibachi_xyz.WebSocketMessageError(message: str)[source][source]

Bases: TransportError

Raised when there’s an error processing a WebSocket message.

class hibachi_xyz.WebSocketOrderCancelParams(orderId: str, accountId: str, nonce: int)[source][source]

Bases: object

Parameters for WebSocket order cancellation.

accountId: str[source]
nonce: int[source]
orderId: str[source]
class hibachi_xyz.WebSocketOrderModifyParams(orderId: str, accountId: str, symbol: str, quantity: str, price: str, maxFeesPercent: str)[source][source]

Bases: object

Parameters for WebSocket order modification.

accountId: str[source]
maxFeesPercent: str[source]
orderId: str[source]
price: str[source]
quantity: str[source]
symbol: str[source]
class hibachi_xyz.WebSocketOrderStatusParams(orderId: str, accountId: str)[source][source]

Bases: object

Parameters for WebSocket order status query.

accountId: str[source]
orderId: str[source]
class hibachi_xyz.WebSocketOrdersBatchParams(accountId: str, orders: List[WebSocketBatchOrder])[source][source]

Bases: object

Parameters for WebSocket batch order operations.

accountId: str[source]
orders: List[WebSocketBatchOrder][source]
class hibachi_xyz.WebSocketOrdersCancelParams(accountId: str, nonce: str, contractId: int | None = None)[source][source]

Bases: object

Parameters for WebSocket bulk order cancellation.

accountId: str[source]
contractId: int | None = None[source]
nonce: str[source]
class hibachi_xyz.WebSocketOrdersStatusParams(accountId: str)[source][source]

Bases: object

Parameters for WebSocket orders status query.

accountId: str[source]
class hibachi_xyz.WebSocketResponse(id: int | None, result: Dict[str, Any] | None, status: int | None, subscriptions: List[WebSocketSubscription] | None)[source][source]

Bases: object

Generic WebSocket response.

id: int | None[source]
result: Dict[str, Any] | None[source]
status: int | None[source]
subscriptions: List[WebSocketSubscription] | None[source]
class hibachi_xyz.WebSocketStreamPingParams(accountId: str, listenKey: str, timestamp: int)[source][source]

Bases: object

Parameters for WebSocket stream ping.

accountId: str[source]
listenKey: str[source]
timestamp: int[source]
class hibachi_xyz.WebSocketStreamStartParams(accountId: str)[source][source]

Bases: object

Parameters to start WebSocket stream.

accountId: str[source]
class hibachi_xyz.WebSocketStreamStopParams(accountId: str, listenKey: str, timestamp: int)[source][source]

Bases: object

Parameters to stop WebSocket stream.

accountId: str[source]
listenKey: str[source]
timestamp: int[source]
class hibachi_xyz.WebSocketSubscription(symbol: str, topic: WebSocketSubscriptionTopic)[source][source]

Bases: object

WebSocket subscription configuration.

symbol: str[source]
topic: WebSocketSubscriptionTopic[source]
class hibachi_xyz.WebSocketSubscriptionTopic(*values)[source][source]

Bases: Enum

WebSocket subscription topics.

ASK_BID_PRICE = 'ask_bid_price'[source]
FUNDING_RATE_ESTIMATION = 'funding_rate_estimation'[source]
KLINES = 'klines'[source]
MARK_PRICE = 'mark_price'[source]
ORDERBOOK = 'orderbook'[source]
SPOT_PRICE = 'spot_price'[source]
TRADES = 'trades'[source]
class hibachi_xyz.WithdrawRequest(accountId: int, coin: str, withdrawAddress: str, network: str, quantity: Decimal | str | float | int, maxFees: Decimal | str | float | int, signature: str)[source][source]

Bases: object

Withdrawal request.

accountId: int[source]
coin: str[source]
maxFees: Decimal[source]
network: str[source]
quantity: Decimal[source]
signature: str[source]
withdrawAddress: str[source]
class hibachi_xyz.WithdrawResponse(orderId: str)[source][source]

Bases: object

Withdrawal response.

orderId: str[source]
class hibachi_xyz.WithdrawalLimit(lowerLimit: str, upperLimit: str)[source][source]

Bases: object

Withdrawal limits.

lowerLimit: str[source]
upperLimit: str[source]
hibachi_xyz.price_to_bytes(price: Decimal | str | float | int, contract: FutureContract) bytes[source][source]

Convert price to bytes representation for signing.

Converts a price value to an 8-byte representation adjusted for contract decimals and scaled by 2^32 for fixed-point representation.

Parameters:
  • price – The price value to convert

  • contract – The future contract containing decimal precision info

Returns:

8-byte big-endian representation of the scaled price

Return type:

bytes

hibachi_xyz.print_data(response: Any) None[source][source]

Pretty-print response data, handling dataclasses specially.

Dataclass instances are converted to dictionaries before printing for better formatting.

Parameters:

response – Data to print