Guía de la API de Backpack Exchange en Python
Prerequisitos
Obtén tus claves API si vas a usar endpoints de cuenta: https://backpack.exchange/portfolio/settings/api-keys
Instala las librerías de Python necesarias:
cryptography – para X-Signature (solo endpoints de cuenta)
requests – para realizar peticiones HTTP (o aiohttp si prefieres async)
pip3 install cryptography requests
Instala dotenv-python para gestionar de forma segura tus claves usando variables de entorno si vas a usar endpoints de cuenta
pip3 install python-dotenv
Crea un archivo .env y almacena tus claves así:
PUBLIC_KEY=zDIJj9qneWIY0IYZ5aXoHcNMCm+XDhVcTssiT0HyY0A=
SECRET_KEY=4odxgSUxFrC/zsKWZF4OQwYAgnNu9hnWH3NxWfLAPz4=
Crea un archivo .gitignore y añade .env para excluirlo del control de versiones.
.env
Para todos los ejemplos, usaremos la librería síncrona requests. Vamos a importarla:
import requests
Endpoints públicos
Para endpoints públicos, simplemente envía una petición GET.
No se requieren claves API.
Ejemplo: Accediendo a datos públicos
# https://docs.backpack.exchange/#tag/Markets/operation/get_open_interest
BASE_URL: str = "https://api.backpack.exchange/" # base api url for all endpoints
symbol: str = "SOL_USDC_PERP" # let's specify the symbol
result_url: str = f"{BASE_URL}api/v1/openInterest?symbol={symbol}" # add your argument as a query string. For GET requests you need only query string
from json import JSONDecodeError
response = requests.get(url=result_url) # make a get request
print(f"response status code: {response}")
if response.status_code == 200:
# make your code safe in case you receive unexpected data
try:
print(f"response json: {response.json()}")
open_interest: str = response.json()[0]["openInterest"]
print(f"open interest: {open_interest}")
except JSONDecodeError:
print(f"response text if response isn't json: {response.text}")
else:
...
Nota: Si tienes más de un argumento, únelos usando el símbolo &.
Endpoints privados
Para endpoints privados, necesitamos crear headers específicos y un cuerpo de petición (para peticiones POST). Esto requiere autenticación con tus claves API.
import base64 # for base64 encoding the signature
from time import time # for timestamp generation
import os # to access environment variables
from cryptography.hazmat.primitives.asymmetric import ed25519 # to create a private key for signing
# from dotenv import load_dotenv, find_dotenv # to load environment variables from .env file
# In production code, use this approach:
# load_dotenv(find_dotenv())
# public_key: str = os.getenv("PUBLIC_KEY")
# secret_key: str = os.getenv("SECRET_KEY")
# For demonstration purposes only - don't hardcode keys in production
public_key: str = "5+yQgwU0ZdJ/9s+GXfuPFfo7yQQpl9CgvQedJXne30o="
secret_key: str = "TDSkv44jf/iD/QCKkyCdixO+p1sfLXxk+PZH7mW/ams="
# Create private key from secret key
private_key = ed25519.Ed25519PrivateKey.from_private_bytes(
base64.b64decode(secret_key)
)
Ejemplo: Obteniendo una dirección de depósito
Veamos cómo obtener una dirección de depósito usando la API: https://docs.backpack.exchange/#tag/Capital/operation/get_deposit_address
# Generate timestamp and window parameters
timestamp = int(time() * 1e3) # Unix time in milliseconds
window: str = "5000" # Time window in milliseconds that the request is valid for
Ahora que tenemos nuestros componentes de autenticación listos (X-Timestamp
, X-Window
, and X-API-Key
), vamos a crear la firma.
# Define the instruction for this API call
instruction: str = "depositAddressQuery"
sign_str = f"instruction={instruction}"
# This endpoint requires the "blockchain" parameter
params: dict = {
"blockchain": "Solana",
}
# Generate a valid query string from parameters
sorted_params_list = []
for key, value in sorted(params.items()):
if isinstance(value, bool): # boolean variables should be lowercase in query strings
value = str(value).lower()
sorted_params_list.append(f"{key}={value}")
sorted_params = "&".join(sorted_params_list)
# Combine all parts of the signature string
if sorted_params:
sign_str += "&" + sorted_params
sign_str += f"×tamp={timestamp}&window={window}"
print(f"Signature string: {sign_str}")
Firmando la petición
Ahora vamos a firmar la petición con nuestra clave privada:
# Sign the string with our private key
signature_bytes = private_key.sign(sign_str.encode())
encoded_signature = base64.b64encode(signature_bytes).decode()
print(f"Base64 encoded signature: {encoded_signature}")
Creando headers
Crear los headers requeridos para la petición a la API:
# Prepare the headers with all required authentication parameters
headers = {
"X-API-Key": public_key,
"X-Signature": encoded_signature,
"X-Timestamp": str(timestamp),
"X-Window": window,
"Content-Type": "application/json; charset=utf-8",
}
Enviando la petición
Ahora podemos enviar la petición autenticada a la API:
# Send the GET request with our authentication headers
url = "https://api.backpack.exchange/wapi/v1/capital/deposit/address"
response = requests.get(url=url, headers=headers, params=params)
print(response.json())
Usando peticiones POST
Para peticiones POST
, necesitas incluir el cuerpo JSON y usar el método post()
en lugar de get()
.
Ejemplo: Ejecutando una orden
Veamos cómo enviar una orden al motor de matching para ejecución usando la API: https://api.backpack.exchange/api/v1/order
# Generate timestamp and window parameters
timestamp = int(time() * 1e3) # Unix time in milliseconds
window = "5000" # Time window in milliseconds that the request is valid for
# Define the instruction for this API call
instruction = "orderExecute"
sign_str = f"instruction={instruction}"
# Create the order request body
order_params = {
"symbol": "SOL_USDC", # Required: The market for the order
"side": "Bid", # Required: "Bid" (buy) or "Ask" (sell)
"orderType": "Limit", # Required: "Market" or "Limit"
"price": "170.50", # The order price (required for limit orders)
"quantity": "1.0", # The order quantity
"timeInForce": "GTC", # "GTC" (Good Till Cancelled), "IOC" (Immediate or Cancel), "FOK" (Fill or Kill)
"clientId": 123456, # Custom order ID (optional)
"selfTradePrevention": "RejectTaker" # Optional: "RejectTaker", "RejectMaker", "RejectBoth"
}
# Generate a valid query string from parameters
sorted_params_list = []
for key, value in sorted(order_params.items()):
if isinstance(value, bool): # boolean variables should be lowercase in query strings
value = str(value).lower()
sorted_params_list.append(f"{key}={value}")
sorted_params = "&".join(sorted_params_list)
# Combine all parts of the signature string
if sorted_params:
sign_str += "&" + sorted_params
sign_str += f"×tamp={timestamp}&window={window}"
print(f"Signature string: {sign_str}")
# Sign the string with our private key
signature_bytes = private_key.sign(sign_str.encode())
encoded_signature = base64.b64encode(signature_bytes).decode()
print(f"Base64 encoded signature: {encoded_signature}")
# Prepare the headers with all required authentication parameters
headers = {
"X-API-Key": public_key,
"X-Signature": encoded_signature,
"X-Timestamp": str(timestamp),
"X-Window": window,
"Content-Type": "application/json; charset=utf-8",
}
# Send the POST request with our authentication headers and order parameters
url = "https://api.backpack.exchange/api/v1/order"
response = requests.post(url=url, headers=headers, json=order_params)
print(f"Response status code: {response.status_code}")
try:
print(f"Response JSON: {response.json()}")
except JSONDecodeError:
print(f"Response text: {response.text}")
Fuentes
El SDK hace el proceso de desarrollo mucho más fácil.
SDK de ejemplo: https://github.com/sndmndss/bpx-py
Para más información, visita la documentación oficial: https://docs.backpack.exchange/
Last updated