Using python-binance to provide websocket data to freqtrade

Overview

Websocket for Freqtrade Strategy

The goal of this project is to provide an alternative way to get realtime data from Binance and use it in freqtrade despite the exchange used. It also uses talipp for computing

Features

  • Live Ticker
  • Live Order Book Data
  • Live Candles

Requirements

  • python-binance
  • talipp

Advantages over using standard freqtrade data

Freqtrade data is obtained using requests: it asks for new data and then it will receive the results. Using websockets you will get the pair information pushed from binance servers as soon as they are computed. For instance, while testing using about 100 pairs, freqtrade took almost one minute to start computing the new candle, while using this approcach in 3s all pairs were already processed.

Using talipp reduce the computation power required, since data are update by only adding the contribution of the new candle to the already computed data. While freqtrade computes the indicators on their integrity and by default for 1000 timeframes.

With a minimal change (see bellow) one can trigger a buy or sell directly from the function that computes the signal, reducing even more the time between taking decision and executing a trade. Also this option allow to choose the buy and sell prices inside the strategy (for instance using the orderbook information).

How to use it

CombinedBinHAndClucV4WS is an example of using this interface to code a strategy. In a few words what you need is:

  • Inherit from BinanceStream class
  • Implement init_indicators method to initialize the websocket stream and setup the indicators
  • Implement new_candle, new_ob or new_ticker to process new data (be carefull with the amount of computation, you will usually have a call every second)
  • Call pair_info.buy() and pair_info.sell() to trigger a buy or a sell

How to directly trigger a buy and sell and choose the price.

To directly trigger a buy or sell, BinanceStream must have a refernce to the freqtradebot class. It requires adding the following line into freqtradebot.py:

self.strategy.set_ft(self)

around line 66

        # Cache values for 1800 to avoid frequent polling of the exchange for prices
        # Caching only applies to RPC methods, so prices for open trades are still
        # refreshed once every iteration.
        self._sell_rate_cache: TTLCache = TTLCache(maxsize=100, ttl=1800)
        self._buy_rate_cache: TTLCache = TTLCache(maxsize=100, ttl=1800)

        self.strategy: IStrategy = StrategyResolver.load_strategy(self.config)
        self.strategy.set_ft(self) 

        # Check config consistency here since strategies can set certain options
        validate_config_consistency(config)

Callback data

new_ticker

New ticker data is exactly as provided by the Binance API:

   
        Message format:
        {
        "e": "kline",     // Event type
        "E": 123456789,   // Event time
        "s": "BNBBTC",    // Symbol
        "k": {
            "t": 123400000, // Kline start time
            "T": 123460000, // Kline close time
            "s": "BNBBTC",  // Symbol
            "i": "1m",      // Interval
            "f": 100,       // First trade ID
            "L": 200,       // Last trade ID
            "o": "0.0010",  // Open price
            "c": "0.0020",  // Close price
            "h": "0.0025",  // High price
            "l": "0.0015",  // Low price
            "v": "1000",    // Base asset volume
            "n": 100,       // Number of trades
            "x": false,     // Is this kline closed?
            "q": "1.0000",  // Quote asset volume
            "V": "500",     // Taker buy base asset volume
            "Q": "0.500",   // Taker buy quote asset volume
            "B": "123456"   // Ignore
        }
        }
           

How to keep it running in case of falure

Websockets can get closed, or connection can be lost, managing it indivudually can be a source of problems and error prone. The solution employed is simply exit freqtrade as soon as there is a problem, so you can yous a shell script that will restart it automatically:

while :
do
  freqtrade  trade       --config config.json --config config_obonly_dr.json    --db-url sqlite:///tradesv3_wild.sqlite
  sleep 10
done

Hints

  • Use a large timeframe on freqtrade (1h) to avoid it fetching data too often, and get the desired timeframe from BaseIndicator
You might also like...
Django Channels HTTP/WebSocket server

daphne Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels. It supports automatic negotia

Benchmark a WebSocket server's message throughput ⌛
Benchmark a WebSocket server's message throughput ⌛

📻 WebSocket Benchmarker ⌚ Message throughput is how fast a WebSocket server can parse and respond to a message. Some people consider this to be a goo

wssh ("wish") is a command-line utility/shell for WebSocket inpsired by netcat.

wssh ("wish") is a command-line utility/shell for WebSocket inspired by netcat

Minecraft WebSocket

Minecraft-WebSocket Pythonでマインクラフトと通信します。 紹介動画 推奨設定 Minecraft Windows Edition (Education Edition) 1.17 以上 Python 3系(3.8.2で動作確認済み) 必要なモジュール ・asyncio ・w

Tetri5 - Multiplayer Websocket Backend

Tetri5 - Multiplayer Websocket Backend This repository is the backend of the multiplayer portion of the Tetri5 game client. It uses the python websock

image stream publish server over websocket
image stream publish server over websocket

