### Install Extended Python SDK Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Installs the x10-python-trading-starknet package using pip. This command is essential for setting up the SDK in your Python environment. ```shell pip install x10-python-trading-starknet ``` -------------------------------- ### Get Orders History with Python SDK Source: https://context7.com/x10xchange/python_sdk/llms.txt Fetches historical order data with support for pagination and filtering using the X10 Python SDK. This example shows how to retrieve orders by market, side, and limit, and also how to get a specific order by its ID or external ID. Requires StarkPerpetualAccount and PerpetualTradingClient. ```python import asyncio from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient from x10.perpetual.orders import OrderSide async def get_orders_history(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) # Get order history with filters and pagination orders_history = await trading_client.account.get_orders_history( market_names=["BTC-USD", "ETH-USD"], order_side=OrderSide.BUY, limit=50, ) for order in orders_history.data: print(f"Order {order.id}: {order.market} {order.side} {order.qty} @ ${order.price} - {order.status}") # Get specific order by ID order = await trading_client.account.get_order_by_id(order_id=12345) print(f"Order details: {order.to_pretty_json()}") # Get order by external ID orders = await trading_client.account.get_order_by_external_id(external_id="my-order-123") await trading_client.close() asyncio.run(get_orders_history()) ``` -------------------------------- ### Get User Accounts Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Retrieves all accounts associated with the user, returning a list of OnBoardedAccount objects. ```python accounts = user_client.get_accounts() ``` -------------------------------- ### Get Positions API Source: https://context7.com/x10xchange/python_sdk/llms.txt Fetches current open positions with optional filtering by market and side. ```APIDOC ## GET /positions ### Description Fetches current open positions with optional filtering. ### Method GET ### Endpoint /positions ### Query Parameters - **market_names** (list[str]) - Optional - Filter positions by market names. - **position_side** (PositionSide) - Optional - Filter positions by side (LONG or SHORT). ### Response #### Success Response (200) - **data** (list[Position]) - A list of position objects. - **market** (str) - The market name. - **side** (PositionSide) - The side of the position (LONG or SHORT). - **size** (float) - The size of the position. - **mark_price** (float) - The current mark price of the market. - **open_price** (float) - The average opening price of the position. - **leverage** (float) - The leverage applied to the position. - **unrealised_pnl** (float) - The unrealized profit or loss. - **liquidation_price** (float) - The liquidation price for the position. ### Response Example ```json { "data": [ { "market": "BTC-USD", "side": "LONG", "size": 0.01, "mark_price": 30000.00, "open_price": 29500.00, "leverage": 10.0, "unrealised_pnl": 50.00, "liquidation_price": 28000.00 } ] } ``` ``` -------------------------------- ### Get Market Information using Python SDK Source: https://context7.com/x10xchange/python_sdk/llms.txt Retrieves comprehensive market data, including configuration, statistics, orderbook snapshots, historical candles, and funding rates. Requires initialization of StarkPerpetualAccount and PerpetualTradingClient. Outputs include market details, statistics, orderbook prices, candle data, and funding rates. ```python import asyncio from datetime import datetime, timedelta from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient from x10.perpetual.candles import CandleType, CandleInterval async def get_market_info(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) # Get all markets markets = await trading_client.markets_info.get_markets() for market in markets.data: print(f"{market.name}: Min size={market.trading_config.min_order_size}") # Get market as dictionary for easy lookup markets_dict = await trading_client.markets_info.get_markets_dict() btc_market = markets_dict["BTC-USD"] # Get market statistics stats = await trading_client.markets_info.get_market_statistics(market_name="BTC-USD") print(f"BTC-USD: Last={stats.data.last_price}, 24h Volume={stats.data.volume_24h}") # Get orderbook snapshot orderbook = await trading_client.markets_info.get_orderbook_snapshot(market_name="BTC-USD") print(f"Best Bid: {orderbook.data.bid[0].price}, Best Ask: {orderbook.data.ask[0].price}") # Get candles history candles = await trading_client.markets_info.get_candles_history( market_name="BTC-USD", candle_type=CandleType.TRADE, interval=CandleInterval.ONE_HOUR, limit=24, ) for candle in candles.data: print(f"Open: {candle.open}, High: {candle.high}, Low: {candle.low}, Close: {candle.close}") # Get funding rates history now = datetime.utcnow() funding = await trading_client.markets_info.get_funding_rates_history( market_name="BTC-USD", start_time=now - timedelta(days=7), end_time=now, ) await trading_client.close() asyncio.run(get_market_info()) ``` -------------------------------- ### Cancel Orders (Python) Source: https://context7.com/x10xchange/python_sdk/llms.txt Provides examples for canceling individual orders by ID or external ID, and performing mass cancellations by order IDs, external IDs, or markets. It also shows how to cancel all open orders. This function requires account setup and uses the PerpetualTradingClient. ```python import asyncio from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient async def cancel_orders(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) # Cancel by order ID await trading_client.orders.cancel_order(order_id=12345) # Cancel by external ID await trading_client.orders.cancel_order_by_external_id(order_external_id="my-order-123") # Mass cancel by order IDs await trading_client.orders.mass_cancel(order_ids=[12345, 12346, 12347]) # Mass cancel by external IDs await trading_client.orders.mass_cancel(external_order_ids=["order-1", "order-2"]) # Mass cancel by market await trading_client.orders.mass_cancel(markets=["BTC-USD", "ETH-USD"]) # Cancel all orders await trading_client.orders.mass_cancel(cancel_all=True) await trading_client.close() asyncio.run(cancel_orders()) ``` -------------------------------- ### Get Positions with Python SDK Source: https://context7.com/x10xchange/python_sdk/llms.txt Fetches current open positions from the X10 perpetual trading platform using the Python SDK. It demonstrates how to retrieve all positions or filter them by market and side. Requires StarkPerpetualAccount and PerpetualTradingClient initialization. ```python import asyncio from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient from x10.perpetual.positions import PositionSide async def get_positions(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) # Get all positions positions = await trading_client.account.get_positions() for position in positions.data: print(f"Market: {position.market}") print(f" Side: {position.side}") print(f" Size: {position.size}") print(f" Mark Price: ${position.mark_price}") print(f" Open Price: ${position.open_price}") print(f" Leverage: {position.leverage}x") print(f" Unrealized PnL: ${position.unrealised_pnl}") print(f" Liquidation Price: ${position.liquidation_price}") # Filter by market and side btc_longs = await trading_client.account.get_positions( market_names=["BTC-USD"], position_side=PositionSide.LONG, ) await trading_client.close() asyncio.run(get_positions()) ``` -------------------------------- ### Get Open Orders API Source: https://context7.com/x10xchange/python_sdk/llms.txt Retrieves all open orders with optional filtering by market, type, and side. ```APIDOC ## GET /open_orders ### Description Retrieves all open orders with optional filtering. ### Method GET ### Endpoint /open_orders ### Query Parameters - **market_names** (list[str]) - Optional - Filter orders by market names. - **order_type** (OrderType) - Optional - Filter orders by type (e.g., LIMIT, MARKET). - **order_side** (OrderSide) - Optional - Filter orders by side (BUY or SELL). ### Response #### Success Response (200) - **data** (list[Order]) - A list of open order objects. - **id** (int) - The unique identifier for the order. - **market** (str) - The market name. - **side** (OrderSide) - The side of the order (BUY or SELL). - **type** (OrderType) - The type of the order (e.g., LIMIT, MARKET). - **price** (float) - The price of the order. - **qty** (float) - The quantity of the order. - **filled_qty** (float) - The quantity already filled. - **status** (str) - The current status of the order. ### Response Example ```json { "data": [ { "id": 12345, "market": "BTC-USD", "side": "BUY", "type": "LIMIT", "price": 29000.00, "qty": 0.005, "filled_qty": 0.000, "status": "OPEN" } ] } ``` ``` -------------------------------- ### Get Orders History API Source: https://context7.com/x10xchange/python_sdk/llms.txt Retrieves historical orders with pagination support and filtering. ```APIDOC ## GET /orders_history ### Description Retrieves historical orders with pagination support and optional filtering. ### Method GET ### Endpoint /orders_history ### Query Parameters - **market_names** (list[str]) - Optional - Filter orders by market names. - **order_side** (OrderSide) - Optional - Filter orders by side (BUY or SELL). - **limit** (int) - Optional - The maximum number of orders to return. ### Response #### Success Response (200) - **data** (list[Order]) - A list of historical order objects. - **id** (int) - The unique identifier for the order. - **market** (str) - The market name. - **side** (OrderSide) - The side of the order (BUY or SELL). - **qty** (float) - The quantity of the order. - **price** (float) - The price of the order. - **status** (str) - The status of the order. ### Response Example ```json { "data": [ { "id": 12346, "market": "ETH-USD", "side": "SELL", "qty": 0.1, "price": 1800.00, "status": "FILLED" } ] } ``` ## GET /order/{order_id} ### Description Retrieves a specific order by its unique ID. ### Method GET ### Endpoint /order/{order_id} ### Path Parameters - **order_id** (int) - Required - The unique identifier of the order. ### Response #### Success Response (200) - **order** (Order) - The order object details. ### Response Example ```json { "order": { "id": 12345, "market": "BTC-USD", "side": "BUY", "type": "LIMIT", "price": 29000.00, "qty": 0.005, "filled_qty": 0.005, "status": "FILLED" } } ``` ## GET /orders_by_external_id/{external_id} ### Description Retrieves orders associated with a given external ID. ### Method GET ### Endpoint /orders_by_external_id/{external_id} ### Path Parameters - **external_id** (str) - Required - The external identifier for the orders. ### Response #### Success Response (200) - **data** (list[Order]) - A list of order objects matching the external ID. ### Response Example ```json { "data": [ { "id": 12347, "market": "SOL-USD", "side": "BUY", "type": "MARKET", "price": 0.00, "qty": 1.0, "filled_qty": 1.0, "status": "FILLED" } ] } ``` ``` -------------------------------- ### Manage Leverage Settings - Python Source: https://context7.com/x10xchange/python_sdk/llms.txt Allows users to get and update leverage settings for trading markets using the x10xchange Python SDK. It requires account authentication and specifies the market and desired leverage. The function first retrieves current leverage and then updates it. ```python import asyncio from decimal import Decimal from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient async def manage_leverage(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) # Get current leverage for markets leverage_info = await trading_client.account.get_leverage(market_names=["BTC-USD", "ETH-USD"]) for lev in leverage_info.data: print(f"{lev.market}: {lev.leverage}x leverage") # Update leverage for a market await trading_client.account.update_leverage( market_name="BTC-USD", leverage=Decimal("20.0"), ) print("Leverage updated to 20x for BTC-USD") await trading_client.close() asyncio.run(manage_leverage()) ``` -------------------------------- ### Get Open Orders with Python SDK Source: https://context7.com/x10xchange/python_sdk/llms.txt Retrieves all currently open orders using the X10 Python SDK. The function shows how to fetch all open orders or filter them by market, order type, and side. It requires setting up the StarkPerpetualAccount and PerpetualTradingClient. ```python import asyncio from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient from x10.perpetual.orders import OrderSide, OrderType async def get_open_orders(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) # Get all open orders open_orders = await trading_client.account.get_open_orders() for order in open_orders.data: print(f"Order ID: {order.id}") print(f" Market: {order.market}") print(f" Side: {order.side}") print(f" Type: {order.type}") print(f" Price: ${order.price}") print(f" Quantity: {order.qty}") print(f" Filled: {order.filled_qty}") print(f" Status: {order.status}") # Filter by market, type, and side btc_buy_orders = await trading_client.account.get_open_orders( market_names=["BTC-USD"], order_type=OrderType.LIMIT, order_side=OrderSide.BUY, ) await trading_client.close() asyncio.run(get_open_orders()) ``` -------------------------------- ### Get Market Information Source: https://context7.com/x10xchange/python_sdk/llms.txt Retrieve market configuration, statistics, and orderbook snapshots for various markets. This includes fetching all markets, specific market details, statistics, orderbook data, historical candles, and funding rates. ```APIDOC ## GET /markets ### Description Retrieves a list of all available markets on the exchange. ### Method GET ### Endpoint /markets ### Parameters None ### Request Example None ### Response #### Success Response (200) - **data** (array) - An array of market objects. - **name** (string) - The name of the market (e.g., "BTC-USD"). - **trading_config** (object) - Configuration for trading in this market. - **min_order_size** (string) - The minimum order size allowed for this market. #### Response Example ```json { "data": [ { "name": "BTC-USD", "trading_config": { "min_order_size": "0.0001" } } ] } ``` ## GET /markets/{market_name} ### Description Retrieves detailed information for a specific market. ### Method GET ### Endpoint /markets/{market_name} ### Parameters #### Path Parameters - **market_name** (string) - Required - The name of the market to retrieve (e.g., "BTC-USD"). ### Request Example None ### Response #### Success Response (200) - **data** (object) - Market details. - **name** (string) - The name of the market. - **trading_config** (object) - Configuration for trading in this market. - **min_order_size** (string) - The minimum order size allowed for this market. #### Response Example ```json { "data": { "name": "BTC-USD", "trading_config": { "min_order_size": "0.0001" } } } ``` ## GET /markets/statistics ### Description Retrieves trading statistics for all markets. ### Method GET ### Endpoint /markets/statistics ### Parameters None ### Request Example None ### Response #### Success Response (200) - **data** (object) - An object containing statistics for each market. - **market_name** (string) - The name of the market. - **last_price** (string) - The last traded price. - **volume_24h** (string) - The trading volume over the last 24 hours. #### Response Example ```json { "data": { "BTC-USD": { "last_price": "30000.00", "volume_24h": "100000000.00" } } } ``` ## GET /markets/{market_name}/orderbook ### Description Retrieves the current orderbook snapshot for a given market. ### Method GET ### Endpoint /markets/{market_name}/orderbook ### Parameters #### Path Parameters - **market_name** (string) - Required - The name of the market (e.g., "BTC-USD"). ### Request Example None ### Response #### Success Response (200) - **data** (object) - Orderbook data. - **bid** (array) - An array of bid orders. - **price** (string) - The price of the bid. - **size** (string) - The size of the bid. - **ask** (array) - An array of ask orders. - **price** (string) - The price of the ask. - **size** (string) - The size of the ask. #### Response Example ```json { "data": { "bid": [ {"price": "29999.50", "size": "10.0"} ], "ask": [ {"price": "30000.50", "size": "5.0"} ] } } ``` ## GET /markets/{market_name}/candles ### Description Retrieves historical candle data for a given market and interval. ### Method GET ### Endpoint /markets/{market_name}/candles ### Parameters #### Path Parameters - **market_name** (string) - Required - The name of the market (e.g., "BTC-USD"). #### Query Parameters - **candle_type** (string) - Required - The type of candles (e.g., "TRADE", "FUNDING"). - **interval** (string) - Required - The candle interval (e.g., "ONE_HOUR", "ONE_DAY"). - **limit** (integer) - Optional - The number of candles to retrieve. - **start_time** (integer) - Optional - The start timestamp for the candle data. - **end_time** (integer) - Optional - The end timestamp for the candle data. ### Request Example None ### Response #### Success Response (200) - **data** (array) - An array of candle objects. - **open** (string) - The opening price. - **high** (string) - The highest price. - **low** (string) - The lowest price. - **close** (string) - The closing price. - **timestamp** (integer) - The timestamp of the candle. #### Response Example ```json { "data": [ { "open": "29900.00", "high": "30100.00", "low": "29800.00", "close": "30050.00", "timestamp": 1678886400 } ] } ``` ## GET /markets/{market_name}/funding-rates ### Description Retrieves historical funding rates for a given market. ### Method GET ### Endpoint /markets/{market_name}/funding-rates ### Parameters #### Path Parameters - **market_name** (string) - Required - The name of the market (e.g., "BTC-USD"). #### Query Parameters - **start_time** (integer) - Required - The start timestamp for the funding rates. - **end_time** (integer) - Required - The end timestamp for the funding rates. ### Request Example None ### Response #### Success Response (200) - **data** (array) - An array of funding rate objects. - **rate** (string) - The funding rate. - **timestamp** (integer) - The timestamp of the funding rate. #### Response Example ```json { "data": [ { "rate": "0.0001", "timestamp": 1678886400 } ] } ``` ``` -------------------------------- ### Get Current Positions Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Retrieves the current open positions for the user's account. It can optionally filter positions by market name and side. The fetched positions are logged. ```python import logging logger = logging.getLogger("demo_logger") positions = await trading_client.account.get_positions() logger.info("Positions: %s", positions.to_pretty_json()) ``` -------------------------------- ### Get Historical Positions Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Fetches the historical positions of the user's account, allowing filtering by market name and position side. The historical data is then logged. ```python import logging logger = logging.getLogger("demo_logger") positions = await trading_client.account.get_positions_history() logger.info("Positions: %s", positions.to_pretty_json()) ``` -------------------------------- ### Get Account Balance Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Fetches the current balance of the user's trading account using the `get_balance` method. The balance is then logged in a pretty JSON format. ```python import logging logger = logging.getLogger("demo_logger") balance = await trading_client.account.get_balance() logger.info("Balance: %s", balance.to_pretty_json()) ``` -------------------------------- ### Subscribe to Multiple WebSocket Streams Concurrently Source: https://context7.com/x10xchange/python_sdk/llms.txt This example shows how to handle multiple WebSocket subscriptions simultaneously using the PerpetualStreamClient. It sets up concurrent tasks to listen for orderbook updates, public trades, funding rates, candle data, and account updates for a given trading pair and API key. An asyncio.Event is used to manage the stopping of these streams. ```python import asyncio from x10.perpetual.configuration import MAINNET_CONFIG from x10.perpetual.stream_client import PerpetualStreamClient from x10.perpetual.candles import CandleType, CandleInterval async def multi_stream_subscription(): stream_client = PerpetualStreamClient(api_url=MAINNET_CONFIG.stream_url) stop_event = asyncio.Event() async def handle_orderbook(): async with stream_client.subscribe_to_orderbooks("BTC-USD") as stream: while not stop_event.is_set(): try: msg = await asyncio.wait_for(stream.recv(), timeout=1.0) print(f"Orderbook: {msg.type}#{msg.seq}") except asyncio.TimeoutError: pass async def handle_trades(): async with stream_client.subscribe_to_public_trades("BTC-USD") as stream: while not stop_event.is_set(): try: msg = await asyncio.wait_for(stream.recv(), timeout=1.0) if msg.data: for trade in msg.data: print(f"Trade: {trade.side} {trade.qty} @ {trade.price}") except asyncio.TimeoutError: pass async def handle_funding_rates(): async with stream_client.subscribe_to_funding_rates("BTC-USD") as stream: while not stop_event.is_set(): try: msg = await asyncio.wait_for(stream.recv(), timeout=1.0) if msg.data: print(f"Funding Rate: {msg.data.funding_rate}") except asyncio.TimeoutError: pass async def handle_candles(): async with stream_client.subscribe_to_candles( "BTC-USD", CandleType.TRADE, CandleInterval.ONE_MINUTE ) as stream: while not stop_event.is_set(): try: msg = await asyncio.wait_for(stream.recv(), timeout=1.0) if msg.data: print(f"Candle: O={msg.data[0].open} C={msg.data[0].close}") except asyncio.TimeoutError: pass async def handle_account(api_key: str): async with stream_client.subscribe_to_account_updates(api_key) as stream: while not stop_event.is_set(): try: msg = await asyncio.wait_for(stream.recv(), timeout=1.0) print(f"Account Update: {msg.type}#{msg.seq}") if msg.data: if msg.data.orders: print(f" Orders: {len(msg.data.orders)}") if msg.data.positions: print(f" Positions: {len(msg.data.positions)}") if msg.data.balance: print(f" Balance updated") except asyncio.TimeoutError: pass # Run all streams concurrently await asyncio.gather( handle_orderbook(), handle_trades(), handle_funding_rates(), handle_candles(), handle_account("your-api-key"), ) asyncio.run(multi_stream_subscription()) ``` -------------------------------- ### Get Account Balance (Python) Source: https://context7.com/x10xchange/python_sdk/llms.txt Retrieves the current balance details for a trading account, including equity, available balance, and margin information. It requires account authentication and uses the PerpetualTradingClient to fetch the data. The output is presented in a pretty JSON format. ```python import asyncio from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient async def get_balance(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) balance = await trading_client.account.get_balance() print(f"Balance: {balance.to_pretty_json()}") # Output includes: equity, available_balance, initial_margin, maintenance_margin, etc. await trading_client.close() asyncio.run(get_balance()) ``` -------------------------------- ### Get Account Trades - Python Source: https://context7.com/x10xchange/python_sdk/llms.txt Retrieves the trade history for a specific account on the x10xchange platform. It requires account credentials and allows filtering trades by market and side. The function returns a list of trade objects. ```python import asyncio from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient from x10.perpetual.orders import OrderSide from x10.perpetual.trades import TradeType async def get_trades(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) trades = await trading_client.account.get_trades( market_names=["BTC-USD"], trade_side=OrderSide.BUY, limit=100, ) for trade in trades.data: print(f"Trade: {trade.market} {trade.side} {trade.qty} @ ${trade.price}") await trading_client.close() asyncio.run(get_trades()) ``` -------------------------------- ### Get Trading Fees - Python Source: https://context7.com/x10xchange/python_sdk/llms.txt Retrieves trading fee rates for specified markets on the x10xchange platform. This function requires account authentication and can optionally include a builder ID for fee sharing. It returns fee information including maker and taker rates. ```python import asyncio from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient async def get_fees(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient(TESTNET_CONFIG, stark_account) fees = await trading_client.account.get_fees(market_names=["BTC-USD", "ETH-USD"]) for fee in fees.data: print(f"{fee.market}: Maker={fee.maker_fee_rate}, Taker={fee.taker_fee_rate}") # Get fees with builder ID for fee sharing builder_fees = await trading_client.account.get_fees( market_names=["BTC-USD"], builder_id=12345, ) await trading_client.close() asyncio.run(get_fees()) ``` -------------------------------- ### Onboard New Accounts and Manage API Keys in Python Source: https://context7.com/x10xchange/python_sdk/llms.txt Shows how to onboard new accounts and manage API keys using an Ethereum wallet. This involves creating a UserClient, onboarding a main account, generating an API key, and setting up a PerpetualTradingClient. ```python import asyncio from eth_account import Account from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.trading_client import PerpetualTradingClient from x10.perpetual.user_client.user_client import UserClient async def onboard_new_account(): eth_account = Account.from_key("YOUR_ETH_PRIVATE_KEY") # Create UserClient with Ethereum account user_client = UserClient( endpoint_config=TESTNET_CONFIG, l1_private_key=eth_account.key.hex, ) # Onboard main account (derives L2 keys from L1 signature) root_account = await user_client.onboard(referral_code="OPTIONAL_REFERRAL") print(f"Vault ID: {root_account.account.l2_vault}") print(f"L2 Public Key: {root_account.l2_key_pair.public_hex}") print(f"L2 Private Key: {root_account.l2_key_pair.private_hex}") # Create API key for trading api_key = await user_client.create_account_api_key( account=root_account.account, description="Trading Bot Key", ) print(f"API Key: {api_key}") # Create trading client with onboarded credentials trading_client = PerpetualTradingClient( TESTNET_CONFIG, StarkPerpetualAccount( vault=root_account.account.l2_vault, private_key=root_account.l2_key_pair.private_hex, public_key=root_account.l2_key_pair.public_hex, api_key=api_key, ), ) # Claim testnet funds (testnet only) claim = await trading_client.testnet.claim_testing_funds() print(f"Claimed testnet funds: {claim.data.id if claim.data else 'Failed'}") await user_client.close_session() await trading_client.close() asyncio.run(onboard_new_account()) ``` -------------------------------- ### PerpetualTradingClient Initialization and Place Order Source: https://context7.com/x10xchange/python_sdk/llms.txt This snippet demonstrates how to initialize the PerpetualTradingClient and place a limit order using the convenience method. ```APIDOC ## POST /api/v1/orders ### Description Places a new order on the perpetual futures market. ### Method POST ### Endpoint /api/v1/orders ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **market_name** (string) - Required - The name of the market (e.g., "BTC-USD"). - **amount_of_synthetic** (Decimal) - Required - The amount of synthetic asset to trade. - **price** (Decimal) - Required - The price at which to place the order. - **side** (OrderSide) - Required - The side of the order (BUY or SELL). - **post_only** (boolean) - Optional - If true, the order will only be placed if it does not immediately match with an existing order. ### Request Example ```python { "market_name": "BTC-USD", "amount_of_synthetic": "0.01", "price": "63000.0", "side": "BUY", "post_only": true } ``` ### Response #### Success Response (200) - **data** (object) - Contains details of the placed order. - **id** (string) - The unique identifier of the order. - **external_id** (string) - The external identifier of the order. #### Response Example ```json { "data": { "id": "order-id-123", "external_id": "external-order-id-456" } } ``` ``` -------------------------------- ### Instantiate Perpetual Trading Client and Place Order Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Creates a PerpetualTradingClient instance using the provided configuration and StarkPerpetualAccount. It demonstrates placing a sell order for BTC-USD and then canceling it. Requires Decimal for price and amount. ```python from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.orders import OrderSide from x10.perpetual.trading_client import PerpetualTradingClient from decimal import Decimal trading_client = PerpetualTradingClient.create(TESTNET_CONFIG, stark_account) placed_order = await trading_client.place_order( market_name="BTC-USD", amount_of_synthetic=Decimal("1"), price=Decimal("63000.1"), side=OrderSide.SELL, ) await trading_client.orders.cancel_order(order_id=placed_order.id) print(placed_order) ``` -------------------------------- ### Create and Manage Subaccounts in Python Source: https://context7.com/x10xchange/python_sdk/llms.txt Illustrates how to create and manage subaccounts under the same Ethereum wallet. This includes onboarding a subaccount with a specific index and retrieving a list of all associated accounts. ```python import asyncio from eth_account import Account from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.user_client.user_client import UserClient async def manage_subaccounts(): eth_account = Account.from_key("YOUR_ETH_PRIVATE_KEY") user_client = UserClient( endpoint_config=TESTNET_CONFIG, l1_private_key=eth_account.key.hex, ) # Create subaccount with index 1 subaccount = await user_client.onboard_subaccount( account_index=1, description="Trading Bot Subaccount", ) print(f"Subaccount Vault: {subaccount.account.l2_vault}") # Get all accounts all_accounts = await user_client.get_accounts() for acc in all_accounts: print(f"Account {acc.account.account_index}: Vault={acc.account.l2_vault}") await user_client.close_session() asyncio.run(manage_subaccounts()) ``` -------------------------------- ### Create Account API Key Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Generates an API key for a specified account with an optional description. Returns the newly created API key as a string. ```python api_key = user_client.create_account_api_key(account=account_model, description="My API Key") ``` -------------------------------- ### Initialize Trading Client Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Initializes the trading client with specified endpoint configuration. This is essential for interacting with the X10 exchange API. ```python trading_client = TradingClient(endpoint_configuration=MAINNET_CONFIG) ``` -------------------------------- ### Place Order with create_order_object Source: https://context7.com/x10xchange/python_sdk/llms.txt This snippet shows how to create an order object with fine-grained control using the `create_order_object` function and then place it. ```APIDOC ## POST /api/v1/orders ### Description Places a new order on the perpetual futures market using a pre-constructed order object. ### Method POST ### Endpoint /api/v1/orders ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **order** (object) - Required - The order object constructed using `create_order_object`. - **market_name** (string) - The name of the market. - **amount_of_synthetic** (Decimal) - The amount of synthetic asset to trade. - **price** (Decimal) - The price at which to place the order. - **side** (OrderSide) - The side of the order (BUY or SELL). - **time_in_force** (TimeInForce) - The time in force for the order (e.g., GTT). - **reduce_only** (boolean) - If true, the order will only be placed if it reduces an existing position. - **post_only** (boolean) - If true, the order will only be placed if it does not immediately match with an existing order. ### Request Example ```json { "order": { "market_name": "ETH-USD", "amount_of_synthetic": "0.001", "price": "3000.0", "side": "BUY", "time_in_force": "GTT", "reduce_only": false, "post_only": true } } ``` ### Response #### Success Response (200) - **data** (object) - Contains details of the placed order. - **id** (string) - The unique identifier of the order. - **external_id** (string) - The external identifier of the order. #### Response Example ```json { "data": { "id": "order-id-789", "external_id": "external-order-id-101" } } ``` ``` -------------------------------- ### Onboard User Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md Handles the user onboarding process by generating L2 keys from an L1 Ethereum account and sending an onboarding payload to the exchange. Returns an OnBoardedAccount object upon success. ```python onboarded_account = user_client.onboard(referral_code="YOUR_REFERRAL_CODE") ``` -------------------------------- ### Get Available L1 Withdrawal Balance using Python SDK Source: https://github.com/x10xchange/python_sdk/blob/starknet/README.md The `available_l1_withdrawal_balance` method retrieves the available balance for Layer 1 (L1) withdrawals. It queries the underlying contract to fetch this balance and returns it as a `Decimal` value. ```python from decimal import Decimal def available_l1_withdrawal_balance() -> Decimal: # Implementation details to fetch withdrawal balance pass ``` -------------------------------- ### Initialize PerpetualTradingClient and Place Limit Order Source: https://context7.com/x10xchange/python_sdk/llms.txt Initializes the PerpetualTradingClient for REST API interactions and demonstrates placing a limit order using a convenience method. Requires an active StarkPerpetualAccount and closes the client upon completion. ```python import asyncio from decimal import Decimal from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.trading_client import PerpetualTradingClient from x10.perpetual.orders import OrderSide async def main(): stark_account = StarkPerpetualAccount( vault=123456, private_key="0x1234...", public_key="0xabcd...", api_key="your-api-key", ) trading_client = PerpetualTradingClient( endpoint_config=TESTNET_CONFIG, stark_account=stark_account, ) # Place a limit order using the convenience method placed_order = await trading_client.place_order( market_name="BTC-USD", amount_of_synthetic=Decimal("0.01"), price=Decimal("63000.0"), side=OrderSide.BUY, post_only=True, ) print(f"Order placed: ID={placed_order.data.id}, External ID={placed_order.data.external_id}") # Always close the client when done await trading_client.close() asyncio.run(main()) ``` -------------------------------- ### Configure StarkPerpetualAccount Source: https://context7.com/x10xchange/python_sdk/llms.txt Demonstrates how to create a StarkPerpetualAccount instance using API credentials obtained from the Extended Exchange API Management dashboard. Supports both testnet and mainnet configurations. ```python from x10.perpetual.accounts import StarkPerpetualAccount from x10.perpetual.configuration import TESTNET_CONFIG, MAINNET_CONFIG # Create account from API Management credentials stark_account = StarkPerpetualAccount( vault=123456, # Vault ID from API management private_key="0x1234567890abcdef...", # L2 private key (hex) public_key="0xabcdef1234567890...", # L2 public key (hex) api_key="your-api-key-here", # API key from API management ) # Use TESTNET_CONFIG for development, MAINNET_CONFIG for production # If previously onboarded on app.x10.exchange, use MAINNET_CONFIG_LEGACY_SIGNING_DOMAIN ``` -------------------------------- ### Manage OrderBook State with Callbacks in Python Source: https://context7.com/x10xchange/python_sdk/llms.txt Demonstrates how to use the OrderBook class for automatic order book state management. It includes setting up callbacks for best bid and ask changes, accessing current prices, calculating price impact for notional and quantity, and closing the order book. ```python import asyncio from decimal import Decimal from x10.perpetual.configuration import TESTNET_CONFIG from x10.perpetual.orderbook import OrderBook, OrderBookEntry async def use_orderbook(): # Callback for best bid changes async def on_best_bid_change(entry: OrderBookEntry | None): if entry: print(f"New best bid: {entry.price} ({entry.amount})") # Callback for best ask changes async def on_best_ask_change(entry: OrderBookEntry | None): if entry: print(f"New best ask: {entry.price} ({entry.amount})") # Create and start orderbook with callbacks orderbook = await OrderBook.create( endpoint_config=TESTNET_CONFIG, market_name="BTC-USD", best_bid_change_callback=on_best_bid_change, best_ask_change_callback=on_best_ask_change, depth=20, start=True, ) # Wait for orderbook to populate await asyncio.sleep(2) # Access best prices best_bid = orderbook.best_bid() best_ask = orderbook.best_ask() print(f"Current spread: {best_ask.price - best_bid.price if best_bid and best_ask else 'N/A'}") # Calculate price impact for notional impact = orderbook.calculate_price_impact_notional(Decimal("10000"), "BUY") if impact: print(f"$10k buy impact: Avg price={impact.price}, Amount={impact.amount}") # Calculate price impact for quantity impact = orderbook.calculate_price_impact_qty(Decimal("1.0"), "SELL") if impact: print(f"1 BTC sell impact: Avg price={impact.price}") # Stop orderbook when done await orderbook.close() asyncio.run(use_orderbook()) ```