> For the complete documentation index, see [llms.txt](https://support.backpack.exchange/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://support.backpack.exchange/support-docs/ru/birzha/api-i-dokumentaciya-dlya-razrabotchikov/rukovodstvo-po-api-backpack-exchange-python.md).

# Руководство по API Backpack Exchange Python

{% hint style="info" %}
Этот документ переведён с помощью машинного перевода и может содержать неточности. В случае расхождений руководствуйтесь [английской версией](https://support.backpack.exchange/).
{% endhint %}

### Предварительные требования

Получите ваши API ключи, если вы собираетесь использовать endpoints аккаунта: \
<https://backpack.exchange/settings/api-keys>

Установите необходимые библиотеки Python:

* cryptography — для X-Signature (только [endpoints аккаунта](https://docs.backpack.exchange/#tag/Account))
* requests — для выполнения HTTP запросов (или aiohttp, если вы предпочитаете async)

```
pip3 install cryptography requests 
```

Установите dotenv-python для безопасного управления вашими ключами с помощью переменных окружения, если вы собираетесь использовать [endpoints аккаунта](https://docs.backpack.exchange/#tag/Account)

```
pip3 install python-dotenv
```

Создайте файл .env и храните ваши ключи так:

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

Создайте файл .gitignore и добавьте .env, чтобы исключить его из контроля версий.

```
.env
```

Для всех примеров мы будем использовать синхронную библиотеку requests. Давайте импортируем её:

```
import requests
```

### Публичные endpoints <a href="#public-endpoints" id="public-endpoints"></a>

Для публичных endpoints просто отправьте GET запрос.

API ключи не требуются.

#### Пример: Доступ к публичным данным <a href="#example-accessing-public-data" id="example-accessing-public-data"></a>

```

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

\
**Примечание:** Если у вас более одного аргумента, объедините их, используя символ &.

### Приватные endpoints <a href="#private-endpoints" id="private-endpoints"></a>

Для приватных endpoints нам нужно создать специальные заголовки и тело запроса (для POST запросов). Это требует аутентификации с вашими 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)
        )
```

#### Пример: Получение адреса депозита <a href="#example-retrieving-a-deposit-address" id="example-retrieving-a-deposit-address"></a>

Давайте посмотрим, как получить адрес депозита, используя 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
```

Теперь, когда у нас готовы компоненты аутентификации (`X-Timestamp`, `X-Window` и `X-API-Key`), давайте создадим подпись.

```

# 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"&timestamp={timestamp}&window={window}" 

print(f"Signature string: {sign_str}")
```

#### Подписание запроса <a href="#signing-the-request" id="signing-the-request"></a>

Теперь давайте подпишем запрос нашим приватным ключом:

```

# 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}")
```

#### Создание заголовков <a href="#creating-headers" id="creating-headers"></a>

Создайте необходимые заголовки для 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",
}
```

#### Отправка запроса <a href="#sending-the-request" id="sending-the-request"></a>

Теперь мы можем отправить аутентифицированный запрос к 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())
```

### Использование POST запросов <a href="#using-post-requests" id="using-post-requests"></a>

Для `POST` запросов вам нужно включить тело JSON и использовать метод `post()` вместо `get()`.

#### Пример: Исполнение ордера <a href="#example-executing-an-order" id="example-executing-an-order"></a>

Давайте посмотрим, как отправить ордер в движок сопоставления для исполнения, используя 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"&timestamp={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}")
```

### Источники

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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://support.backpack.exchange/support-docs/ru/birzha/api-i-dokumentaciya-dlya-razrabotchikov/rukovodstvo-po-api-backpack-exchange-python.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
