LogoLogo
X👾💡🎒
Documentación de Soporte
  • Support Docs
  • Technical Docs
  • API Docs
Documentación de Soporte
  • Comienza Aquí
    • Descargas
  • Exchange
    • Account Functions
      • Cambio de Correo Electrónico
      • Órdenes de Take Profit y Stop Loss (TP/SL)
      • Exportar Historial de Trading(CSV)
      • Tipos de Órdenes y Ejecuciones
      • Generar Claves API para Backpack Exchange
    • Verificación de Identidad
      • Verificación de Identidad KYC Pendiente
      • Cómo Verificar la Identidad de la Cuenta
        • Crear una Nueva Cuenta
        • Verificar Identidad (KYC)
      • Regiones Soportadas
    • Depósitos y Retiros
      • Incidencias en Depósitos y Retiros
      • Cómo Depositar
      • Cómo Retirar
      • Comisiones de Retiro
    • Inicio de Sesión y Seguridad
      • Requisitos de Identidad de la Cuenta
      • Restablecer Contraseña
      • Código OTP (One Time Pass)
      • Restablecer 2FA
      • Sospecho de un Acceso No Autorizado a Mi Cuenta
      • Solucionar problemas de conectividad
    • Preguntas Frecuentes sobre los Productos
      • Spot Trading FAQs
      • Lend/Borrow FAQs
    • Programs
      • Puntos
      • Referidos
      • Programa de Afiliados
        • Compartir comisiones de forma flexible
      • VIP
      • Programa Market Maker
      • Aplicación para el Listado de un Token
      • Programa de Recompensas por Errores (Bug Bounty)
    • Comisiones de Trading
    • API & Developer Docs
      • Clientes de API
      • Guía de la API de Backpack Exchange en Python
  • Wallet
    • ¿Qué es Backpack Wallet?
    • Comenzar ahora
      • Navegadores y Plataformas Soportados
      • Importar/Recuperar Billetera
    • Acciones
      • Intercambiar Tokens
      • Referir, Intercambiar y Ganar
      • Stake SOL
      • SOL/ETH Bridge
      • Asegurar NFTs
      • Agregar Redes
      • Conectar una Billetera de Hardware
      • Multi Firma
      • Direcciones RPC Personalizadas
      • Añadir Testnets de Desarrollo
      • Formulario de Solicitud de Colaboración
    • Solución de problemas
      • Ocultar NFTs Spam
      • Ocultar Tokens
      • Problemas al Cargar la Wallet
      • Ver frases secretas de recuperación y claves privadas
    • Documentación Técnica
      • Deeplinks
        • Provider Methods
          • Connect
          • Disconnect
          • SignAndSendTransaction
          • SignAllTransactions
          • SignTransaction
          • SignMessage
        • Other Methods
          • Browse
        • Handling Sessions
        • Specifying Redirects
        • Encryption
        • Limitations
  • Reportar un Problema o Error
    • Exchange
    • Billetera
  • Legal
    • General Legal
      • User Agreement
      • Privacy Policy
      • Cookie Policy
    • VARA Disclosures
      • Virtual Asset Standards
      • VARA License Information
      • Risk Disclosures
      • Price Quotes
      • Exchange Trading Rules
      • Complaints
      • Available Digital Assets
    • UK Crypto Regulations & Risk Disclosure
    • Backpack Wallet
      • Terms and Conditions
      • Privacy Notice
Powered by GitBook

@ 2025 Backpack Exchange

On this page
Export as PDF
  1. Exchange
  2. API & Developer Docs

Guía de la API de Backpack Exchange en Python

PreviousClientes de APINextWallet

Last updated 4 days ago

Get your API keys if you are going to use account endpoints:

Install the required Python libraries:

  • cryptography – for X-Signature ( only)

  • requests – for making HTTP requests (or aiohttp if you prefer async)

Copy

pip3 install cryptography requests 

Install dotenv-python to securely manage your keys using environment variables if you are going to use

Copy

pip3 install python-dotenv

