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
Websocket 'broadcast' demo using FastAPI/Starlette

fastapi-websocket-broadcast An example of the familiar 'chat' websocket demo app, implemented in FastAPI / Starlette. Run with uvicorn app:app And th

Kit Thwaite 109 Nov 30, 2022
Minecraft WebSocket

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

Roii.py 2 Jul 07, 2022
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

3.1k Jan 02, 2023
Python socket.io server implementation on top of Tornado framework

TornadIO2 Disclaimer Unfortunately, Socket.IO 0.8 branch is abandoned, there are huge amount of bugs and nothing getting fixed. I would suggest to loo

Serge S. Koval 526 Oct 03, 2022
tiny multi-threaded socks4 server implemented in python2

tiny, multi-threaded socks4a server implemented in python2.

4 Sep 21, 2022
Async (trio) KuCoin minimal REST API + Websocket

Minimal Async KuCoin REST API + WebSocket using trio Coded by π ([email protected] TG: @p

Pi 2 Oct 23, 2022
This websocket program is for data transmission between server and client. Data transmission is for Federated Learning in Edge computing environment.

websocket-for-data-transmission This websocket program is for data transmission between server and client. Data transmission is for Federated Learning

9 Jul 19, 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
一款为 go-cqhttp 的正向 WebSocket 设计的 Python SDK

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

35 Dec 21, 2022
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
Synci - Learning project to create a websocket based client server messaging application

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

2 Jan 13, 2022
Burgeramt-appointments-websockets - Fetch Bürgeramt appointments and broadcast them via websockets

Bürgeramt appointment finder This server looks for Bürgeramt appointment every f

74 Dec 19, 2022
Websocket RPC and Pub/Sub for Python applications and microservices

wampy [whomp-ee] For a background as to what WAMP is, please see here. This is a Python implementation of WAMP using Gevent, but you can also configur

simon 121 Nov 22, 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
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
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
Using python-binance to provide websocket data to freqtrade

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

58 Jan 01, 2023
Library for easily creating and managing websockets.

Documentation coming in version 0.1.4 GitHub PyPI Discord Features Easy to use with object oriented syntax. Intellisense support with typehints and do

ZeroIntensity 0 Aug 27, 2022
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

Jeff Lindsay 256 Nov 16, 2022
image stream publish server over websocket

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

MrError404 1 Nov 04, 2021