Image Stream Push Server 简介 通过浏览器网页实时查看图像处理结果。 环境 运行程序需要安装一下python依赖: tornado: 用于创建http及websocket服务; opencv-contrib-python: 用于图像数据源获取及图像处理。 使用 进入到src目

AWS API Gateway Websocket Asynchronous Notifications Pusher
AWS API Gateway Websocket Asynchronous Notifications Pusher

AWS API Gateway Websocket Asynchronous Pusher Fast AWS API Gateway websockets notifications' pusher using Python AsyncIO for managing asynchronous and

Discord.py Connect to Discord voice call with websocket

Discord.py Connect to Discord voice call with websocket

Synci - Learning project to create a websocket based client server messaging application

Synci Learning project to create a websocket based client server messaging appli

Comments
  • Explanation

    Explanation

    Hi Tom,

    I have a few clarification questions:

    1. how can you access the candle for the hourly, when the trade time frame is 15min ? i.e. current 1h candle which is still being built as the hour is not up
    2. I see the dataframe data does not show the correct price for some tickers, I presume it is not used?
    3. how would one construct dataframe for closed candles time period, let's say last 10 candles? i.e. dataframe_trend_period
    4. please confirm the index for candles? i.e. [0] = last complete candle? or [-1] = last complete candle? [-2] one back and so forth

    Thank you!!!

    opened by surfablebot 0
  • AttributeError: 'Strategy' object has no attribute 'set_ft'

    AttributeError: 'Strategy' object has no attribute 'set_ft'

    hello , can you please help me implement this into my freqtrade? i went to the freqtradebot.py and added the line:

    self.strategy.set_ft(self)

    around line 66

        # Cache values for 1800 to avoid frequent polling of the exchange for prices
        # Caching only applies to RPC methods, so prices for open trades are still
        # refreshed once every iteration.
        self._sell_rate_cache: TTLCache = TTLCache(maxsize=100, ttl=1800)
        self._buy_rate_cache: TTLCache = TTLCache(maxsize=100, ttl=1800)
    
        self.strategy: IStrategy = StrategyResolver.load_strategy(self.config)
        self.strategy.set_ft(self) 
    
        # Check config consistency here since strategies can set certain options
        validate_config_consistency(config)
    

    And i get this error : self.strategy.set_ft(self) AttributeError: 'Strategy' object has no attribute 'set_ft'

    What do i need to add into my startegy to make the bot get infor through this websockets? Sorry, but i am in process of learning python and don't know all the information yet. Thank you!

    opened by LucianPopaLVP 3
Owner
null
A websocket client for Source Filmmaker intended to trasmit scene and frame data to other applications.

SFM SOCK A websocket client for Source Filmmaker intended to trasmit scene and frame data to other applications. This software can be used to transmit

KiwifruitDev 2 Jan 8, 2022
Whatsapp Clone using django, django-channels and websocket

whatsapp-clone Whatsapp Clone using django, django-channels and websocket Features : Signup/Login One on One personal chat with other user Some screen

Anshu Pal 14 Dec 25, 2022
WebSocket implementation in Python built on top of websockets python library. Similar to Node.js's ws.

ws WebSocket implementation in Python built on top of websockets python library. Similar to Node.js's ws. Basic usage. server.py import ws server = w

AceExpert 7 Jun 27, 2022
WebSocket and WAMP in Python for Twisted and asyncio

Autobahn|Python WebSocket & WAMP for Python on Twisted and asyncio. Quick Links: Source Code - Documentation - WebSocket Examples - WAMP Examples Comm

Crossbar.io 2.4k Jan 4, 2023
Library for building WebSocket servers and clients in Python

What is websockets? websockets is a library for building WebSocket servers and clients in Python with a focus on correctness and simplicity. Built on

Aymeric Augustin 4.3k Jan 4, 2023
WebSocket client for Python

websocket-client The websocket-client module is a WebSocket client for Python. It provides access to low level APIs for WebSockets. All APIs are for s

null 3.1k Jan 2, 2023
Websockify is a WebSocket to TCP proxy/bridge. This allows a browser to connect to any application/server/service. Implementations in Python, C, Node.js and Ruby.

websockify: WebSockets support for any application/server websockify was formerly named wsproxy and was part of the noVNC project. At the most basic l

noVNC 3.3k Jan 3, 2023
WebSocket emulation - Python server

SockJS-tornado server SockJS-tornado is a Python server side counterpart of SockJS-client browser library running on top of Tornado framework. Simplif

Serge S. Koval 854 Nov 19, 2022
一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK

Nakuru Project 一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK 在 kuriyama 的基础上改动 项目名来源于藍月なくる,图标由せら绘制 食用方法 将 nakuru 文件夹移至 Python 的 Lib/site-packages 目录下。

null 35 Dec 21, 2022
alien.py - Python interface to websocket endpoint of ALICE Grid Services

alien.py - Python interface to websocket endpoint of ALICE Grid Services Quick containerized testing: singularity

Adrian Sevcenco 6 Dec 14, 2022