# Python API 指南

### 前提条件

若要使用账户相关接口，请先获取您的 API 密钥：

<https://backpack.exchange/settings/api-keys><br>

安装所需的 Python 库：

* `cryptography`：用于生成 X-Signature（仅限[账户接口](https://docs.backpack.exchange/#tag/Account)）
* `requests`：用于发起 HTTP 请求（如果更偏好异步请求，也可以使用 `aiohttp`）

```
pip3 install cryptography requests 
```

如果您打算使用[账户接口](https://docs.backpack.exchange/#tag/Account)，建议安装 `dotenv-python`，以通过环境变量安全管理密钥。

```
pip3 install python-dotenv
```

创建 `.env` 文件，并按如下方式存储您的密钥：

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

创建 `.gitignore` 文件，并添加 `.env` 以排除其版本控制。

```
.env
```

本指南示例均使用同步方式的 `requests` 库。我们先导入它：

```
import requests
```

### 公共接口

对于公共接口，只需发送 `GET` 请求，无需提供 API 密钥。

#### 示例：访问公共数据

```
# https://docs.backpack.exchange/#tag/Markets/operation/get_open_interest
BASE_URL: str = "https://api.backpack.exchange/"  # 所有接口的基础 URL
symbol: str = "SOL_USDC_PERP"  # 指定交易对
result_url: str = f"{BASE_URL}api/v1/openInterest?symbol={symbol}"  # 使用查询字符串拼接参数
```

```
from json import JSONDecodeError

response = requests.get(url=result_url)  # 发起 GET 请求
print(f"响应状态码: {response}")
if response.status_code == 200:
    try:
        print(f"响应内容（JSON）: {response.json()}")
        open_interest: str = response.json()[0]["openInterest"]
        print(f"未平仓合约量: {open_interest}")
    except JSONDecodeError:
        print(f"响应文本（若非 JSON）: {response.text}")
else:
    ...
```

**注意：**&#x5982;果包含多个参数，请使用 `&` 符号拼接。

### 私有接口

对于私有接口，我们需要构造特定的请求头以及请求体（对于 POST 请求）。这些请求需要通过 API 密钥进行认证。

```
import base64  # 用于对签名进行 base64 编码
from time import time  # 用于生成时间戳
import os  # 用于访问环境变量

from cryptography.hazmat.primitives.asymmetric import ed25519  # 用于创建签名所需的私钥
# from dotenv import load_dotenv, find_dotenv  # 从 .env 文件加载环境变量
```

```
# 正式环境中应使用以下方式：
# load_dotenv(find_dotenv())
# public_key: str = os.getenv("PUBLIC_KEY")
# secret_key: str = os.getenv("SECRET_KEY")

# 以下仅用于演示，请勿在生产环境中硬编码密钥
public_key: str = "5+yQgwU0ZdJ/9s+GXfuPFfo7yQQpl9CgvQedJXne30o="
secret_key: str = "TDSkv44jf/iD/QCKkyCdixO+p1sfLXxk+PZH7mW/ams="

# 使用密钥字符串创建私钥对象
private_key = ed25519.Ed25519PrivateKey.from_private_bytes(
    base64.b64decode(secret_key)
)
```

#### 示例：获取存款地址

以下展示如何通过 API 获取充值地址：\
<https://docs.backpack.exchange/#tag/Capital/operation/get_deposit_address>

```
# 生成时间戳和有效时间窗口
timestamp = int(time() * 1e3)  # 毫秒时间戳
window: str = "5000"  # 请求的有效时间窗（毫秒）
```

现在我们准备好了认证组件：`X-Timestamp`、`X-Window` 和 `X-API-Key`，开始生成签名：

```
# 定义本次调用的指令
instruction: str = "depositAddressQuery"
sign_str = f"instruction={instruction}"

# 本接口需传入 "blockchain" 参数
params: dict = {
    "blockchain": "Solana",
}

# 将参数格式化为合法的查询字符串
sorted_params_list = []
for key, value in sorted(params.items()):
    if isinstance(value, bool):
        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(f"签名字符串: {sign_str}")
```

#### 请求签名

现在用我们的私钥签署请求：

```
# 使用私钥对签名字符串签名
signature_bytes = private_key.sign(sign_str.encode())
encoded_signature = base64.b64encode(signature_bytes).decode()
print(f"Base64 编码签名: {encoded_signature}")
```

#### 请求头创建

为API请求创建所需请求头：

```
# 构造带有身份验证参数的请求头
headers = {
    "X-API-Key": public_key,
    "X-Signature": encoded_signature,
    "X-Timestamp": str(timestamp),
    "X-Window": window,
    "Content-Type": "application/json; charset=utf-8",
}
```

#### 发起请求（GET/POST）

现在我们可以将经过身份验证的请求发送到API：

```
# 发起 GET 请求
url = "https://api.backpack.exchange/wapi/v1/capital/deposit/address"
response = requests.get(url=url, headers=headers, params=params)
print(response.json())
```

#### 使用post请求

对于`POST`请求，您需要包含JSON主体，并使用`post()`方法而不是`get()`。

#### 示例：执行订单

我们看看如何通过API提交订单到匹配引擎进行执行： <https://api.backpack.exchange/api/v1/order>

```
# 生成时间戳和时间窗
timestamp = int(time() * 1e3)
window = "5000"

# 定义调用指令
instruction = "orderExecute"
sign_str = f"instruction={instruction}"

# 构建订单参数
order_params = {
    "symbol": "SOL_USDC",             # 必填：交易对
    "side": "Bid",                    # 必填：买单 "Bid"，卖单 "Ask"
    "orderType": "Limit",            # 必填：市价 "Market" 或限价 "Limit"
    "price": "170.50",                # 限价单所需价格
    "quantity": "1.0",                # 下单数量
    "timeInForce": "GTC",            # 有效类型："GTC"、"IOC"、"FOK"
    "clientId": 123456,               # 自定义订单 ID（可选）
    "selfTradePrevention": "RejectTaker"  # 自成交保护（可选）
}

# 格式化参数为查询字符串
sorted_params_list = []
for key, value in sorted(order_params.items()):
    if isinstance(value, bool):
        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(f"签名字符串: {sign_str}")
```

```
# 对签名字符串签名
signature_bytes = private_key.sign(sign_str.encode())
encoded_signature = base64.b64encode(signature_bytes).decode()
print(f"Base64 编码签名: {encoded_signature}")
```

```
# 准备带认证信息的请求头
headers = {
    "X-API-Key": public_key,
    "X-Signature": encoded_signature,
    "X-Timestamp": str(timestamp),
    "X-Window": window,
    "Content-Type": "application/json; charset=utf-8",
}
```

```
# 发起 POST 请求，提交订单
url = "https://api.backpack.exchange/api/v1/order"
response = requests.post(url=url, headers=headers, json=order_params)
print(f"响应状态码: {response.status_code}")
try:
    print(f"响应 JSON: {response.json()}")
except JSONDecodeError:
    print(f"响应文本: {response.text}")
```

### 开发建议与参考链接

使用 SDK 可以大大简化开发流程。\
示例 SDK：<https://github.com/sndmndss/bpx-py>

更多信息，请查阅官方文档：\
<https://docs.backpack.exchange/>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://support.backpack.exchange/support-docs/cn/jiao-yi-suo/api-yu-kai-fa-zhe-wen-dang/python-api-zhi-nan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
