> For the complete documentation index, see [llms.txt](https://docs.outpoll.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.outpoll.com/api/futures-api/python-examples/futures-examples/setup-and-helpers.md).

# Setup & Helpers

Python environment setup and shared helpers for the futures examples.

Use this page before running any futures script in this section.

## Requirements

Use Python `3.10+`.

Install the required packages first.

{% code title="install.sh" %}

```bash
pip install requests websockets
```

{% endcode %}

{% hint style="warning" %}
Replace the placeholder API key and secret in every script before running it. The scripts place real orders: start with small amounts.
{% endhint %}

## What the Helpers Cover

* `FuturesClient` — signed REST requests to `https://futures-trading-service.outpoll.com`. The signature covers `timestamp + METHOD + path + body`; the query string is never signed.
* Numbers are read as `Decimal` and sent as strings (`"0.017"`), so prices and sizes stay exact. Never use floats for prices, sizes or money.
* Errors raise `FuturesApiError`; `code` is the stable `FUT-NNNN` code from the [error body](broken://pages/5af105514c769e54cdcc5c7c16de2848aa3aa267#errors).
* `get_pairs()` — the public pair catalogue by symbol: pair ID `gid`, tick size `ts`, lot size `ls`, leverage range, status.
* `floor_to_step()` / `round_price()` — fit a size to the lot size and a price to the tick size. Request numbers accept at most 8 decimal places.
* `connect_private()` — opens `/ws/account` or `/ws/margin-call` and sends the signed `AUTH` frame. See [Futures Account → Authentication](broken://pages/faa2c076dfe2f95047048724a161c66cc460d6ec#authentication).
* `mark_price()` / `best_quote()` — current mark price and best bid/ask of one pair from the public market data streams.

Save the file as `futures_helpers.py` next to the scripts.

{% code title="futures\_helpers.py" %}

```python
"""Shared helpers for the Outpoll futures Python examples."""
import asyncio
import base64
import hashlib
import hmac
import json
import time
from decimal import Decimal, ROUND_DOWN

import requests
import websockets

TRADING_HOST = "https://futures-trading-service.outpoll.com"
TRADING_WS = "wss://futures-trading-service.outpoll.com"
MARKET_DATA_WS = "wss://futures-marketdata-service.outpoll.com"


def sign(api_secret: str, message: str) -> str:
    """Base64URL (no padding) of HMAC-SHA256 keyed by the Base64URL-decoded secret."""
    key = base64.urlsafe_b64decode(api_secret + "=" * (-len(api_secret) % 4))
    digest = hmac.new(key, message.encode(), hashlib.sha256).digest()
    return base64.urlsafe_b64encode(digest).decode().rstrip("=")


def _decimal_str(value):
    if isinstance(value, Decimal):
        return format(value, "f")  # plain notation, never "1E-7"
    raise TypeError(f"not JSON serializable: {value!r}")


class FuturesApiError(Exception):
    """A non-2xx answer. `code` is the stable FUT-NNNN code when the API sent one."""

    def __init__(self, status: int, body):
        self.status = status
        self.body = body
        self.code = body.get("e") if isinstance(body, dict) else None
        message = body.get("message") if isinstance(body, dict) else body
        super().__init__(f"HTTP {status} {self.code or ''} {message}".strip())


class FuturesClient:
    """Signed REST client for https://futures-trading-service.outpoll.com."""

    def __init__(self, api_key: str, api_secret: str, host: str = TRADING_HOST):
        self.api_key = api_key
        self.api_secret = api_secret
        self.host = host
        self.http = requests.Session()

    def request(self, method: str, path: str, params: dict = None, body=None):
        # Decimals are sent as strings ("0.017"): exact, and accepted for every number field.
        raw = "" if body is None else json.dumps(body, default=_decimal_str, separators=(",", ":"))
        ts = str(int(time.time()))
        headers = {
            "OUTPOLL-API-KEY": self.api_key,
            "OUTPOLL-API-TIMESTAMP": ts,
            # Sign the path only, never the query string.
            "OUTPOLL-API-SIGNATURE": sign(self.api_secret, ts + method + path + raw),
        }
        if body is not None:
            headers["Content-Type"] = "application/json"
        resp = self.http.request(method, self.host + path, params=params,
                                 data=raw.encode() if raw else None, headers=headers, timeout=10)
        if not resp.content:
            if resp.status_code >= 400:
                raise FuturesApiError(resp.status_code, None)
            return None
        try:
            payload = resp.json(parse_float=Decimal)
        except ValueError:
            payload = resp.text
        if resp.status_code >= 400:
            raise FuturesApiError(resp.status_code, payload)
        return payload

    def get(self, path, params=None):
        return self.request("GET", path, params=params)

    def post(self, path, body=None):
        return self.request("POST", path, body=body if body is not None else {})

    def patch(self, path, body):
        return self.request("PATCH", path, body=body)

    def delete(self, path, body=None):
        return self.request("DELETE", path, body=body)

# ─── Pairs and rounding ─────────────────────────────────────────────────

def get_pairs() -> dict:
    """Public pair catalogue keyed by symbol, e.g. pairs["BTCUSDT"]["gid"]. No API key needed."""
    resp = requests.get(TRADING_HOST + "/api/v1/trade/pairs", timeout=10)
    resp.raise_for_status()
    return {p["nm"]: p for p in resp.json(parse_float=Decimal)["ps"]}


def floor_to_step(value: Decimal, step: Decimal) -> Decimal:
    """Round down to a multiple of the lot size `ls` (or tick size `ts`)."""
    return (value / step).to_integral_value(rounding=ROUND_DOWN) * step


def round_price(value: Decimal, tick: Decimal) -> Decimal:
    """Nearest multiple of the tick size `ts`."""
    return (value / tick).quantize(Decimal(1)) * tick

# ─── WebSocket ──────────────────────────────────────────────────────────

def ws_auth_frame(api_key: str, api_secret: str, path: str) -> str:
    """AUTH frame for a private stream; `path` is the stream path, e.g. "/ws/account"."""
    ts = str(int(time.time()))
    return json.dumps({"t": "AUTH", "d": {"key": api_key, "ts": ts,
                                         "sig": sign(api_secret, ts + "GET" + path)}})


async def connect_private(api_key: str, api_secret: str, path: str):
    """Open a private stream (/ws/account, /ws/margin-call) and authenticate.

    A failed AUTH closes the socket with code 1008, which raises ConnectionClosed here.
    """
    ws = await websockets.connect(TRADING_WS + path)
    await ws.send(ws_auth_frame(api_key, api_secret, path))
    ack = json.loads(await asyncio.wait_for(ws.recv(), timeout=10))
    if ack.get("t") != "AUTH" or not ack.get("d", {}).get("ok"):
        await ws.close()
        raise RuntimeError(f"unexpected AUTH answer: {ack}")
    return ws


async def keepalive(ws, every: int = 20):
    """Send the plain-text `ping` the futures streams expect."""
    while True:
        await asyncio.sleep(every)
        await ws.send("ping")


async def first_frame(path: str, pair_id: int) -> dict:
    """Subscribe one pair on a public market-data stream and return its first data frame."""
    async with websockets.connect(MARKET_DATA_WS + path) as ws:
        await ws.send(json.dumps({"act": "subscribe", "pi": pair_id}))
        while True:
            raw = await asyncio.wait_for(ws.recv(), timeout=10)
            if raw == "pong":
                continue
            msg = json.loads(raw, parse_float=Decimal)
            if "er" in msg:
                raise RuntimeError(f"{msg['er']}: {msg['msg']}")
            return msg


async def mark_price(pair_id: int) -> Decimal:
    return (await first_frame("/ws/mark-price", pair_id))["mp"]


async def best_quote(pair_id: int) -> tuple:
    """(best bid, best ask) prices."""
    msg = await first_frame("/ws/book/best", pair_id)
    return msg["b"][0], msg["a"][0]
```

{% endcode %}

{% hint style="info" %}
Every REST call and every `AUTH` counts against your API key's [rate limits](broken://pages/17081ff6556bc030aad99768726350d198881933#do-i-have-any-rate-limits). Exceeding them repeatedly blocks the key permanently. Load state once over REST and follow the streams instead of polling.
{% endhint %}

## Related Pages

* [Futures API](broken://pages/5af105514c769e54cdcc5c7c16de2848aa3aa267)
* [Market](broken://pages/bba14d4639c3c29cf6fdbadc86ec5d4dfeea3b07)
* [Futures Market Data](broken://pages/03869a2c7095ebee30a177ae823d7a4420086e38)
* [Futures Account streams](broken://pages/faa2c076dfe2f95047048724a161c66cc460d6ec)


---

# 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://docs.outpoll.com/api/futures-api/python-examples/futures-examples/setup-and-helpers.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.
