REST API Interaction
The REST API is an essential part of the 21X platform, providing a wide range of functionality to interact with trading pairs, order books, and user-specific data. The API is divided into two categories: public and authenticated endpoints.
Why Use the REST API?
Public Endpoints Public endpoints are accessible without authentication and are used to:
Fetch available trading pairs.
Retrieve order book data and price levels.
Access general ticker information for trading pairs.
Authenticated Endpoints Authenticated endpoints require user authentication and are designed for private, wallet-specific operations, such as:
Viewing orders placed by your wallet.
Fetching your order and trade history.
Retrieving order IDs (useful for canceling orders).
These endpoints complement the smart contract interactions by providing additional data and ensuring smooth integration for trading activities.
Client Configuration
The 21X SDK includes a REST API client for seamless interaction with the platform. The client supports both synchronous and asynchronous requests, enabling flexible integration into your applications.
Setting Up the Client
Public Endpoints Use the
Client
class to interact with public endpoints:from x21_sdk import Client client = Client(base_url="<insert the 21X API url here>")
Authenticated Endpoints For endpoints requiring authentication, use the
AuthenticatedClient
class and provide a valid token:from x21_sdk import AuthenticatedClient client = AuthenticatedClient( base_url="<insert the 21X API url here>", client_id="<insert the client id here>", client_secret="<insert the client secret here>", token_endpoint="<insert the oidc token endpoint here>", )
Alternatively, you can make use the following environment variables, to auto configure the clients.
export 21X_BASE_URL=<>
export 21X_AUTH_CLIENT_ID=<>
export 21X_AUTH_CLIENT_SECRET=<>
export 21X_AUTH_CLIENT_TOKEN_ENDPOINT=<>
from x21_sdk import Client, AuthenticatedClient
# Initialize either a client for the public endpoints
client = Client()
# Or a Client to use the authenticated endpoints
client = AuthenticatedClient()
Example Usage
Synchronous Example
Calling an endpoint and working with the response:
from x21_sdk.client.api.public_market_data import get_trading_pairs
# Fetch trading pairs
trading_pairs = get_trading_pairs.sync(client=client)
# Process response
for pair in trading_pairs.items:
print("orderbook_addr: " + pair.smart_contract_order_book)
print("base: " + pair.base_token_data.symbol)
print("quote: " + pair.quote_token_symbol)
Asynchronous Example
Using the async version of the client:
from x21_sdk.client.api.public_market_data import get_trading_pairs
async def fetch_trading_pairs():
async with client as client:
trading_pairs = await get_trading_pairs.asyncio(client=client)
for pair in trading_pairs.items:
print("orderbook_addr: " + pair.smart_contract_order_book)
print("base: " + pair.base_token_data.symbol)
print("quote: " + pair.quote_token_symbol)
# Run the async function
import asyncio
asyncio.run(fetch_trading_pairs())
Advanced Configuration
The client provides options to customize behavior based on your application's needs.
SSL Verification
For APIs using HTTPS, SSL verification ensures secure connections. You can specify a custom certificate bundle:
client = Client(
verify_ssl="/path/to/certificate_bundle.pem",
)
To disable SSL verification (not recommended), set verify_ssl=False
:
client = Client(
verify_ssl=False,
)
Customizing HTTPX
You can extend or replace the underlying httpx
client for advanced use cases:
from x21_sdk import Client
def log_request(request):
print(f"Request: {request.method} {request.url}")
def log_response(response):
print(f"Response: {response.status_code} {response.url}")
client = Client(
httpx_args={"event_hooks": {"request": [log_request], "response": [log_response]}},
)
For even greater control, set a custom httpx.Client
instance directly:
import httpx
from x21_sdk import Client
client = Client()
client.set_httpx_client(httpx.Client(base_url="https://api.21x.com", proxies="http://localhost:8030"))
Public Endpoints
getTradingPairs
getTradingPairs
Fetches a list of all available trading pairs on the platform.
Parameters
None
Example Usage
from x21_sdk.client.api.public_market_data import get_trading_pairs
trading_pairs = get_trading_pairs(client=client)
for pair in trading_pairs.items:
print(pair)
Refer to the API Documentation for detailed request/response structure.
getTradeInfo
getTradeInfo
Retrieves trade information for a trading pair
Parameters
id
(str): The identifier of the trading pair.
Example Usage
from x21_sdk.client.api.public_market_data import get_trade_info
id = "06162bc3-9765-4673-a874-9b8a21e97e27"
trade_info = get_trade_info(id, client=client)
print(trade_info)
Refer to the API Documentation for detailed request/response structure.
getOrderBookTopOrders
getOrderBookTopOrders
Retrieves the top orders from the order book for a specified trading pair.
Parameters
id
(str): The identifier of the trading pair.kind
(Union[Unset, OrderKindEnum], optional): The type of orders to retrieve (e.g., buy or sell).max_
(Union[Unset, int], optional): The maximum number of orders to return.
Example Usage
from x21_sdk.client.api.public_market_data import get_order_book_top_orders
from x21_sdk.client.models import OrderKindEnum
pair_id = "0xBaseTokenAddress-0xQuoteTokenAddress"
kind = OrderKindEnum.BUY
max_orders = 10
top_orders = get_order_book_top_orders.sync(
client=client,
id=pair_id,
kind=kind,
max_=max_orders
)
for order in top_orders.buy:
print(order)
Notes
The
kind
parameter can be used to filter results by order type (e.g., only buy or sell orders).If
max_
is not provided, the endpoint will return a default number of top orders.
Refer to the API Documentation for detailed request/response structure.
getOrderBookPriceLevels
getOrderBookPriceLevels
Fetches the price levels from the order book for a specified trading pair.
Parameters
id
(str): The identifier of the trading pair.kind
(Union[Unset, OrderKindEnum], optional): The type of price levels to retrieve (e.g., buy or sell).max_
(Union[Unset, int], optional): The maximum number of price levels to return.
Example Usage
from x21_sdk.client.api.public_market_data import get_order_book_price_levels
from x21_sdk.client.models import OrderKindEnum
pair_id = "0xBaseTokenAddress-0xQuoteTokenAddress"
kind = OrderKindEnum.SELL
max_levels = 5
price_levels = get_order_book_price_levels.sync(
client=client,
id=pair_id,
kind=kind,
max_=max_levels
)
for level in price_levels.sell:
print(level)
Notes
The
kind
parameter allows filtering price levels by type (e.g., only buy or sell price levels).If
max_
is omitted, the endpoint defaults to returning a predefined number of price levels.
Refer to the API Documentation for detailed request/response structure.
getPostTradeTransparency
getPostTradeTransparency
Retrieves regulatory post-trade transparency data for the entire exchange. By default, it shows the most recent trades first. You can limit the results to a specific trading pair by providing its ID.
Parameters
query
(Union[Unset, GetPostTradeTransparencyQuery], optional): Query parameters to filter the data, such as trading pair ID.cursor
(Union[Unset, str], optional): A pagination cursor to navigate through the dataset.limit
(Union[Unset, int], optional): The maximum number of trades to retrieve.count
(Union[Unset, bool], optional): IfTrue
, includes a count of total available trades in the response.
Example Usage
from x21_sdk.client.api.public_market_data import get_post_trade_transparency
# Example query to limit data to a specific trading pair
query = {"tradingpair": "06162bc3-9765-4673-a874-9b8a21e97e27"}
limit = 10
cursor = None # Omit or use a valid cursor for paginated requests
transparency_data = get_post_trade_transparency.sync(
client=client,
query=query,
cursor=cursor,
limit=limit,
count=True
)
for trade in transparency_data.items:
print(trade)
Notes
Providing a
trading_pair_id
in the query restricts the results to trades involving that pair.Use the
cursor
for paginated requests, especially when dealing with large datasets.The
count
parameter helps determine the total number of trades available without fetching all results.
Refer to the API Documentation for detailed request/response structure.
Authenticated Endpoints
getWalletOrders
getWalletOrders
Description
This authenticated endpoint fetches all orders associated with the specified wallet. By default, it returns open orders. You can filter the results to a specific trading pair or include completed, canceled, and rejected orders by adjusting the parameters.
Parameters
wallet_address
(str, required): The wallet address to fetch orders for.query
(Union[Unset, GetWalletOrdersQuery], optional): Filters for the request, such as trading pair ID or status.cursor
(Union[Unset, str], optional): A pagination cursor to navigate through the dataset.limit
(Union[Unset, int], optional): The maximum number of orders to retrieve.count
(Union[Unset, bool], optional): IfTrue
, includes a count of total available orders in the response.
Example Usage
from x21_sdk.client.api.order import get_wallet_orders
# Example query to restrict data to a specific trading pair
query = {"trading_pair": "06162bc3-9765-4673-a874-9b8a21e97e27", "only_open": True}
limit = 10
cursor = None # Omit or use a valid cursor for paginated requests
wallet_orders = get_wallet_orders.sync(
client=client,
wallet_address="0xYourWalletAddress",
query=query,
cursor=cursor,
limit=limit,
count=True
)
for order in wallet_orders.items:
print(order)
Notes
Set
only_open
toFalse
in the query to fetch completed, canceled, and rejected orders instead of open ones.Use the
cursor
parameter for paginated requests when dealing with a large number of orders.The
count
parameter is helpful for understanding the size of the dataset without fetching all results.
Refer to the OpenAPI Documentation for detailed request/response structures.
getWalletTrades
getWalletTrades
Description
This authenticated endpoint retrieves all completed trades involving the specified wallet. You can optionally restrict the results to a specific trading pair.
Parameters
wallet_address
(str, required): The wallet address to fetch trades for.query
(Union[Unset, GetWalletTradesQuery], optional): Filters for the request, such as trading pair ID or trade time range.cursor
(Union[Unset, str], optional): A pagination cursor to navigate through the dataset.limit
(Union[Unset, int], optional): The maximum number of trades to retrieve.count
(Union[Unset, bool], optional): IfTrue
, includes a count of total available trades in the response.
Example Usage
from x21_sdk.client.api.trade import get_wallet_trades
# Example query to fetch trades for a specific trading pair
query = {"trading_pair": "06162bc3-9765-4673-a874-9b8a21e97e27"}
limit = 20
cursor = None # Use a valid cursor for paginated requests if applicable
wallet_trades = get_wallet_trades.sync(
client=client,
wallet_address="0xYourWalletAddress",
query=query,
cursor=cursor,
limit=limit,
count=True
)
for trade in wallet_trades.items:
print(trade)
Notes
Use the
trading_pair
parameter in the query to restrict results to a specific pair.The
cursor
parameter allows for paginated navigation, which is helpful for wallets with a high trade volume.Setting the
count
parameter toTrue
provides a total count of trades without retrieving the entire dataset.
Refer to the OpenAPI Documentation for more details on request/response formats.
Last updated