Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Hibachi SDKs
https://github.com/hibachi-xyz/hibachi_sdk
Admin
Official SDKs for interacting with the Hibachi cryptocurrency exchange API.
Tokens:
21,016
Snippets:
204
Trust Score:
4.8
Update:
3 months ago
Context
Chat
Benchmark
64
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Get Account Info using Environment Setup (Python) Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/README.md Retrieves account information after initializing the client using environment variables. Prints the account balance and total position notional. ```python account_info = hibachi.get_account_info() print(f"Account Balance: {account_info.balance}") print(f"total Position Notional: {account_info.totalPositionNotional}") ``` -------------------------------- ### Install Hibachi Python SDK Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Install the SDK using pip and set up a virtual environment. ```bash pip install hibachi-xyz==<x.x.x> python3 -m venv myapp source myapp/bin/activate ``` -------------------------------- ### Example Usage of HibachiWSAccountClient Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md This example demonstrates how to connect to the account WebSocket, start streaming data, listen for messages, and handle reconnections with backoff. It requires environment variables to be set up. ```python import asyncio import os import time from datetime import datetime, timezone from hibachi_xyz import HibachiWSAccountClient, print_data from hibachi_xyz.env_setup import setup_environment def now(): return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") async def example_ws_account(): print("Loading environment variables from .env file") api_endpoint, _, api_key, account_id, _, _, _ = setup_environment() ws_base_url = api_endpoint.replace("https://", "wss://") attempt = 1 backoff = 1 # seconds while True: print(f"[{now()}] [Attempt {attempt}] Connecting to WebSocket...") myaccount_live = HibachiWSAccountClient( api_endpoint=ws_base_url, api_key=api_key, account_id=account_id ) start_time = time.time() try: await myaccount_live.connect() result_start = await myaccount_live.stream_start() print(f"[Connected] stream_start result:") print_data(result_start) print("Listening for account WebSocket messages (Ctrl+C to stop)...") last_msg_time = time.time() while True: message = await myaccount_live.listen() if message is None: print(f"[{now()}] No message received. (Ping sent.) " f"Last message was {int(time.time() - last_msg_time)}s ago.") continue last_msg_time = time.time() print_data(message) except asyncio.CancelledError: print(f"[{now()}] CancelledError caught. Cleaning up WebSocket connection.") await myaccount_live.disconnect() break except Exception as e: print(f"[Error] {e}") finally: duration = time.time() - start_time print(f"[{now()}] Disconnected. Connection lasted {duration:.2f} seconds.") await myaccount_live.disconnect() print(f"[{now()}] Client cleaned up.") print(f"Reconnecting in {backoff} seconds...\n") try: await asyncio.sleep(backoff) except asyncio.CancelledError: print(f"[{now()}] Cancelled during backoff sleep. Exiting.") break attempt += 1 backoff = min(backoff * 2, 60) if __name__ == "__main__": try: asyncio.run(example_ws_account()) except KeyboardInterrupt: print(f"[{now()}] KeyboardInterrupt received. Exiting cleanly.") ``` -------------------------------- ### Setup and Run Tests Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Navigate to the SDK directory, create a Python virtual environment, and run tests using pytest. ```shell cd hibachi_sdk python3 -m venv python # Run tests ./bin/pytest -v -s ``` -------------------------------- ### get_account_info Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get account information/details. ```APIDOC ## GET /trade/account/info ### Description Get account information/details. ### Method GET ### Endpoint /trade/account/info ``` -------------------------------- ### Start Account Data Stream Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Initiates the streaming of account information, including assets, positions, and balances. This method is asynchronous. ```python async def stream_start() -> AccountStreamStartResult ``` -------------------------------- ### Setup Environment and Initialize Hibachi Client (Python) Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/README.md Sets up the environment variables from a .env file and initializes the Hibachi API client. This method is useful for loading credentials securely. ```python # ensure .env has the values set. from hibachi_xyz.env_setup import setup_environment api_endpoint, data_api_endpoint, api_key, account_id, private_key, public_key, _ = setup_environment() hibachi = HibachiApiClient( api_url= api_endpoint, data_api_url= data_api_endpoint, api_key = api_key, account_id = account_id, private_key = private_key, ) ``` -------------------------------- ### Example Usage of HibachiWSMarketClient Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Demonstrates how to instantiate, connect, subscribe to market data topics, handle incoming messages, and gracefully disconnect the HibachiWSMarketClient. This is useful for real-time market data consumption. ```python import asyncio from hibachi_xyz import ( HibachiWSMarketClient, WebSocketSubscription, print_data ) async def example_ws_market(): client = HibachiWSMarketClient() await client.connect() subscriptions = [ WebSocketSubscription(symbol="BTC/USDT-P", topic="mark_price"), WebSocketSubscription(symbol="BTC/USDT-P", topic="trades"), ] # Async handlers for message topics async def handle_mark_price(msg): print("[Mark Price]", msg) async def handle_trades(msg): print("[Trades]", msg) client.on("mark_price", handle_mark_price) client.on("trades", handle_trades) await client.subscribe(subscriptions) print("Subscribed. Press Ctrl+C to exit.\n") try: # Wait forever (or until Ctrl+C) while True: await asyncio.sleep(1) except KeyboardInterrupt: print("\n[Shutdown] Ctrl+C detected.") finally: print("[Cleanup] Unsubscribing and disconnecting...") await client.unsubscribe(subscriptions) await client.disconnect() print("[Done] Gracefully exited.") if __name__ == "__main__": import sys try: asyncio.run(example_ws_market()) except KeyboardInterrupt: # Suppress ugly stack trace on Ctrl+C print("\n[Exit] Keyboard interrupt received. Shutting down cleanly.") sys.exit(0) ``` -------------------------------- ### Upgrade Hibachi SDK Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/release-notes/v0.2.0.md Install the latest version of the Hibachi SDK using pip. ```bash pip install --upgrade hibachi_xyz ``` -------------------------------- ### connect Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Establishes a WebSocket connection to the market data endpoint. It initializes the client and starts a background task for receiving messages. ```APIDOC ## connect ### Description Establishes a WebSocket connection to the market data endpoint. It initializes the client and starts a background task for receiving messages. ### Method async def connect(self) ### Parameters None ### Response Example None ``` -------------------------------- ### Initialize Hibachi API Client with Environment Setup Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Initialize the Hibachi API client using environment variables loaded by `setup_environment`. This method ensures all necessary credentials are correctly loaded. ```python # ensure .env has the values set. from hibachi_xyz.env_setup import setup_environment api_endpoint, data_api_endpoint, api_key, account_id, private_key, public_key, _ = setup_environment() hibachi = HibachiApiClient( api_url= api_endpoint, data_api_url= data_api_endpoint, api_key = api_key, account_id = account_id, private_key = private_key, ) account_info = hibachi.get_account_info() print(f"Account Balance: {account_info.balance}") print(f"total Position Notional: {account_info.totalPositionNotional}") ``` -------------------------------- ### get_prices Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the price and funding information for a future contract. ```APIDOC ## GET /market/data/prices ### Description Get the price and funding information for a future contract. ### Method GET ### Endpoint /market/data/prices ``` -------------------------------- ### Example Composite Test File Structure Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/tests/README.md Illustrates the structure of a `test.*.json` file, which can contain multiple related API responses for comprehensive testing. ```json { "response.exchange_info": { "feeConfig": { ... }, "futureContracts": [ ... ], "serverTimestamp": 1728000000, "apiVersion": "v2.1.0" }, "response.withdraw": { "coin": "USDT", "orderId": "12345", "estimatedCompletionTime": 1728000300 } } ``` -------------------------------- ### get_capital_balance Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the balance of your account. ```APIDOC ## GET /capital/balance ### Description Get the balance of your account. ### Method GET ### Endpoint /capital/balance ``` -------------------------------- ### Initialize Hibachi API Client and Get Account Info (Python) Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/README.md Initializes the Hibachi API client with provided credentials and retrieves account information. Ensure you have your API key, account ID, and private key. ```python from hibachi_xyz import HibachiApiClient # Initialize client hibachi = HibachiApiClient( api_key="your-api-key", account_id=123, private_key="your-private-key" ) # Get account info account_info = hibachi.get_account_info() print(f"Balance: {account_info.balance}") ``` -------------------------------- ### Get Deposit Information Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Retrieves the deposit address for a given public key. Use this to obtain an address for funding your account. ```python deposit_info = client.get_deposit_info(public_key="0x...") print(deposit_info.depositAddressEvm) ``` -------------------------------- ### get_deposit_info Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get deposit address. ```APIDOC ## GET /capital/deposit-info ### Description Get deposit address. ### Method GET ### Endpoint /capital/deposit-info ``` -------------------------------- ### get_orderbook Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the orderbook price levels. ```APIDOC ## GET /market/data/orderbook ### Description Get the orderbook price levels. ### Method GET ### Endpoint /market/data/orderbook ``` -------------------------------- ### Configure Logging for Hibachi SDK Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/release-notes/v0.2.0.md Set up Python's logging module to capture output from the Hibachi SDK instead of using print statements. This example shows basic configuration. ```python import logging # Setup logging config logging.basicConfig(level=logging.INFO) # just an example, your standard config setup should work # Retrieve SDK logger logger = logging.getLogger('hibachi_xyz') # Configure SDK logger ... ``` -------------------------------- ### get_order_details Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the details about your one particular order. ```APIDOC ## GET /trade/order ### Description Get the details about your one particular order. ### Method GET ### Endpoint /trade/order ``` -------------------------------- ### Get Capital Balance Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Retrieves the net equity of your account, including unrealized PnL. Use this to check your current account balance. ```python capital_balance = client.get_capital_balance() print(capital_balance.balance) ``` -------------------------------- ### get_capital_history Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the deposit and withdraw history of your account. ```APIDOC ## GET /capital/history ### Description Get the deposit and withdraw history of your account. ### Method GET ### Endpoint /capital/history ``` -------------------------------- ### get_stats Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get 24h high/low/volume for a future contract. ```APIDOC ## GET /market/data/stats ### Description Get 24h high/low/volume for a future contract. ### Method GET ### Endpoint /market/data/stats ``` -------------------------------- ### Get Order Details Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Fetch details for a specific order using `get_order_details`. You can query by either `order_id` or `nonce`. Ensure one of these parameters is provided. ```python order_details = client.get_order_details(order_id=123) # or order_details = client.get_order_details(nonce=1234567) ``` -------------------------------- ### get_pending_orders Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the pending orders of your account. ```APIDOC ## GET /trade/orders ### Description Get the pending orders of your account. ### Method GET ### Endpoint /trade/orders ``` -------------------------------- ### get_klines Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the candlesticks for a future contract. ```APIDOC ## GET /market/data/klines ### Description Get the candlesticks for a future contract. ### Method GET ### Endpoint /market/data/klines ``` -------------------------------- ### Environment Variables for Hibachi API Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/README.md Example of environment variables required for the Hibachi API. These should be stored in a .env file for secure credential management. ```dotenv ENVIRONMENT=production HIBACHI_API_ENDPOINT_PRODUCTION="https://api.hibachi.xyz" HIBACHI_DATA_API_ENDPOINT_PRODUCTION="https://data-api.hibachi.xyz" HIBACHI_API_KEY_PRODUCTION="your_api_key_here" HIBACHI_PRIVATE_KEY_PRODUCTION="your_private_key_here" HIBACHI_PUBLIC_KEY_PRODUCTION="your_public_key_here" HIBACHI_ACCOUNT_ID_PRODUCTION="your_account_id_here" HIBACHI_TRANSFER_DST_ACCOUNT_PUBLIC_KEY_PRODUCTION="transfer_destination_account_public_key_here" ``` -------------------------------- ### get_open_interest Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the open interest for one future contract. ```APIDOC ## GET /market/data/open-interest ### Description Get the open interest for one future contract. ### Method GET ### Endpoint /market/data/open-interest ``` -------------------------------- ### Get All Order Statuses Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Retrieves the status of all currently active orders for the account. ```python async def get_orders_status() -> OrdersStatusResponse ``` -------------------------------- ### Get Capital History Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Fetches the deposit and withdrawal history for your account, returning up to 100 of each. This is useful for auditing financial transactions. ```python capital_history = client.get_capital_history() ``` -------------------------------- ### Get Account Information Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Fetches detailed information about your account, including balances, maximal withdrawal amounts, and asset details. This is essential for understanding your account's status. ```python account_info = client.get_account_info() print(account_info.balance) ``` -------------------------------- ### get_order_details Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get details for a specific order using either its order ID or a nonce. This is useful for checking the status and specifics of a single order. ```APIDOC ## GET /trade/order ### Description Retrieves the details of a specific order. ### Method GET ### Endpoint /trade/order ### Parameters #### Query Parameters - **order_id** (Optional[int]) - The ID of the order to retrieve. - **nonce** (Optional[int]) - A nonce value to identify the order. ### Response #### Success Response (200) - **Order** (object) - An object containing the details of the order, including account ID, available quantity, order ID, order type, status, symbol, etc. ### Response Example ```json { "accountId": "int", "availableQuantity": "str", "contractId": "Optional[int]", "creationTime": "Optional[int]", "finishTime": "Optional[int]", "numOrdersRemaining": "Optional[int]", "numOrdersTotal": "Optional[int]", "orderId": "str", "orderType": "OrderType", "price": "Optional[str]", "quantityMode": "Optional[str]", "side": "Side", "status": "OrderStatus", "symbol": "str", "totalQuantity": "Optional[str]", "triggerPrice": "Optional[str]" } ``` ``` -------------------------------- ### Get Exchange Information Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Fetch and print exchange metadata, including future contracts and maintenance windows. This method calls the /market/exchange-info endpoint. ```python exchange_info = client.get_exchange_info() print(exchange_info) ``` -------------------------------- ### Get Pending Orders Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Retrieve a list of all pending orders for the account using the `get_pending_orders` method. This is useful for monitoring open trade positions. ```python pending_orders = client.get_pending_orders() ``` -------------------------------- ### Get Orderbook Data Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Retrieve orderbook price levels for a given trading symbol, depth, and granularity. This method calls the /market/data/orderbook endpoint. ```python orderbook = client.get_orderbook(symbol="BTC/USDT-P", depth=20, granularity=0.01) print(orderbook) ``` -------------------------------- ### Initialize HibachiApiClient Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Initialize the HibachiApiClient with API credentials and account details. Ensure environment variables for API key, account ID, and private key are set. ```python 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"), ) ``` -------------------------------- ### get_account_trades Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get the trades history of your account. ```APIDOC ## GET /trade/account/trades ### Description Get the trades history of your account. ### Method GET ### Endpoint /trade/account/trades ``` -------------------------------- ### Initialize and Use HibachiWSTradeClient Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Demonstrates how to initialize the HibachiWSTradeClient with API credentials, connect to the WebSocket, retrieve order status, modify an order, and print the results. Ensure environment variables for API keys and account ID are set. ```python 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) # client.api.set_private_key(private_key) 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()) ``` -------------------------------- ### Initialize Hibachi API Client Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Initialize the Hibachi API client with default settings. Ensure your .env file is configured with API credentials. ```python from hibachi_xyz import HibachiApiClient from dotenv import load_dotenv import os load_dotenv() hibachi = HibachiApiClient() exchange_info = hibachi.get_exchange_info() print(exchange_info) ``` -------------------------------- ### stream_start Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Initiates the streaming of account information, including assets, positions, and balances. ```APIDOC ## stream_start ### Description Initiates the streaming of account information, including assets, positions, and balances. ### Method `async def stream_start() -> AccountStreamStartResult` ### Endpoint (This is a method call, not a direct HTTP endpoint.) ### Parameters None ### Request Example (This is a method call, no explicit request body.) ### Response #### Success Response (200) - **AccountStreamStartResult** (object) - Result object indicating the stream has started successfully. ``` -------------------------------- ### get_trades Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get recent trades from all users for one future contract. ```APIDOC ## GET /market/data/trades ### Description Get recent trades from all users for one future contract. ### Method GET ### Endpoint /market/data/trades ``` -------------------------------- ### Generate Documentation Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Execute the documentation generation script to update the README.md file. Ensure doc_header.md and doc_footer.md are updated prior to generation. ```shell ./bin/python docs.py # updates README.md ``` -------------------------------- ### Connect to WebSocket Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Establishes a WebSocket connection with retry logic. This is the initial step before performing any trade operations. ```python async def connect() ``` -------------------------------- ### Place a New Order Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Use this method to place a new order on the trading platform. It requires order placement parameters. ```python async def place_order(params: OrderPlaceParams) -> tuple[Nonce, int] ``` -------------------------------- ### Get Specific Order Status Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Retrieves the status of a single, specific order using its order ID. ```python async def get_order_status(orderId: int) -> OrderStatusResponse ``` -------------------------------- ### get_pending_orders Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Get a list of all pending orders. This method allows users to view orders that have not yet been executed or canceled. ```APIDOC ## GET /trade/orders ### Description Retrieves a list of all pending orders for the account. ### Method GET ### Endpoint /trade/orders ### Response #### Success Response (200) - **orders** (array) - A list of pending order objects, each containing details such as account ID, available quantity, order ID, order type, status, and symbol. ### Response Example ```json { "orders": [ { "accountId": "int", "availableQuantity": "str", "contractId": "Optional[int]", "creationTime": "Optional[int]", "finishTime": "Optional[int]", "numOrdersRemaining": "Optional[int]", "numOrdersTotal": "Optional[int]", "orderId": "str", "orderType": "OrderType", "price": "Optional[str]", "quantityMode": "Optional[str]", "side": "Side", "status": "OrderStatus", "symbol": "str", "totalQuantity": "Optional[str]", "triggerPrice": "Optional[str]" } ] } ``` ``` -------------------------------- ### Connect to Account WebSocket Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Establishes a WebSocket connection to the account endpoint. It uses a helper function `connect_with_retry` and includes authentication headers. ```python async def connect(self): self.websocket = await connect_with_retry( web_url=self.api_endpoint + f"/ws/account?accountId={self.account_id}", headers=[("Authorization", self.api_key)] ) ``` -------------------------------- ### Hibachi SDK Repository Structure Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/README.md Overview of the directory structure for the Hibachi SDK repository. Highlights the main README, Python SDK specifics, and other components. ```tree hibachi_sdk/ ├── README.md # This file - multi-SDK overview ├── python/ # Python SDK │ ├── README.md # Python-specific documentation │ ├── hibachi_xyz/ # SDK source code │ ├── examples/ # Usage examples │ ├── tests/ # Test suite │ └── docs/ # Sphinx documentation └── CODEOWNERS # Repository ownership ``` -------------------------------- ### Connect to WebSocket Market Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Establishes a connection to the market data WebSocket endpoint. This method should be called before subscribing to any data. ```python async def connect(self): self.websocket = await connect_with_retry(self.api_endpoint) self._receive_task = asyncio.create_task(self._receive_loop()) return self ``` -------------------------------- ### HibachiWSMarketClient Methods Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Methods for managing the market websocket connection and subscribing to market data streams. ```APIDOC ## HibachiWSMarketClient ### Methods * **connect()**: Establishes a connection to the market websocket. * **subscribe(streams: list)**: Subscribes to one or more market data streams. * **unsubscribe(streams: list)**: Unsubscribes from market data streams. * **disconnect()**: Closes the market websocket connection. ``` -------------------------------- ### Place a Limit Order (Python) Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/README.md Places a limit order on the Hibachi exchange. Requires symbol, quantity, price, side, and max fees percentage. Returns nonce and order ID. ```python # Place a limit order nonce, order_id = hibachi.place_limit_order( symbol="BTC/USDT-P", quantity=0.001, price=50000, side=Side.BUY, max_fees_percent=0.001 ) ``` -------------------------------- ### Get Settlements History Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Obtain the history of settled trades using the `get_settlements_history` method. This method retrieves settlement data for the account. ```python settlements = client.get_settlements_history() ``` -------------------------------- ### Place Limit Order Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Place a limit order using the `place_limit_order` method. This requires specifying the symbol, quantity, price, side, and maximum fees. Optional parameters include `trigger_price` and `creation_deadline`. ```python (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) (nonce, trigger_limit_order_id) = client.place_limit_order("BTC/USDT-P", 0.001, 90_000, Side.ASK, max_fees_percent, trigger_price=90_100) ``` -------------------------------- ### Place Limit Order with Trigger Direction Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/release-notes/v0.3.1.md Place a limit order and specify the `trigger_direction` for TPSL (take-profit/stop-loss) functionality. This is now correctly supported for limit orders. ```python client.place_limit_order( "BTC/USDT-P", 0.001, 1_001_000, Side.ASK, max_fees_percent, trigger_price=1_000_000, trigger_direction=TriggerDirection.LOW, ) ``` -------------------------------- ### connect Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Establishes a WebSocket connection to the account endpoint. It uses a retry mechanism for robust connection attempts. ```APIDOC ## connect ### Description Establishes a WebSocket connection to the account endpoint. It uses a retry mechanism for robust connection attempts. ### Method `async def connect(self)` ### Endpoint (Implicitly handled by `connect_with_retry` using `self.api_endpoint` and account ID) ### Parameters None directly exposed in this method signature, but relies on client initialization parameters. ### Request Example (No explicit request body for connection establishment) ### Response (Connection status is managed internally; successful connection results in a valid WebSocket object.) #### Success Response (A successful connection yields an active WebSocket object.) #### Response Example (No explicit response body for connection establishment.) ``` -------------------------------- ### Migrating Order Placement to v0.3.0 Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/release-notes/v0.3.0.md Update your order placement logic to use `round_price_to_tick` before submitting prices. This ensures compliance with the new tick size enforcement, preventing `ValidationError`. ```python # Before (may now raise ValidationError) client.place_limit_order( symbol="BTC/USDT-P", quantity=0.001, price=float(mark_price), # e.g., 71286.1234567 side=Side.BID, max_fees_percent=max_fees, ) # After from hibachi_xyz import round_price_to_tick tick_size = client.get_tick_size("BTC/USDT-P") price = round_price_to_tick(float(mark_price), tick_size) client.place_limit_order( symbol="BTC/USDT-P", quantity=0.001, price=price, side=Side.BID, max_fees_percent=max_fees, ) ``` -------------------------------- ### connect Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Establishes a WebSocket connection with retry logic. This method should be called before any other trade operations. ```APIDOC ## connect ### Description Establish WebSocket connection with retry logic. ### Method `async def connect()` ### Endpoint N/A (WebSocket connection) ### Parameters None ### Request Example ```python await client.connect() ``` ### Response N/A (Establishes connection, no direct return value specified for success) ### Error Handling Connection errors are handled internally with retry logic. ``` -------------------------------- ### Update Exception Handling (Before vs. After) Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/release-notes/v0.2.0.md Transition from generic exception handling to specific Hibachi SDK exception types for more granular error management. ```python # Before (still works) try: client.place_order(...) except Exception as e: print(f"Error: {e}") ``` ```python # After (recommended) from hibachi_xyz.errors import ValidationError, HttpConnectionError try: client.place_order(...) except ValidationError as e: print(f"Invalid parameters: {e}") except HttpConnectionError as e: print(f"Network error: {e}") ``` -------------------------------- ### Get Account Trades History Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Retrieves the recent trade history for your account, limited to the most recent 100 records. Useful for reviewing past trading activity. ```python account_trades = client.get_account_trades() ``` -------------------------------- ### get_inventory Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Fetches inventory details, including cross-chain assets, fee configurations, market data with latest price information, and trading tier details. ```APIDOC ## get_inventory ### Description Similar to /market/exchange-info, in addition to the contract metadata we will return their latest price info. ### Response #### Success Response (200) - **crossChainAssets** (object[]) - Description - **feeConfig** (object) - Description - **markets** (object[]) - Description - **tradingTiers** (object[]) - Description ### Response Example ```json { "crossChainAssets": [ { "chain": "string", "exchangeRateFromUSDT": "string", "exchangeRateToUSDT": "string", "instantWithdrawalLowerLimitInUSDT": "string", "instantWithdrawalUpperLimitInUSDT": "string", "token": "string" } ], "feeConfig": { "depositFees": "string", "instantWithdrawDstPublicKey": "string", "instantWithdrawalFees": "List[List[Union[int, float]]", "tradeMakerFeeRate": "string", "tradeTakerFeeRate": "string", "transferFeeRate": "string", "withdrawalFees": "string" }, "markets": [ { "contract": { "displayName": "string", "id": 0, "marketCloseTimestamp": "Optional[str]", "marketOpenTimestamp": "Optional[str]", "minNotional": "string", "minOrderSize": "string", "orderbookGranularities": ["string"], "initialMarginRate": "string", "maintenanceMarginRate": "string", "settlementDecimals": 0, "settlementSymbol": "string", "status": "string", "stepSize": "string", "symbol": "string", "tickSize": "string", "underlyingDecimals": 0, "underlyingSymbol": "string" }, "info": { "category": "string", "price24hAgo": "string", "priceLatest": "string", "tags": ["string"] } } ], "tradingTiers": [ { "level": 0, "lowerThreshold": "string", "title": "string", "upperThreshold": "string" } ] } ``` ``` -------------------------------- ### HibachiWSAccountClient Methods Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Methods for managing the account websocket connection and listening to account-related streams. ```APIDOC ## HibachiWSAccountClient ### Methods * **connect()**: Establishes a connection to the account websocket. * **stream_start(stream_name: str)**: Starts a specific data stream. * **listen()**: Listens for incoming messages on the websocket. * **disconnect()**: Closes the websocket connection. ``` -------------------------------- ### get_inventory Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Similar to exchange info, includes price data. ```APIDOC ## GET /market/inventory ### Description Similar to exchange info, includes price data. ### Method GET ### Endpoint /market/inventory ``` -------------------------------- ### place_order Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Places a new order using the provided order parameters. Returns a tuple containing a nonce and an integer representing the order ID. ```APIDOC ## place_order ### Description Place a new order. ### Method `async def place_order(params: OrderPlaceParams) -> tuple[Nonce, int]` ### Endpoint N/A (WebSocket operation) ### Parameters #### Request Body - **params** (OrderPlaceParams) - Required - Parameters for placing an order. ### Request Example ```python # Assuming order_params is an instance of OrderPlaceParams nonce, order_id = await client.place_order(params=order_params) ``` ### Response #### Success Response - **Nonce** (Nonce) - A unique nonce for the operation. - **int** (int) - The ID of the placed order. #### Response Example ```json { "nonce": "some_nonce_value", "orderId": 12345 } ``` ``` -------------------------------- ### Configure Hibachi SDK Environment Variables Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Set these environment variables to configure the Hibachi SDK. Ensure your API keys and sensitive information are kept secure. These variables define the API endpoints and authentication credentials. ```sh # Default API endpoint HIBACHI_API_ENDPOINT_PRODUCTION="https://api.hibachi.xyz" # Default data API endpoint HIBACHI_DATA_API_ENDPOINT_PRODUCTION="https://data-api.hibachi.xyz" # Your API key HIBACHI_API_KEY_PRODUCTION="" # Your account ID HIBACHI_ACCOUNT_ID_PRODUCTION="" # Your private key HIBACHI_PRIVATE_KEY_PRODUCTION="" ``` -------------------------------- ### place_market_order Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Place a market order for a given symbol and quantity. This order will be executed at the best available market price. ```APIDOC ## POST /trade/order ### Description Places a market order for a specified trading pair. ### Method POST ### Endpoint /trade/order ### Parameters #### Request Body - **symbol** (str) - The trading pair symbol (e.g., "BTC/USDT-P"). - **quantity** (float) - The amount of the asset to trade. - **side** (Side) - The side of the order (BUY, SELL, BID, ASK). - **max_fees_percent** (float) - The maximum allowed percentage for fees. - **trigger_price** (Optional[float]) - The price at which to trigger the order. - **twap_config** (Optional[TWAPConfig]) - Configuration for Time-Weighted Average Price orders. - **creation_deadline** (Optional[int]) - The deadline for order creation in seconds. ### Response #### Success Response (200) - **tuple[Nonce, OrderId]** - A tuple containing the nonce and order ID of the placed order. ### Request Example ```json { "symbol": "BTC/USDT-P", "quantity": 0.0001, "side": "BUY", "max_fees_percent": 0.01, "creation_deadline": 2 } ``` ``` -------------------------------- ### place_market_order Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Submit a new market order. ```APIDOC ## POST /trade/order ### Description Submit a new market order. ### Method POST ### Endpoint /trade/order ``` -------------------------------- ### place_limit_order Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Place a limit order for a given symbol, quantity, and price. This order will only be executed at the specified price or better. ```APIDOC ## POST /trade/order ### Description Places a limit order for a specified trading pair at a specific price. ### Method POST ### Endpoint /trade/order ### Parameters #### Request Body - **symbol** (str) - The trading pair symbol (e.g., "BTC/USDT-P"). - **quantity** (float) - The amount of the asset to trade. - **price** (float) - The price at which to execute the order. - **side** (Side) - The side of the order (BUY, SELL, BID, ASK). - **max_fees_percent** (float) - The maximum allowed percentage for fees. - **trigger_price** (Optional[float]) - The price at which to trigger the order. - **creation_deadline** (Optional[int]) - The deadline for order creation in seconds. ### Response #### Success Response (200) - **tuple[Nonce, OrderId]** - A tuple containing the nonce and order ID of the placed order. ### Request Example ```json { "symbol": "BTC/USDT-P", "quantity": 0.0001, "price": 80000, "side": "BUY", "max_fees_percent": 0.01, "creation_deadline": 2 } ``` ``` -------------------------------- ### HibachiWSTradeClient Methods Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Methods for managing the trade websocket connection, placing and managing orders via websocket. ```APIDOC ## HibachiWSTradeClient ### Methods * **connect()**: Establishes a connection to the trade websocket. * **place_order(params: dict)**: Places an order via the trade websocket. * **cancel_order(order_id: str)**: Cancels an order via the trade websocket. * **modify_order(order_id: str, params: dict)**: Modifies an existing order via the trade websocket. * **get_order_status(order_id: str)**: Retrieves the status of a specific order. * **get_orders_status(order_ids: list)**: Retrieves the status of multiple orders. * **cancel_all_orders()**: Cancels all open orders. * **batch_orders(params: list)**: Submits multiple orders in a batch. * **enable_cancel_on_disconnect()**: Enables the cancel-on-disconnect feature. * **disconnect()**: Closes the trade websocket connection. ``` -------------------------------- ### Place Market Order Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Execute a market order with the `place_market_order` method. Specify the symbol, quantity, side, and maximum fees. Optional parameters include `trigger_price`, `twap_config`, and `creation_deadline`. ```python (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) (nonce, trigger_market_order_id) = client.place_market_order("BTC/USDT-P", 0.001, Side.ASK, max_fees_percent, trigger_price=90_100) ``` -------------------------------- ### listen Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Listens for incoming messages from the WebSocket. Includes a 5-second timeout that triggers a ping to keep the connection alive. ```APIDOC ## listen ### Description Listens for incoming messages from the WebSocket. Includes a 5-second timeout that triggers a ping to keep the connection alive. ### Method `async def listen(self) -> Optional[dict]` ### Endpoint (This is a method call, not a direct HTTP endpoint.) ### Parameters None ### Request Example (This is a method call, no explicit request body.) ### Response #### Success Response (200) - **Optional[dict]** - A dictionary containing the received message, or None if no message is received within the timeout period. ``` -------------------------------- ### HibachiApiClient Methods Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Methods for interacting with the Hibachi REST API to retrieve exchange information, manage orders, and access account details. ```APIDOC ## HibachiApiClient ### Methods * **get_exchange_info()**: Retrieves general exchange information. * **get_inventory()**: Fetches inventory details. * **get_open_interest()**: Retrieves open interest data. * **get_orderbook(symbol: str)**: Gets the order book for a given symbol. * **get_capital_balance()**: Retrieves capital balance information. * **get_capital_history()**: Fetches the history of capital transactions. * **withdraw(params: dict)**: Initiates a withdrawal. * **transfer(params: dict)**: Executes a fund transfer. * **get_deposit_info(asset: str)**: Retrieves deposit information for a specific asset. * **get_account_info()**: Fetches general account information. * **get_account_trades(symbol: str)**: Retrieves trades for a specific account and symbol. * **get_settlements_history()**: Fetches the history of settlements. * **get_pending_orders(symbol: str)**: Retrieves pending orders for a given symbol. * **get_order_details(order_id: str)**: Gets details for a specific order. * **place_market_order(params: dict)**: Places a market order. * **place_limit_order(params: dict)**: Places a limit order. * **update_order(order_id: str, params: dict)**: Updates an existing order. * **cancel_order(order_id: str)**: Cancels a specific order. * **cancel_all_orders(symbol: str)**: Cancels all open orders for a given symbol. * **batch_orders(params: list)**: Submits multiple orders in a batch. ``` -------------------------------- ### Place Market Order with TPSL and Trigger Price Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/release-notes/v0.3.1.md Place a market order with TPSL configuration and a trigger price. The SDK now raises a `ValidationError` immediately if the order is simultaneously a parent TPSL order and a trigger order, preventing exchange rejections. ```python # Now raises ValidationError immediately client.place_market_order( "BTC/USDT-P", 0.001, Side.BUY, max_fees_percent, trigger_price=85_000, tpsl=TPSLConfig().add_take_profit(price=90_000), ) ``` -------------------------------- ### batch_orders Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Submit multiple order requests for an account. Place or Modify. ```APIDOC ## POST /trade/orders ### Description Submit multiple order requests for an account. Place or Modify. ### Method POST ### Endpoint /trade/orders ``` -------------------------------- ### Enable Cancel on Disconnect Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Configures the system to automatically cancel all open orders when the WebSocket connection is disconnected. Requires specific parameters. ```python async def enable_cancel_on_disconnect( params: EnableCancelOnDisconnectParams) -> WebSocketResponse ``` -------------------------------- ### Submit Withdrawal Request Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Initiates a withdrawal of funds from your account. Ensure the quantity does not exceed the maximalWithdraw limit and specify the network. ```python client.withdraw(coin="USDT", withdraw_address="0x...", quantity="100", max_fees="10", network="arbitrum") ``` -------------------------------- ### New Helper Functions for Tick and Step Sizes Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/release-notes/v0.3.0.md Utilize these functions to round prices and quantities according to contract specifications. `round_price_to_tick` ensures prices align with tick size, `round_quantity_to_step` adjusts quantities to valid increments, and `check_tick_size` validates prices without modification. ```python from hibachi_xyz import round_price_to_tick, round_quantity_to_step, check_tick_size # Round a price to the nearest valid tick increment tick_size = client.get_tick_size("BTC/USDT-P") price = round_price_to_tick(mark_price * 0.99, tick_size) # Round a quantity down to the nearest valid step increment step_size = client.get_step_size("BTC/USDT-P") quantity = round_quantity_to_step(desired_qty, step_size) # Validate a price without rounding (raises ValidationError if invalid) check_tick_size(price, tick_size) ``` -------------------------------- ### Listen for Account WebSocket Messages Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Listens for incoming messages from the account WebSocket. It has a 5-second timeout that triggers a ping if no message is received. ```python async def listen(self) -> Optional[dict] ``` -------------------------------- ### batch_orders Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Performs batch operations for creating, updating, and canceling orders. ```APIDOC ## POST /trade/orders ### Description Executes a batch of order operations, including creation, updates, and cancellations. Requires full details for existing orders when updating. ### Method POST ### Endpoint /trade/orders ### Parameters #### Request Body - **orders** (list[CreateOrder | UpdateOrder | CancelOrder]) - Required - A list of order operations to perform. ### Request Example ```python # Example usage: # 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), # # Update limit order # 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), # ]) ``` ### Response #### Success Response (200) - **Dict[str, Any]** - A dictionary containing the response from the API. ``` -------------------------------- ### Subscribe to Market Data Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Sends a subscription request to the WebSocket server for specified market data topics. Ensure the client is connected before calling this method. ```python async def subscribe(self, subscriptions: List[WebSocketSubscription]): message = { "method": "subscribe", "parameters": { "subscriptions": [ {**asdict(sub), "topic": sub.topic} for sub in subscriptions ] } } await self.websocket.send(json.dumps(message)) ``` -------------------------------- ### place_limit_order Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Submit a new limit order. ```APIDOC ## POST /trade/order ### Description Submit a new limit order. ### Method POST ### Endpoint /trade/order ``` -------------------------------- ### Fetch klines with Time Range Filter Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/release-notes/v0.3.1.md Use the `from_ms` and `to_ms` parameters to filter candlestick data by a specific time window. Omitting these parameters returns all available klines. ```python # Fetch klines for a specific time window klines = client.get_klines( "BTC/USDT-P", Interval.ONE_HOUR, from_ms=1700000000000, to_ms=1700003600000, ) ``` -------------------------------- ### Batch Orders Operation Source: https://github.com/hibachi-xyz/hibachi_sdk/blob/main/python/README.md Executes multiple order operations (e.g., place, cancel, modify) in a single request for efficiency. Requires batch order parameters. ```python async def batch_orders(params: OrdersBatchParams) -> WebSocketResponse ```