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
Python framework for AsyncAPI-documented Websocket, PubSub, and other async constructs

asyncapi-eventrouter Work in Progress Write Python code for Event-Driven Architectures! The asyncapi-eventrouter prototype library creates Websocket,

noteable 4 Jan 27, 2022
Developer-friendly asynchrony for Django

Django Channels Channels augments Django to bring WebSocket, long-poll HTTP, task offloading and other async support to your code, using familiar Djan

Django 5.5k Jan 03, 2023
Chat app for Django, powered by Django Channels, Websockets & Asyncio

Django Private Chat2 New and improved https://github.com/Bearle/django-private-chat Chat app for Django, powered by Django Channels, Websockets & Asyn

Bearle 205 Dec 30, 2022
Terminals served by tornado websockets

This is a Tornado websocket backend for the Xterm.js Javascript terminal emulator library. It evolved out of pyxterm, which was part of GraphTerm (as

Project Jupyter 332 Dec 27, 2022
An IPC based on Websockets, fast, stable, and reliable

winerp An IPC based on Websockets. Fast, Stable, and easy-to-use, for inter-communication between your processes or discord.py bots. Key Features Fast

Black Thunder 5 Aug 09, 2022
Python Socket.IO server and client

python-socketio Python implementation of the Socket.IO realtime client and server. Version compatibility The Socket.IO protocol has been through a num

Miguel Grinberg 3.2k Dec 31, 2022
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 03, 2023
Discord.py Connect to Discord voice call with websocket

Discord.py Connect to Discord voice call with websocket

WoahThatsHot 3 Apr 22, 2022
tiny multi-threaded socks4 server implemented in python2

tiny, multi-threaded socks4a server implemented in python2.

4 Sep 21, 2022
A simple texts communication platform using pygame and sockets.

Python Tchat A simple texts communication platform using pygame and sockets. How to install ? You need a python 3.8.6 server with at least one opened

Yohann Boniface 7 Jan 23, 2022
image stream publish server over websocket

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

MrError404 1 Nov 04, 2021
A Security Tool for Enumerating WebSockets

STEWS: Security Testing and Enumeration of WebSockets STEWS is a tool suite for security testing of WebSockets This research was first presented at OW

175 Jan 01, 2023
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 08, 2022
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

Andrew Healey 24 Nov 17, 2022
一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK

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

35 Dec 21, 2022
JINS MEME(2021年モデル)のJINS MEME LoggerをPythonのWebSocketサーバーで受信するサンプル

JINS-MEME-Python-WebSocketServer-Sample JINS MEME(2021年モデル)のJINS MEME LoggerをPythonのWebSocketサーバーで受信するサンプルです。 Logging Data 以下のデータに対応しています。 各データの定義はJIN

KazuhitoTakahashi 19 Apr 29, 2022
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 04, 2023
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

OBytes 5 May 15, 2022
Socket.IO integration for Flask applications.

Flask-SocketIO Socket.IO integration for Flask applications. Installation You can install this package as usual with pip: pip install flask-socketio

Miguel Grinberg 4.9k Jan 03, 2023
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 04, 2023