LogoLogo
XπŸ‘ΎπŸ’‘πŸŽ’
Support Docs
  • Support Docs
  • Technical Docs
  • API Docs
Support Docs
  • Start Here
    • Downloads
  • Exchange
    • Account Functions
      • Change Email
      • Take Profit & Stop Loss Orders (TP/SL)
      • Export trading history (CSV)
      • Order types and executions
      • Generate API keys for Backpack Exchange
    • Identity Verification
      • KYC Identity Verification is pending
      • How To Verify Account Identity
        • Create a new account
        • Verify Identity (KYC)
      • Supported Regions
    • Deposits and Withdrawals
      • Crypto
        • How to Deposit
        • How to Withdraw
        • Deposit & Withdrawal Issues
        • Withdrawal Fees
      • Fiat
        • How to Deposit via Wire
        • How to Withdraw via Wire
        • FAQs
          • Deposit
          • Withdraw
        • Bank Guides
          • ZA Bank
            • How to Withdraw via Wire β€” ZA Bank
    • Login and Security
      • Account Identity Requirements
      • Reset Password
      • OTP Passcode
      • Reset 2FA
      • I suspect unauthorized access to my account
      • Troubleshoot connectivity issues
    • Product FAQs
      • Spot Trading FAQs
      • Lend/Borrow FAQs
    • Programs
      • Points
      • Referrals
      • Affiliate Program
        • Flexible Commission Sharing
      • VIP
      • Market Maker Program
      • Token Listing Application
      • Bug Bounty Program
    • Trading Fees
    • API & Developer Docs
      • API Clients
      • Backpack Exchange Python API guide
  • Wallet
    • What is Backpack Wallet?
    • Get Started
      • Supported Browsers and Platforms
      • Import/Recover Wallet
    • Actions
      • Swap Tokens
      • How to Buy and Sell Crypto with MoonPay
        • Buy Crypto in Backpack Wallet with MoonPay
        • Sell Crypto in Backpack Wallet with MoonPay
      • Refer, Swap & Earn
      • Stake SOL
      • SOL/ETH Bridge
      • Secure NFTs
      • Add Networks
      • Connect Hardware Wallet
      • Multisig
      • Custom RPC Addresses
      • Add Developer Testnets
      • Collaboration Application Form
    • Troubleshoot
      • Hide Spam NFTs
      • Hide Tokens
      • Wallet Not Loading
      • View Secret Recovery Phrases and Private Keys
    • Technical Docs
      • Deeplinks
        • Provider Methods
          • Connect
          • Disconnect
          • SignAndSendTransaction
          • SignAllTransactions
          • SignTransaction
          • SignMessage
        • Other Methods
          • Browse
        • Handling Sessions
        • Specifying Redirects
        • Encryption
        • Limitations
  • Report Issue or Bug
    • Exchange
    • Wallet
  • 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
  • Public endpoints
  • Private endpoints
  • Note:
  • SDK
Export as PDF
  1. Exchange
  2. API & Developer Docs

Backpack Exchange Python API guide

PreviousAPI ClientsNextWallet

Last updated 21 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)

pip3 install cryptography requests 

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

pip3 install python-dotenv

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

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

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

.env

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

import requests

Public endpoints

For public endpoints, simply send a GET request.

No API keys are required.

Example

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

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

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

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)
instruction=depositAddressQuery&blockchain=Solana&timestamp=1743731167786&window=5000

Now let's sign it!

signature_bytes = private_key.sign(sign_str.encode())
encoded_signature = base64.b64encode(signature_bytes).decode()
print(f"signed query string: {encoded_signature}")
signed query string: lLc/zjqju853/hmCdb9dXtMhUijoetARooBn56hqbxPNXZTV9Gy18YcBjZ8+HuPDJHz6LmeB/366bJ5uTCZSAA==

Create headers:

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:

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

Note:

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

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