Select Page

You want to find out the cryptocurrency that has the highest accumulative returns in relation to USD or Tether for the past 24 hours.

You go to CoinGecko and sort on the 24h to display the coins with the highest percent change in the last 24 hours.

You wanted to buy the 1st, 2nd or 3rd in the list but you found out that your cryptocurrency exchange (for example, Binance US) does not support trading of those coins!

You logged in to your account and checked on Binance US markets which are the top movers.

But what if you only want to see the list of best performers over the past one hour or six hours? In addition to this, you only want the top 5 cryptocurrencies in your exchange.

Your local web application will look like this, with a URL http://127.0.0.1:5000/index?hour=1&limit=5 wherein you pass in the parameters:

  • hour = for the number of hours ago of data that you want to view on
  • limit = number of cryptocurrencies that you want to display in the list

Once you know these best assets, you can use them, along with other indicators to place trades manually or create a real-time trading bot.

Here are the steps I did to accomplish this small project which is only less than 100 lines of code:

Step 1. Watch and follow Algovibe’sHow to get the BEST performing Cryptocurrencies over the last n hours/minutes. I created a local web application on top of his base codes.

Step 2. Setup Binance API Key.

After logging in and creating an API in Binance US, copy the API Key and Secret Key in a notepad.

Step 3. Setup Environment Variables

Step 3a. If you are using Windows, select Control Panel -> System and Security -> System -> Advanced system settings -> Environment Variables..

Step 3b. Add variables for API_KEY and API_SECRET. The values will come from the created API in Step 2.

Step 4. Setup Python Project Workspace

Step 4a. Download and install Pycharm Community Edition in https://www.jetbrains.com/pycharm/download/
This tutorial uses the latest stable release pycharm-community-2021.2.2.exe

Step 4b. Create New Project with a Virtual environment.

Step 4c. Create new file with filename requirements.txt

flask
gunicorn
python-binance
tqdm
pandas

Step 4d. Select “Terminal” on the bottom panel. This will launch a command line. Execute the command

pip3 install -r requirements.txt

Step 4d. Create a new file with filename app.py

import os
import pandas as pd
from tqdm import tqdm
from binance.client import Client
from datetime import datetime
from flask import Flask, request
import time

app = Flask(__name__)

client = Client(os.environ.get('API_KEY'), os.environ.get('API_SECRET'), tld='us')
info = client.get_exchange_info()

tickers = []
tickers = client.get_ticker()


@app.route('/index')
def welcome():
    hour = request.args.get('hour')
    limit = request.args.get('limit')
    timenow = datetime.now().strftime("%m/%d/%Y %H:%M:%S")
    html = f"<b>Best Performing Crypto assets for the past {hour} hour(s) <br>(As of {timenow})</b><br>"
    client = Client(os.environ.get('API_KEY'), os.environ.get('API_SECRET'), tld='us')
    info = client.get_exchange_info()

    symbols = [x['symbol'] for x in info['symbols']]
    exclude = ['UP', 'DOWN', 'BEAR', 'BULL']
    non_lev = [symbol for symbol in symbols if all(excludes not in symbol for excludes in exclude)]

    exclude2 = ['BUSD']
    non_busd = [symbol for symbol in symbols if all(excludes not in symbol for excludes in exclude2)]

    relevant = [symbol for symbol in non_busd if symbol.endswith('USD')]
    html += "<br><table  ><tr><td><b>USD</b></td></tr><td> "
    html += getPerformers(relevant, hour, limit)
    html += "</td>"

    relevant = [symbol for symbol in non_busd if symbol.endswith('USDT')]
    html += " <tr><td><b>USDT</b></td></tr><td> "
    html += getPerformers(relevant, hour, limit)
    html += "</td></tr></table>"
    return html


def getPerformers(relevant, hour, limit):
    string = ""
    klines = {}
    returns, symbols = [], []

    for symbol in tqdm(relevant):
        data = '{}'.format(hour) + ' hour ago UTC'
        klines[symbol] = client.get_historical_klines(symbol, '1m', data)

    for symbol in relevant:
        if len(klines[symbol]) > 0:
            cumret = (pd.DataFrame(klines[symbol])[4].astype(float).pct_change() + 1).prod() - 1
            returns.append(cumret)
            symbols.append(symbol)
    retdf = pd.DataFrame(returns, index=symbols, columns=['ret'])
    newretdf = retdf.ret.nlargest(int(limit))

    string = f"<table border='1'><tr><td>#</td><td>Pair</td><td>Price % Change ({hour} hrs ago)</td><td>Current Price</td></tr>"
    ctr = 0

    while ctr < len(newretdf):
        string += f"<tr><td>{ctr + 1}</td><td> {newretdf.index[ctr]}</td><td> {round(newretdf.iloc[ctr] * 100, 4)}</td>"
        string += f"<td>{get_current_price(tickers, newretdf.index[ctr])}</td>"
        string += "</tr>"
        ctr += 1

    string += "</table>"
    return string


def get_current_price(tickers, assetPair):
    price = 0
    strAsset = ""
    for ticker in tickers:
        strAsset = ticker['symbol']
        if assetPair == strAsset:
            price = ticker['lastPrice']
    return price

Step 4e. In the Terminal window, execute

flask run

Step 5. Run in web browser by entering the URL and the desired parameters http://127.0.0.1:5000/index?hour=1&limit=5

Congratz! You now have an up and running local web application that shows you the top gainer crypto assets over the last hours.

Areas of Improvement:

  • Use of websocket. You may get error messages from Binance API banning your IP address and you will only be able to resume after a certain time (usually after a few minutes). Binance sets a limit on the frequency of your application can call the Binance API endpoints. A solution to this is to make use of websocket instead of the Binance Client code above.
  • Replace the Binance Python wrapper library with CCXT Python library. You can easily add other exchanges such as Coinbase Pro, Gate.io and others.
  • Host the web application in the cloud such as Heroku, Google Cloud or Amazon Web Services.