Create a .env file and store your keys like this:

Copy

PUBLIC_KEY=zDIJj9qneWIY0IYZ5aXoHcNMCm+XDhVcTssiT0HyY0A=
SECRET_KEY=4odxgSUxFrC/zsKWZF4OQwYAgnNu9hnWH3NxWfLAPz4=

Create a .gitignore file and add .env to exclude it from version control.

Copy

.env

For all examples, we will use the synchronous requests library. Let's import it:

Copy

import requests

Public endpoints

For public endpoints, simply send a GET request.

No API keys are required.

Example

Copy

# 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

Copy

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:
    ...

Copy

response status code: <Response [200]>
response json: [{'openInterest': '81420.17', 'symbol': 'SOL_USDC_PERP', 'timestamp': 1743731167028}]
open interest: 81420.17

If you have more than one argument, join them using the & symbol.

Private endpoints

For private endpoints we need to create spesific headers and a request body (for POST requests)

Copy

import base64 # import base64 as "The signature should then be base64 encoded"
from time import time # import time for timestamp 
import os  # import os – to access environment variables

from cryptography.hazmat.primitives.asymmetric import ed25519 # import ed25519 to create a private key that will sign the message
# from dotenv import load_dotenv, find_dotenv # to create env variables from your .env file

Copy

# use this in your code
# load_dotenv(find_dotenv())
# public_key: str = os.getenv("PUBLIC_KEY")
# secret_key: str = os.getenv("SECRET_KEY")

public_key: str = "zDIJj9qneWIY0IYZ5aXoHcNMCm+XDhVcTssiT0HyY0A="  # unsafe!
secret_key: str = "4odxgSUxFrC/zsKWZF4OQwYAgnNu9hnWH3NxWfLAPz4="  # unsafe!

private_key = ed25519.Ed25519PrivateKey.from_private_bytes(
            base64.b64decode(secret_key)
        )

Let’s retrieve the deposit address.

Copy

timestamp = int(time() * 1e3)  # Unix time in milliseconds
window: str = "5000" # Time window in milliseconds that the request is valid for. Increase if you have bad connection.

Now that X-Timestamp (timestamp), X-Window (window) and X-API-Key (public_key) are ready. Let's create X-Signature

Copy

instruction: str = "depositAddressQuery"
sign_str = f"instruction={instruction}"

# This endpoint requires the "blockchain" parameter
params: dict = {
    "blockchain": "Solana",
}
# Generic code to generate a valid query string from any 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)


if sorted_params:
    sign_str += "&" + sorted_params
sign_str += f"&timestamp={timestamp}&window={window}" 

print(sign_str)

Copy

instruction=depositAddressQuery&blockchain=Solana&timestamp=1743731167786&window=5000

Now let's sign it!

Copy

signature_bytes = private_key.sign(sign_str.encode())
encoded_signature = base64.b64encode(signature_bytes).decode()
print(f"signed query string: {encoded_signature}")

Copy

signed query string: lLc/zjqju853/hmCdb9dXtMhUijoetARooBn56hqbxPNXZTV9Gy18YcBjZ8+HuPDJHz6LmeB/366bJ5uTCZSAA==

Create headers:

Copy

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 request:

Copy

url = "https://api.backpack.exchange/wapi/v1/capital/deposit/address"
response = requests.get(url=url, headers=headers, params=params)
print(response.json())

Copy

{'address': '8PzpK8s8ezuSnXPjdPxR2FdZfzm5urkcUePrDL419PRC'}

Note:

For POST requests, include the JSON body and use the post() method.

Copy

url_example = "https://api.backpack.exchange/wapi/v1/example"
response = requests.post(url=url, headers=headers, json=params)

SDK

SDK makes the development process much easier!

Example:

https://backpack.exchange/portfolio/settings/api-keys
account endpoints
account endpoints
https://docs.backpack.exchange/#tag/Capital/operation/get_deposit_address
https://github.com/sndmndss/bpx-py
PreviousAPI Clients
Next