Search This Blog

  • Real-time RSI Trading Bot of Bitcoin using Talib Library and Binance WebSocket Client

    Real-time RSI Trading Bot of Bitcoin using Talib Library and Binance WebSocket Client


    Automated trading has become increasingly popular in recent years, thanks to advancements in technology and the accessibility of financial markets. A trading bot is an automated trading system that is programmed to execute trades based on a set of predefined rules. In this article, we will build a real-time trading bot using the Binance WebSocket client and the RSI (Relative Strength Index) strategy using Talib in Python.


    Binance is a cryptocurrency exchange that provides a WebSocket API for real-time data streaming. The WebSocket client allows us to subscribe to real-time price and volume data for any cryptocurrency listed on Binance. The RSI strategy is a popular technical analysis tool used by traders to identify overbought and oversold conditions in the market.




    We will follow these steps to build the trading bot:


    Install and Import Talib

    Install and Import Websocket Client

    Import other Libraries

    Connect to Binance Websocket

    Trading Strategy Parameters

    Paper Trading Simulation Function

    Fetch Live Data using Websocket Client

    RSI Strategy Using Ta-lib

    Generate Signal

    Start Trading




    Let's get started.


    Step 1: Install and Import Talib


    Talib (Technical Analysis Library) is a popular library for technical analysis. It provides a wide range of technical indicators, including the RSI (Relative Strength Index). To use Talib, we need to install it using pip and import it in our Python code:


    # Install and Import Talib

    !wget http://prdownloads.sourceforge.net/ta-lib/ta-lib-0.4.0-src.tar.gz

    !tar -xzvf ta-lib-0.4.0-src.tar.gz

    %cd ta-lib

    !./configure --prefix=/usr

    !make

    !make install

    !pip install Ta-Lib

    import talib

         



    Step 2: Install and Import WebSocket Client


    The WebSocket protocol allows for real-time communication between a client and a server. In our case, we will use the Binance WebSocket client to fetch real-time price data. We can install the WebSocket client using pip and import it in our Python code:


    # Install and Import Websocket Client

    pip install websocket-client

    import websocket




    Step 3: Import other Libraries


    Next, we will import other libraries that we will use in our trading bot. We will use the time module to introduce delays in our code, and the json module to parse the JSON data received from the WebSocket API.


    # Import other Libraries

    import talib

    import requests

    import pandas as pd

    import numpy as np

    import json

    import ssl

         



    Step 4: Connect to Binance Websocket


    In this step, we will connect to the Binance WebSocket API using the WebSocket client library. We will subscribe to the kline_1m endpoint, which provides 1-minute candlestick data for the Bitcoin/USDT trading pair.


    # Connect to Binance Websocket

    cc= 'btcusd'

    interval = "1m" 

    socket = f"wss://stream.binance.com:9443/ws/{cc}t@kline_{interval}"

         



    Step 5: Trading Strategy Parameters


    In this step, we will define the trading strategy parameters. 


    # Trading Strategy Parameters

    amount=1000000

    money_remaining = 1000000

    portfolio = 0

    investment, closes, highs, lows = [], [], [], []

    buy_price = []

    sell_price = []

    rsi_signal = []

    signal = 0

         



    Step 6: Paper Trading Simulation Function


    Before we start trading with real money, we will first simulate trading using a paper trading function. 


    # Paper Trading Simulation Function

    def buy(allocated_money, price):

        global closes,highs,lows, money_remaining, portfolio, investment, signal

        quantity = allocated_money  / price

        money_remaining -= quantity*price

        portfolio += quantity 

        if investment == []:

          investment.append(allocated_money)

        else:

          investment.append(allocated_money)

          investment[-1] += investment[-2]


    def sell(allocated_money, price):

        global closes,highs,lows, money_remaining, portfolio, investment, signal

        quantity = allocated_money  / price

        money_remaining += quantity*price

        portfolio -= quantity 

        investment.append(-allocated_money)

        investment[-1] += investment[-2]

          

        


    Step 7: Fetch Live Data using Websocket Client


    Next, we will modify the on_message callback function to receive live price data from the WebSocket API and store it in a variable closes. 


    # Fetch Live Data using Websocket Client

    def on_close(ws):

      print("Close")


    def on_message(ws, message):

      global closes,highs,lows, money_remaining, portfolio, investment, signal, position

      json_message = json.loads(message)

      cs = json_message["k"]

      candle_closed, close, high, low = cs["x"], cs["c"],cs["h"],cs["l"]



      if candle_closed:

        closes.append(float(close))

        highs.append(float(high))

        lows.append(float(low))

        last_price = closes[-1]

        print(f'Closes : {closes[-5:]}')




    Step 8: RSI Strategy Using Ta-lib


    We will define our RSI trading strategy using the RSI values that we will generate using Talib.


    # RSI Strategy Using Ta-lib

        rsi = talib.RSI(np.array(closes), timeperiod=3)

        last_rsi=round(rsi[-1],2)

        print(last_rsi)

     

        if (rsi[-1] > 40 and rsi < 40).any():

                  if signal != 1:

                    buy_price.append(closes)

                    sell_price.append(np.nan)

                    signal = 1

                    rsi_signal.append(signal)

                  else:

                    buy_price.append(np.nan)

                    sell_price.append(np.nan)

                    rsi_signal.append(0)

        elif (rsi[-1] < 60 and rsi > 60).any():

                  if signal != -1:

                    buy_price.append(np.nan)

                    sell_price.append(closes)

                    signal = -1

                    rsi_signal.append(signal)

                  else:

                    buy_price.append(np.nan)

                    sell_price.append(np.nan)

                    rsi_signal.append(0)

        else:

                    buy_price.append(np.nan)

                    sell_price.append(np.nan)

                    rsi_signal.append(0)


        print(rsi_signal[-5:])




    Step 9: Generate Signal


    We will generate Trading Signal here.


    # Generate Signal and Trade

        if rsi_signal[-1] == 1:

               buy(250000, last_price)

               print(f'(Bitcoin Bought ="{portfolio}")')

        elif rsi_signal[-1] == -1:

               sell(250000, last_price)

               print(f'(Bitcoin Sold ="{portfolio}")')

        else:

               print("No Trade")



    wsapp = websocket.WebSocketApp(socket, on_message = on_message, on_close = on_close)

         



    Step 10: Start Trading


    Finally, our Real-Time Trading Bot is ready


    # Real Time Trading Bot

    wsapp.run_forever()




    Conclusion


    Here we built a real-time trading bot using the Binance WebSocket client and the RSI strategy using Talib in Python. The trading bot monitors the price of Bitcoin in real-time and executes trades based on the RSI value.


    There are several ways to improve this trading bot. For example, we can add more technical indicators, such as moving averages or MACD, to improve the trading signals. We can also implement a stop-loss and take-profit feature to manage the risk of the trades.





  • 0 comments:

    Post a Comment

    Please do not enter any spam link in the comment box.

    DO YOU WANT MENTORSHIP?

    ADDRESS

    Delhi, India

    EMAIL

    admin@guptaharsh.in