This is an api with rest and websocket endpoints that supports a prototype application to execute and monitor a spread trading strategy involving perpetual futures contracts. The basic strategy is to establish a short position in the perpetual futures contract to enable capture of funding rate payments every eight hours. A corresponding long position in the underlying asset is established at the same time to avoid taking any directional risk.
This api provides data on wallet balances, realized profit and loss, open positions, historical prices and completed trades, including real time updates via websocket.
Create a virtual environment and install dependencies with
pipenv install
- This api is designed to work with the Binance.com API.
- It requires both a margin account and futures account on binance.com.
- Instructions on how to create an API key can be found here.
- The key and secret should appear in a .env file as
BINANCE_API_KEY=<your key>
BINANCE_API_SECRET=<your secret>
- The api requires USDT balances in both the margin and futures accounts
- It also requires a small balance of Binance Coin (BNB) in the margin account to cover transaction costs. This is to avoid having commissions deducted from the traded asset, which otherwise results in a slight mismatches in the value of the short and long positions and odd lot sizes, complicating trade execution and leaving small amounts of orphaned assets. Doing so also has the added benefit of reducing margin account commissions from 0.1% to 0.075%.
pipenv run uvicorn api.api:app --reload
OpenApi documentation of the REST endpoints is available at the /docs
endpoint.
The api is implemented using FastAPI with routes served asynchronously with asyncio. FastAPI also supports websocket endpoints via Starlette, which are used to stream real time updates to most application components. The api uses python-binance, which also has an asynchronous client to fetch data from the binance.com api. Some endpoints are close to being pass throughs of the python-binance (and in turn, binance.com api) endpoints, but in many cases additional coding was required to either link the individual futures and margin positions together or to combine data from multiple endpoints as required by application components.