huobi_futures_python HFT Framework

repository·master·Indexed 42 days ago

https://github.com/hbdmapi/huobi_futures_python

An asynchronous, event-driven high-frequency trading (HFT) system for market makers and liquidity providers. It provides deep integration with Huobi Swap, Future, and Option products via WebSocket and RESTful APIs, featuring modules for market data, asset/position tracking, risk control with DingTalk alarms, and asynchronous MongoDB support. Includes a Delta-neutral hedging strategy for Huobi Options.

Tokens
3.8K
Snippets
16
Records
23
Agent score
54%

What's inside huobi_futures_python

  1. Understand the structure of the examples folder

    master

    The examples directory contains demonstration code for three different Huobi contract types:

    1. Huobi Futures (交割合约)
    2. Huobi Perpetual (永续合约)
    3. Huobi Options (期权合约)

    Each example consists of two primary files:

    • config.json: Contains typical configuration settings for the contracts, such as symbol configurations.
    • strategy.py: Demonstrates a complete trading lifecycle, including subscribing to market data (quotes), subscribing to order pushes, position pushes, account pushes, and executing RESTful API calls for order cancellation.
  2. Overview of the Huobi Futures Quant Framework modules

    master

    The framework is an asynchronous event-driven system composed of several specialized modules:

    • Market Module: Subscribes to orderbook, kline, and tradedetail via WebSocket; provides callbacks to strategies. Supports Perpetual, Delivery, and Options contracts.
    • RESTAPI Module: Implements Huobi contract REST API methods for strategy use.
    • Asset Module: Uses WebSocket to subscribe to account for real-time asset updates via callbacks.
    • Position Module: Uses WebSocket to subscribe to position for real-time position updates via callbacks.
    • Order Module: Uses WebSocket to subscribe to order for real-time order updates via callbacks.
    • Logging Module: Records logs to files based on error levels.
    • Order Execution Module: Provides integrated interfaces for common order placement functions.
    • Error Handling Module: Manages WebSocket reconnection and heartbeat mechanisms.
    • Risk Control Module: Supports alerts via DingTalk and SMS.
    • Database Module: Supports asynchronous calls to MongoDB.
  3. Configure and use MongoDB

    master

    To use MongoDB, add a MONGODB object to your config.json. You can then use alpha.utils.mongo to perform database operations asynchronously.

    "MONGODB": {
        "host": "127.0.0.1",
        "port": 27017,
        "username": "root",
        "password": "root"
    }
    from alpha.utils import mongo
    
    # Example: Updating a kline document
    await mongo.MongoDBBase('quant', 'kline').find_one_and_update(
        {'platform': kline.platform, 'symbol': kline.symbol, 'timestamp': kline.timestamp, 'kline_type': kline.kline_type},
        {'$set': {'open': kline.open, 'high': kline.high, 'close': kline.close, 'low': kline.low, 'volume': kline.volume, 'amount': kline.amount}},
        upsert=True, 
        return_document=True
    )
  4. Understand the Huobi Option Market Making Strategy

    master

    This strategy is a simplified option market-making implementation. It operates by placing buy and sell orders based on the mark_price plus a defined spread. The strategy periodically cancels and replaces orders based on the latest mark price.

    To manage risk, the strategy monitors the total portfolio Delta. If the absolute total Delta exceeds a specified threshold, the strategy automatically hedges the position using Huobi perpetual contracts to bring the total Delta back toward zero.

  5. System Architecture Overview

    master

    The system is an asynchronous, event-driven HFT framework composed of several specialized modules:

    • Market Module: Subscribes to real-time Orderbook, kline, and market trade details via websocket for strategy callbacks. Supports Huobi Swap, Future, and Option.
    • RestFul API Module: Integrated APIs for trading (trade, batch trade, cancel, etc.) across Swap, Future, and Option.
    • Asset Module: WebSocket subscription for asset updates.
    • Position Module: WebSocket subscription for position updates.
    • Order Module: WebSocket subscription for order updates.
    • Logging Module: Supports log levels: DEBUG, INFO, WARN, ERROR.
    • Trading Module: Provides common trade and cancel interfaces.
    • ErrorHandle Module: Handles websocket automatic reconnection and heartbeat mechanisms.
    • RiskControl Module: Includes DingDing message alarms.
    • Database Module: Provides an asynchronous interface for MongoDB.
  6. How Delta Hedging is Calculated

    master

    The strategy maintains a Delta-neutral position using the following logic:

    1. Option Delta ($D_o$): Calculated as the sum of the position Delta ($D_p$) and the option account equity in BTC ($M_o$). $D_o = D_p + M_o$

    2. Perpetual Contract Delta ($D_s$): Calculated using account equity ($M_s$), long position size in BTC ($L_s$), short position size in BTC ($S_s$), and current price ($P_s$). $D_s = M_s + \frac{L_s \cdot 100}{P_s} - \frac{S_s \cdot 100}{P_s}$

    3. Total Delta ($D$): The sum of option and perpetual deltas. $D = D_o + D_s$

    4. Hedging Execution: If $|D| \ge \text{threshold}$:

      • If $D \ge 0$: Sell short $\text{int}(D \cdot P_s / 100)$ contracts in perpetuals.
      • If $D < 0$: Buy long $\text{int}(|D| \cdot P_s / 100)$ contracts in perpetuals.
  7. Quickstart with Demo examples

    master

    To run the provided demonstration strategies, follow these steps:

    1. Clone the repository.
    2. Navigate to the directory.
    3. Configure your Huobi API credentials in Example/config.json:
      • Set access_key to your Huobi API access key.
      • Set secret_key to your Huobi API secret key.
    4. Execute the strategy using the provided shell script.
    git clone https://github.com/hbdmapi/huobi_futures_Python.git
    cd huobi_futures_Python
    # Edit Example/config.json with your access_key and secret_key
    bash run.sh
  8. Quick Start with Huobi Swap Demo

    master

    To run the provided Huobi Swap demo, follow these steps:

    1. Clone the repository:
      git clone https://github.com/hbdmapi/huobi_futures_Python.git
    2. Navigate to the swap example directory:
       ```bash
    cd huobi_futures_Python/examples/huobi_swap
    1. Configure your credentials in config.json:
      • Set access_key to your Huobi API access key.
      • Set secret_key to your Huobi API secret key.
      • Update host and wss addresses if necessary.
    2. Execute the demo script:
      bash run.sh
    
    **Note:** The demo strategy is a simple sell short and close short implementation and must be modified for production use.
    
    ```bash
    git clone https://github.com/hbdmapi/huobi_futures_Python.git
    cd huobi_futures_Python/examples/huobi_swap
    # Edit config.json with access_key and secret_key
    bash run.sh
  9. Run the demonstration examples

    master

    To run a demonstration of the market data, order, and account push functionality (including order cancellation), follow these steps:

    1. Navigate to the specific example directory (Futures, Perpetual, or Options).
    2. Configure the config.json file with your required settings.
    3. Execute the provided shell script to start the demonstration.
    bash run.sh