How to invest and trade in crypto currencies with Tradingview, Cryptohopper and Binance

Travel in the world of crypto currencies! How to invest responsible, using the best tools and configuring them.

In recent years, the impressive rise in the price of the first and main virtual currency in the world, the Bitcoin ( BTC ), has created numerous new rich people who, with a lot of luck, a little daring and a bit of strategy, have amassed small and large fortunes.
The interest generated by these profits then allowed the birth of other virtual currencies (cryptocurrencies) such as Ethereum ( ETH ), Binance ( BNB ), Shiba inu coin ( SHIB ) etc. Now there are hundreds of them: there are even those of some football teams including Manchester City FC ( CITY ), Juventus F.C. ( JUVE ), a.s. Roma ( ASR ) and s.s. Lazio ( LAZIO ). Some are based on proprietary platforms such as BTC and others on the Ethereum platform such as SHIB.

But what do you need, what tools do you need to invest in crypto?

  • First of all money: I advise not to invest more than 2% of your liquidity, being an extremely volatile and very very risky market ( invest at your own risk ). So if you have a nest egg of 200 thousands euros/dollars aside, the advice of investors is to take 4 thousands of them to invest in crypto coins. The rest is better invested in investment funds, or in interest-bearing bonds, or in properties.
  • The money must be transferred to an online trading platform and for me the best is Binance . Binance is packed with features for investing your savings in various ways, but I leave you the pleasure of discovering them. I personally only use Spot type investments: buy and sell directly. To use Binance you need to create an account, put into it some money and create your own API to interact with a BOT that will help you verify your earnings. Finally, Binance also provides the user with a Visa credit card, which they will send to your home, that can be used at any POS or to pay with your mobile phone via NFC or on Amazon using your earnings in cryptocurrency and converted into euros/dollars: better than this could not be done.
  • Then you need to have a tool that "tells" you when to buy and when to sell. Things could get complicated here, but using a tool like Tradingview you will have all the currencies of the world at your disposal together with numerous integrated analysis functions. In addition to a scripting system to launch buy and sell messages. I will explain everything later on.
  • At this point, once we have good signals, we need to send them to an additional security platform that has other tools that allow us to sell cryptocurrencies early if certain conditions are met. I use Cryptohopper for this.

So the scheme is:

tradingview logo        cryptohopper logo        binance logo

And that would be all it takes.


Here are some empirical laws that I have drawn in a year of experience:

  1. buy only when BTC is on the rise ( Bullish monitoring 1 day candle time ) because the other cryptocurrencies are very linked to the trend of Bitcoin;
  2. sell every coins when BTC goes down ( Bearish monitoring 1D candle time );
  3. use a BTC control period set to 1 day in Cryptohopper triggers: 1D;
  4. use 5 hours ( 5H ) candel control period for all the signal in Tradingview for all the coins;
  5. use two financial EMA function to determine when BTC is rising or falling. EMA8 and EMA24.

Configuration Tips


binance logo

First of all once you have a Binance account, click to your profile icon on the right up side of the Binance home page and select "API Management".

Once there create a new API Key for Cryptohopper and call it Cryptohopper . Select Enable Reading, Enable Spot and Unrestricted. Then copy only the Api Key. And Paste it into Cryptohopper .

Into Cryptohopper create a new hopper.

Then into Configuration -> General -> Exchange deselect Paper Trading ( means fake trades, for experiments ).

Select Binance as Exchange, paste the API Key in Binance Api Key.

Then return to your Binance page, copy the secret key, return to your hoppper configuration page and paste it in the Binance API Secrete field.
Finally click Save.


The Best Cryptohopper Config

cryptohopper logo

Go to the Cryptohopper and create an account.

Once you're in, on the left select Hopper and create a new one hopper. Name it as you like.

Since we have used the dollar as a base currency up to now we have to configure Cryptohopper to work with the USDT which is the stable coin ( stable understood as that does not change value with respect to the dollar, but is always a cryptocurrency. Nothing prevents you from using other stablecoins such as BUSD etc ... ).

  • Go to Config -> Baseconfig
  • Select "Coins and amounts"
  • And in the Quote currency selector select USDT
  • Click Save

Now it's better to configure the amount in dollars for each signal recieved to be buyed. I set this value to 21 dollars, becouse the tradingview pinescript that we wrote before repeat buys ( pyramiding ) if the marcket is rising.

  • Go to Config -> Baseconfig
  • Select "Coins and amounts"
  • Set "Minimum USDT amount per order" to 21 and check "Force minimum buy amount"
  • Click Save

Now you need to configure 2 triggers that tell to hopper when BTC goes up to open for purchases, and when BTC goes down to sell everything:

  • Go to Config -> Triggers
  • Create two new triggers called BTC open and BTC close
  • Click Save

Trigger 1 ( BTC open )

the first one called "BTC open" configured as follows:
market: BTC
candle size: 1 day
indicator: EMA con
signals a buy
EMA short period: 8
EMA long period: 24
action: set buy status: Enabled
set selling status: Enabled
Click Save

Trigger 2 ( BTC close )

the second one called "BTC close" instead like this:
marcket: BTC
candle size: 1 day
indicator: EMA con
signals a sell
EMA short period: 8
EMA long period: 24
action: set buy statys: Disabled
set selling status: Enabled
Click Save

Other settings

In the section Config -> Baseconfig -> Selling set:

Sell settings: take profit: 30%
Click Save

Trailing stop loss:

  • Trailing stop-loss percentage: 1%
  • Arm trailing stop-loss at: 5%
Click Save

Disable the buying enabled/disabled selector

And finally in the home page, if on the right you see BUYING IS ENABLED, disable it so it turn into BUYING IS DISABLED (the selector become red). Now all it's set: when the BTC open trigger recieve the info that EMA8 is crossing up EMA24 it turn BUYNG IS DISABLED into BUYING IS ENABLED. And the buying signals from Tradingview become effective.

Now Link Cryptohopper to Tradingview

Now that you are in Cryptohopper clikc on Marketplace on the left of the page. Then click App and finally click on the Tradingview app in the last row. You will land on a page where is your Webhook Url to be used in the Tradingview alerts.

Now it's time to get your hopper id, to be used in the Pine Script later on.
Go down the App page where you in, and in the Alert Generator select your hopper you already created ( down this page you'll find some istruction for it ) and click "Generate".
Down you'll see the alert generater. Copy only the number after hopper_id: and store it in some text file for later use.


The Best Pine Script for Tradingview

tradingview logo

First of all create a Tradingview account.

Once you are in you have to store your Pine Script in the editor you'll find in the bottom panel. You can obviously use any script, there'are a bunch of them in the Tradingview community.

pine script logo

To help you I'll post here my Pine Script (copy and paste and save it as "Extreme prices breakout") for Tradingview which needs to talk to Cryptohopper . For this script I introduced also isScam parameter that activate a control to the previous candle: if the candle had a rise over a give value (maybe so high the next one very problably will be a down) than the script do not buy. I also introduced TrailingStopLoss parameter in order to have a trailing stop loss for every coin. ***Replace [your_cryptohopper_id] with your hopper id:

//@version=5
strategy("Supertrend ckiikc", overlay=true, initial_capital=6100,
     currency=currency.USD,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=15,
     commission_type=strategy.commission.percent,
     commission_value=0.1,
     pyramiding=0)

shortSMA = ta.sma(close,10)
longSMA = ta.sma(close,30)
plot(shortSMA,color=color.blue)
plot(longSMA,color=color.rgb(175, 76, 162))


longCondition = ta.crossover(shortSMA,longSMA)
shortCondition = ta.crossunder(shortSMA,longSMA)


atrPeriod = input(10, "ATR Length")
factor = input.float(3.0, "Factor", step = 0.01)
isScamActive = input.bool(true,"isScam Active")

[_, direction] = ta.supertrend(factor, atrPeriod)

emaFast = 8
emaSlow = 24

fastEMA = ta.ema(close, emaFast)
slowEMA = ta.ema(close, emaSlow)
plot(series=fastEMA, color=color.green, linewidth=3)
plot(series=slowEMA, color=color.red, linewidth=3)


longEMACondition = ta.crossover(fastEMA, slowEMA)
shortEMACondition = ta.crossunder(fastEMA, slowEMA)

ticker = str.replace_all(syminfo.ticker, 'USDT', '')
ticker := str.replace_all(ticker, 'BUSD', '')
ticker := str.replace_all(ticker, 'USD', '')


scam_value = 10
is_also_a_scam_0 = ((close - close[1])/close[1])*100 > scam_value
is_also_a_scam_1 = ((close - close[2])/close[2])*100 > scam_value
is_also_a_scam_2 = ((close - close[3])/close[3])*100 > scam_value
is_scam = (is_also_a_scam_0 or is_also_a_scam_1 or is_also_a_scam_2) and isScamActive

scam_value_down = 3
is_also_a_scam_down_0 = ((close[1] - close)/close[1])*100 > scam_value_down
is_also_a_scam_down_1 = ((close[2] - close)/close[2])*100 > scam_value_down
is_also_a_scam_down_2 = ((close[3] - close)/close[3])*100 > scam_value_down
is_scam_down = is_also_a_scam_down_0 or is_also_a_scam_down_1 or is_also_a_scam_down_2

your_hopper_id = [your_hopper_id] //replace it with your hopper id

if (ta.change(direction) < 0) and not is_scam //or (close > fastEMA and fastEMA > (slowEMA+0.002))
    act = 'buy'
    message_hopper = 'hopper_id:' + your_hopper_id + '\ncoin:' + ticker + '\naction:' + act + '\nmarket_order:1'
    strategy.entry("Buy",strategy.long,alert_message= message_hopper)

//Trailing stop
TrailingIsActive = input.bool(false,"Trailing Stop is Active")
TrailingPercent = input.float(1,"Trailing Stop Percentage",0.0,1.0,0.01)
PriceStop = 0.0

if TrailingIsActive
    if strategy.position_size > 0  
        StopValue = high * (1 - TrailingPercent)
        PriceStop := math.max(StopValue, PriceStop[1])
    else
        PriceStop := 0.0

    if strategy.position_size > 0
        act = 'sell'
        message_hopper = 'hopper_id:' + your_hopper_id + '\ncoin:' + ticker + '\naction:' + act + '\nmarket_order:1'
        strategy.exit("TSL",from_entry="Buy",alert_message=message_hopper, stop = PriceStop)



if  ta.change(direction) > 0 //or (close < fastEMA and fastEMA < (slowEMA+0.002))
    act = 'sell'
    message_hopper = 'hopper_id:' + your_hopper_id + '\ncoin:' + ticker + '\naction:' + act + '\nmarket_order:1'
    strategy.close("Buy", alert_message=message_hopper)
    //semaphore := 1



The Second Best Pine Script for Tradingview

pine script logo

Supertrend strategy it's a very good algorithm but not all crypto currencies react well to it. So for some crypto I use another script called" SMA ckiikc"). It's up to you to ivestigate which script is better for all every coins in a particular moment. In this script there is TrailingStopLoss implemented too. ***Replace [your_cryptohopper_id] with your hopper id:

//@version=5
strategy("SMA ckiikc", overlay=true, initial_capital=6100,
     currency=currency.USD,
     default_qty_type=strategy.percent_of_equity,
     default_qty_value=15,
     commission_type=strategy.commission.percent,
     commission_value=0.1,
     pyramiding=0)


shortSMA = ta.sma(close,10)
longSMA = ta.sma(close,30)
plot(shortSMA,color=color.blue)
plot(longSMA,color=color.green)

RSI = ta.rsi(close,14)
ATR = ta.atr(14)

longCondition = ta.crossover(shortSMA,longSMA)
shortCondition = ta.crossunder(shortSMA,longSMA)

ticker = str.replace_all(syminfo.ticker, 'USDT', '')
ticker := str.replace_all(ticker, 'BUSD', '')
ticker := str.replace_all(ticker, 'USD', '')

your_hopper_id = [your_hopper_id] //change it with your hopper id

if (longCondition and RSI > 30)
    stopLoss = low-ATR*1
    target = high+ATR*1
    act = 'buy'
    message_hopper = 'hopper_id:' + your_hopper_id + '\ncoin:' + ticker + '\naction:' + act + '\nmarket_order:1'
    strategy.entry("Buy", strategy.long,alert_message = message_hopper)

if (shortCondition and RSI < 70)
    stopLoss = high+ATR*1
    target = low-ATR*1
    act = 'sell'
    message_hopper = 'hopper_id:' + your_hopper_id + '\ncoin:' + ticker + '\naction:' + act + '\nmarket_order:1'
    strategy.exit("Sell", alert_message = message_hopper, stop=stopLoss, limit= target)

//Trailing stop
TrailingIsActive = input.bool(true,"Trailing Stop is Active")
TrailingPercent = input.float(0.45,"Trailing Stop Percentage",0.0,1.0,0.01)
PriceStop = 0.0

if TrailingIsActive
    if strategy.position_size > 0  
        StopValue = high * (1 - TrailingPercent)
        PriceStop := math.max(StopValue, PriceStop[1])
    else
        PriceStop := 0.0

    if strategy.position_size > 0
        act = 'sell'
        message_hopper = 'hopper_id:' + your_hopper_id + '\ncoin:' + ticker + '\naction:' + act + '\nmarket_order:1'
        strategy.exit("TSL",from_entry="Buy",alert_message=message_hopper, stop = PriceStop)


On Tradingview at this point you need to create an alert for each currency you want to trade with.

Select any chart in advanced mode and type BTCUSDT for example, or any other coin ( tipe some text after clicked on Tradingvierw graph black part and select any coin with USDT exchange and Binance trader ).

On the graph that will appear be sure to have selected 5H period (this is a standard solution, but you can customize the candle stick period using the Strategy tester to choose the most profitable period). Then click with the right mouse button inside the graph and select Add alert ...

And configure the alert as follows:

  • Condition: Extreme prices breakout
  • Webhook URL: https: //www.cryptohopper.com/tradingview_alerts/hook? key = [Your cryptohopper api key]
  • Message: {{strategy.order.alert_message}}

That's all.


THIS IS NOT NECESSARY, BUT FOR PRO USERS I ALSO PUT THIS PART:

For pro users I suggest to use a script in python to check every n minutes if all your investment in Binance exceeds a certain percentage. In fact I found that after 3-5% of profit the market goes down. This functionality is not yet present in Cryptohopper, so I managed to implement it with Python and Raspberry PI.

Raspberry Pi 4

First of all buy a Rapsberry PI 4 (I suggest the kit):

Then install Raspberry Debian operating system in it. And finally using Flask run this script in your new server.

After installed the Raspberry PI:

  • Create binance and app directory in this position /var/www/binance/app/;
  • Put in it the following code in app.py file;
import json, config, math, concurrent.futures, threading, logging, sqlite3
import numpy as np
import datetime
from flask import Flask, request, jsonify, render_template
from binance.client import Client
from binance.enums import *

app = Flask(__name__)

app.jinja_env.auto_reload = True

thread_local = threading.local()
client = Client(config.API_KEY, config.API_SECRET)


stable_coin = 'USDT'

filename_reserved_currencies = "reserved.txt"
f = open(filename_reserved_currencies, "r")
reserved_currencies = f.readline().rstrip().split(',')
reserved_currencies_with_usdt = [s + stable_coin for s in reserved_currencies]

reserved_currencies = reserved_currencies + reserved_currencies_with_usdt


logging.basicConfig(filename='binance.log', level=logging.INFO, format='%(asctime)s - %(levelname)s: %(message)s', datefmt='%Y-%m-%d %H:%M:%S %p')
#logging.info('Reserved currencies')
#logging.info(reserved_currencies)

def truncate(number, digits) -> float:
    stepper = 10.0 ** digits
    return math.trunc(stepper * number) / stepper

def sell_all(with_reserved=False):
    info = client.get_account()

    assets = []
    values = []

    for index in range(len(info['balances'])):
        if float(info['balances'][index]['free'])>0.0:
            for key in info['balances'][index]:
                if key == 'asset':
                    assets.append(info['balances'][index][key])
                if key == 'free':
                    values.append(info['balances'][index][key])

    data = json.loads(request.data)

    logging.info(data['ticker'])
    logging.info(data['strategy']['order_action'].upper())
    logging.info(data['strategy']['order_contracts'])

    if data['passphrase'] != config.WEBHOOK_PASSPHRASE:
        resp = {"code": "error","message": "Nice try, invalid passphrase"}
        return jsonify(resp)

    if data['ticker'] != "PANIC_BUTTON":
        resp = {"code": "error","message": "no panic"}
        return jsonify(resp)

    #my_file = open("coins_list", "r")
    coins_list = assets

    converted_list = []

    logging.info('Reserved currencies')
    logging.info(reserved_currencies)

    if with_reserved:
        for element in coins_list:
            logging.info(element.strip())
            #converted_list.append(element.strip())
    else:
        for element in coins_list:
            if element != stable_coin and element != 'BNB' and element != 'BNB'+stable_coin and element != 'SHIB' and element != 'SHIB'+stable_coin and element not in reserved_currencies:
                logging.info(element.strip())
                converted_list.append(element.strip())

    order_response_text = ""
    order_response_all = 1
    for i in converted_list:

        data['ticker'] = i

        side = 'SELL'

        logging.info(i)
        this_asset = i + stable_coin
        info_symbol = client.get_symbol_info(this_asset)
        #logging.info(info_symbol)
        #baseAssetPrecision = int(info_symbol['baseAssetPrecision'])
        #logging.info(baseAssetPrecision)
        my_qty = float(client.get_asset_balance(asset=i)['free'])
        OrderSize = my_qty
        if OrderSize >= 0.01 :
            OrderSize = truncate(OrderSize,2)
            logging.info('OrderSize >= 0.01')
            logging.info(OrderSize)
        else :
            logging.info('OrderSize < 0.01')
            logging.info(OrderSize)

        logging.info(OrderSize)
        quantity = OrderSize
        symbol = data['ticker']
        order_type=ORDER_TYPE_MARKET

        logging.info(f"sending order {order_type} - {side} {quantity} {symbol}")

        #order_response = 0
        order_response = order(side, quantity, this_asset)
        order_response_all = order_response_all and order_response
        #logging.info(order_response)

        if order_response:
            order_response_text = f"order {order_type} - {side} {quantity} {symbol} succeded"
            logging.info(order_response_text)
        else:
            order_response_text = f"order {order_type} - {side} {quantity} {symbol} failed"
            logging.info(order_response_text)
            quantity = truncate(quantity,0)
            logging.info('new quontity truncate 0')
            logging.info(quantity)
            order_response2 = order(side, quantity, this_asset)
            logging.info(order_response2)

        logging.info('***')
        
    return order_response_all



def topup_bnb(min_balance: float, topup: float):
    ''' Top up BNB balance if it drops below minimum specified balance '''
    bnb_balance = client.get_asset_balance(asset='BNB')
    bnb_balance = float(bnb_balance['free'])

    logging.info('bnb_balance: %s', str(bnb_balance))
    logging.info('bnb_min_balance: %s', str(min_balance))

    if bnb_balance < min_balance:
        logging.info('bnb_balance < bnb_min_balance')
        qty = round(topup - bnb_balance, 5)
        print(qty)
        logging.info('ordering %s of BNB'+stable_coin, qty)
        order = client.order_market_buy(symbol='BNB'+stable_coin, quantity=qty)
        return order
    return False


def get_symbol_ticker(couple):
    price = client.get_symbol_ticker(symbol=couple)
    return price

def get_total_balance():

    info = client.get_account()

    assets = []
    values = []
    usdt_value = 0.0
    for index in range(len(info['balances'])):
        if float(info['balances'][index]['free'])>0.0:
            for key in info['balances'][index]:
                if key == 'asset':
                    assets.append(info['balances'][index][key])
                if key == 'free':
                    values.append(info['balances'][index][key])
                    if info['balances'][index]['asset'] == stable_coin:
                        usdt_value = info['balances'][index][key]


    token_usdt = []  # Dict to hold pair price in stable_coin
    token_pairs = []  # List to hold different token pairs



    # Creating token pairs and saving into a list
    with concurrent.futures.ThreadPoolExecutor(max_workers=200) as executor:
        for token in assets:
            #logging.info(token)
            if token != stable_coin:
                couple=token + stable_coin
                try:
                    price = executor.submit(get_symbol_ticker, couple)
                    #logging.info(couple)
                    #logging.info('couple price: %s', str(price.result()))
                    token_usdt.append(price.result())
                    token_pairs.append(couple)
                except Exception as e:
                    token_usdt.append({'symbol': couple, 'price': '-1'})
                    token_pairs.append(couple)
                    pass
            else:
                token_usdt.append(0)
   #else:
            #    token_usdt.append(0)
            #    token_pairs.append(stable_coin)
    total = total_amount_usdt(assets,values,token_usdt,token_pairs)
    total_without_reserved = total_amount_without_reserved_usdt(assets,values,token_usdt,token_pairs)
    n_currencies = 0
    this_currency_amount = 0.0
    total_amount = 0.0
    for i, token in enumerate(assets):
        if token in reserved_currencies:
            total_amount = total_amount
        elif token != stable_coin:
            this_currency_amount = float(values[i]) * float(token_usdt[i]['price'])
            if this_currency_amount > 15.0:
                n_currencies = n_currencies + 1

    return total_without_reserved, total, usdt_value, n_currencies

def total_amount_without_reserved_usdt(assets, values, token_usdt, token_pairs):

    total_amount = 0

    for i, token in enumerate(assets):
        if token in reserved_currencies:
            total_amount = total_amount
        elif token != stable_coin:
            if float(token_usdt[i]['price'])> 0.0:
                total_amount += float(values[i]) * float(token_usdt[i]['price'])
        else:
            total_amount += float(values[i]) * 1
    return total_amount

def total_amount_usdt(assets, values, token_usdt, token_pairs):
    total_amount = 0

    #logging.info('enumerate assets = %s elements', str(len(assets)))
    #logging.info('enumerate token_usdt = %s elements', str(len(token_usdt)))
    #logging.info('enumerate values = %s elements', str(len(values)))
    if len(assets)>1:
        logging.info('len_assets: %s', str(len(assets)))
        for i, token in enumerate(assets):
            #logging.info('value = %s', str(values[i]))
            #logging.info('price = %s', str(float(token_usdt[i]['price'])))
            #logging.info('------')
            
            if token != stable_coin:
                if float(token_usdt[i]['price'])> 0.0:
                    total_amount += float(values[i]) * float(token_usdt[i]['price'])
            else:
                total_amount += float(values[i]) * 1
    else:
        logging.info('binance server respond with insufficient coins: %s', str(len(assets)))
    return total_amount

def total_amount_btc(assets, values, token_usdt):
    """
    Function to calculate total portfolio value in BTC
    :param assets: Assets list
    :param values: Assets quantity
    :param token_usdt: Token pair price dict
    :return: total value in BTC
    """
    total_amount = 0
    for i, token in enumerate(assets):
        if token != 'BTC' and token != stable_coin:
            total_amount += float(values[i]) \
                            * float(token_usdt[token + stable_coin]) \
                            / float(token_usdt['BTC'+stable_coin])
        if token == 'BTC':
            total_amount += float(values[i]) * 1
        else:
            total_amount += float(values[i]) \
                            / float(token_usdt['BTC'+stable_coin])
    return total_amount


def assets_usdt(assets, values, token_usdt):
    """
    Function to convert all assets into equivalent stable_coin value
    :param assets: Assets list
    :param values: Assets quantity
    :param token_usdt: Token pair price dict
    :return: list of asset values in stable_coin
    """
    assets_in_usdt = []
    for i, token in enumerate(assets):
        if token != stable_coin:
            assets_in_usdt.append(
                float(values[i]) * float(token_usdt[token + stable_coin])
            )
        else:
            assets_in_usdt.append(float(values[i]) * 1)
    return assets_in_usdt

def order(side, quantity, symbol, order_type=ORDER_TYPE_MARKET, balance = 0.0):
    try:
        logging.info('ENTERING IN ORDER')
        binance_asset=symbol.replace(stable_coin,'')
        binance_asset=binance_asset.replace('USD','')
        OrderSize = quantity
        stepSize = 0

        #topup_bnb(1,1.1)
        logging.info(side)

        if side == "SELL" :
            logging.info('ENTERING IN SELL')
            OrderSize= quantity
            logging.info(symbol)
            logging.info(OrderSize)

            if binance_asset == "BNB" :
                OrderSize = OrderSize * 0.0
            #quantity=quantity-(quantity*0.0016)

        if side == "BUY" :
            logging.info('ENTERING IN BUY')
            logging.info(f"TRYING TO BUY {symbol}")
            if balance == 0.0 :
                total_balance_without_reserved, total_balance, usdt_value, n_currencies = get_total_balance()
            else :
                total_balance_without_reserved = float(balance)
                total_balance = float(balance)

            logging.info(f"{stable_coin} available: {total_balance_without_reserved}")
            total_balance_without_reserved = float(total_balance_without_reserved)
            amount = total_balance_without_reserved*0.0046

            logging.info(f"{stable_coin} available per coin: {amount}")
            
            maxAmount = 22.0
            minAmount = 20.0

            if amount > maxAmount :
                logging.info(f"{stable_coin} amount too big for me ({maxAmount}) per coin")
                amount = maxAmount
                logging.info(f"{stable_coin} amount resetted to ({amount})")
            if amount < minAmount :
                logging.info(f"{stable_coin} amount too small for me ({minAmount}) per coin")
                amount = minAmount
                logging.info(f"{stable_coin} amount resetted to ({amount})")
            symbolusdt=symbol+stable_coin
            info = client.get_symbol_info(symbolusdt)
            

            #print(info)
            baseAssetPrecision = int(info['baseAssetPrecision'])

            minQty = truncate(float(info['filters'][2]['minQty']),baseAssetPrecision)
            logging.info(f"minQty = {minQty}")
            minNotional = truncate(float(info['filters'][3]['minNotional']),baseAssetPrecision)
            logging.info(f"minNotional = {minNotional}")
            stepSize = float(info['filters'][2]['stepSize'])
            logging.info(f"stepSize = {stepSize}")

            logStepSize = abs(math.log10(stepSize))
            logging.info(f"logStepSize = {logStepSize}")

            price = float(client.get_symbol_ticker(symbol=symbolusdt)['price'])
            logging.info(f"price of {symbol}: {price}")

            MinimumOrderSize = truncate(float(round(minNotional / price,0)),logStepSize)

            OrderSize = truncate(float(round(amount/price,0)),logStepSize)
            
            logging.info(f"quantity of {symbol} to buy: {OrderSize}")

            logging.info(f"minQuantity to by of {symbol}: {minQty}")
            logging.info(f"minNotional to by of {symbol}: {minNotional}")

            if OrderSize < MinimumOrderSize :
                logging.info(f"Quantity {OrderSize} considered insufficient")
                OrderSize = MinimumOrderSize
                logging.info(f"Quantity resetted to {OrderSize}")

            stepSize10 = stepSize * 10
            logging.info(f"adding stepSize10 = {stepSize10} to orderSize = {OrderSize} for boh!")

            OrderSize = OrderSize + stepSize10

        
        logging.info(f"sending now order {order_type} - {side} {OrderSize} {symbol}")
        symbolusdt=symbol+stable_coin
        order = client.create_order(symbol=symbolusdt, side=side, type=order_type, quantity=OrderSize)
    except Exception as e:
        logging.info("an exception occured - {}".format(e))
        return False

    return order

def exp_moving_avarage(x,n):
    weights = np.exp(np.linspace(-1.,0.,n))
    weights /= weights.sum()

    ema = np.convolve(x, weights)[:len(x)]
    ema[:n] = ema[n]

    return ema

@app.route('/', methods=['POST','GET'])
def welcome():
    return render_template('result.html')

@app.route('/rebuy_all', methods=['POST'])
def rebuy_all():
    
    currencies_set = request.args.get('set')
    currencies_set_file = 'all_currencies_set.txt'

    if(currencies_set == '200') :
        currencies_set_file = 'all_currencies_first_120.txt'

    data = json.loads(request.data)
    resp = {"code": "error","message": "Wrong message"}

    if data['passphrase'] != config.WEBHOOK_PASSPHRASE :
        resp = {"code": "error","message": "Nice try, invalid passphrase"}
        

    side = data['strategy']['order_action'].upper()
    

    if side == 'REBUY_ALL' :
        f = open(currencies_set_file, "r")
        all_currencies_array = f.readline().rstrip().split(',')
        all_currencies_array.reverse()
        total_balance_without_reserved, total_balance, usdt_value, n_currencies = get_total_balance()
        total_balance_without_reserved = float(total_balance_without_reserved)

        for token in all_currencies_array:
            logging.info('token to be buyed: %s',token)
            order_response = order('BUY', 0.0, token,ORDER_TYPE_MARKET, total_balance_without_reserved)

            if not order_response :
                logging.info('token not buyed: %s',token)

            logging.info('-------------')

            resp = {"code": "success","message": "order executed"}
            
 
    return jsonify(resp)

@app.route('/webhook', methods=['POST'])
def webhook():
    #print(request.data)
    data = json.loads(request.data)
    
    if data['passphrase'] != config.WEBHOOK_PASSPHRASE:
        resp = {"code": "error","message": "Nice try, invalid passphrase"}
        return jsonify(resp)

    print(data['ticker'])
    print(data['bar'])

    side = data['strategy']['order_action'].upper()
    quantity = data['strategy']['order_contracts']
    symbol = data['ticker']

    print(symbol)

    order_response = order(side, quantity, symbol)

    print(order_response)

    resp = {}
    if order_response:
        resp = {"code": "success","message": "order executed"}
    else:
        print("order failed")
        resp = {"code": "error","message": "order failed"}

    return jsonify(resp)

@app.route('/panic_button', methods=['POST'])
def panic_button():
    order_response_all=sell_all()
    resp = {}
    if order_response_all:
        resp = {"code": "success","message": order_response_text}
    else:
        print("order failed")
        resp = {"code": "error","message": order_response_text}

    return jsonify(resp)

@app.route('/check_balance_ten_percent', methods=['POST'])
def check_balance_ten_percent():

    f = open(filename_reserved_currencies, "r")
    reserved_currencies = f.readline().rstrip().split(',')
    reserved_currencies_with_usdt = [s + stable_coin for s in reserved_currencies]

    reserved_currencies = reserved_currencies + reserved_currencies_with_usdt

    logging.info('Reserved currencies:')
    logging.info(reserved_currencies)

    #open and read the file after the appending:
    #logging.info('reading ten_percent.txt and ten_percent_actual.txt')
    
    filename = "ten_percent.txt"
    filename_actual = "ten_percent_actual.txt"
    
    f = open(filename, "r")
    initial_balance=float(f.read())
    
    f_actual = open(filename_actual, "r")
    initial_balance_actual = float(f_actual.read())
    #logging.info(initial_balance_actual)
    #logging.info('initial_balance without reserved: $ %s',str(initial_balance))
    total_balance_without_reserved, total_balance, usdt_value, n_currencies = get_total_balance()
    usdt_value = float(usdt_value)
    n_currencies = float(n_currencies)
    total_balance =float(total_balance)
    total_balance_without_reserved = float(total_balance_without_reserved)
    rounded_total_balance = round(total_balance,4)
    rounded_initial_balance_actual = round(initial_balance_actual,4)
    logging.info('total_balance: $ %s - $ %s ($ %s)',str(rounded_total_balance),str(rounded_initial_balance_actual),str(round(rounded_total_balance - rounded_initial_balance_actual,4)))

    logging.info('total_balance without reserved: $ %s - $ %s ($ %s)',str(round(total_balance_without_reserved,4)),str(round(initial_balance,4)),str(round(total_balance_without_reserved-initial_balance,4)))
    #percent_for_total_balance = float(100*(total_balance - initial_balance)/initial_balance)
    percent_for_total_balance_without_reserved = float(100*(total_balance_without_reserved - initial_balance)/initial_balance)
    #logging.info('current percent of total balance: %s',str(percent_for_total_balance))
    logging.info('current percent of total balance without reserved: %s%%',str(round(percent_for_total_balance_without_reserved,4)))

    filename_perc_for_panic = "percentage_for_panic.txt"
    f = open(filename_perc_for_panic, "r")
    percentage_for_panic=float(f.read())
    logging.info('percentage for panic: %s%%',str(percentage_for_panic))

    filename_perc_for_panic_negative = "percentage_for_panic_negative.txt"
    f = open(filename_perc_for_panic_negative, "r")
    percentage_for_panic_negative=float(f.read())
    logging.info('percentage for panic negative: %s%%',str(percentage_for_panic_negative))
    ct = datetime.datetime.now()
    date_time = ct.strftime("%Y-%m-%d %H:%M:%S")
    result = render_template('index_sum.html',timestamp=date_time, reserved_currencies=reserved_currencies, initial_balance_without_reserved=initial_balance, total_balance = str(rounded_total_balance), total_balance_without_reserved = str(round(total_balance_without_reserved,4)), current_percentage = str(round(percent_for_total_balance_without_reserved,4)), percentage_for_panic= str(percentage_for_panic), percentage_for_panic_negative=str(percentage_for_panic_negative), difference = str(round(total_balance_without_reserved - initial_balance,4)), initial_balance_actual = str(rounded_initial_balance_actual), difference_actual= str(round(rounded_total_balance - rounded_initial_balance_actual,4)))
    with open('templates/result.html', 'w') as f:
        f.write(result)

    if percent_for_total_balance_without_reserved >= percentage_for_panic :
        logging.info('Selling all for profit')
        result = sell_all()
        logging.info('sell_all:')
        logging.info('result')
        #topup_bnb(0.5, 0.5)
        f = open(filename, "w")
        logging.info('Writing new total balance into %s', filename)
        f.write(str(truncate(total_balance_without_reserved, 0)))
        f.close()
        logging.info('new initial_balance written into %s', filename)

    if percent_for_total_balance_without_reserved < percentage_for_panic_negative :
        logging.info('Selling all for stop loss')
        result = sell_all()
        logging.info('sell_all:')
        logging.info('result')
        #topup_bnb(0.5, 0.5)
        f = open(filename, "w")
        logging.info('Writing new total balance into %s', filename)
        f.write(str(truncate(total_balance_without_reserved, 0)))
        f.close()
        logging.info('new initial_balance written into %s', filename)

    if total_balance >= 25000.0 :
        logging.info('Selling all for 25000 profit')
        result = sell_all(True)
        f = open(filename, "w")
        logging.info('Writing new total balance into %s', filename)
        f.write(str(truncate(total_balance, 0)))
        f.close()
        logging.info('new initial_balance written into %s', filename)

    total_invested_without_reserved = total_balance_without_reserved - usdt_value
    percentage_invested = total_invested_without_reserved / total_balance_without_reserved * 100
    #logging.info('total_balance_without_reserved %s', total_balance_without_reserved)
    #logging.info('usdt_value %s', usdt_value)
    #logging.info('total_invested_without_reserved %s', total_invested_without_reserved)
    #logging.info('percentage_invested %s', percentage_invested)
    if n_currencies>0:
        percentage_per_currency = percentage_invested / n_currencies
    #logging.info('n_currencies %s', n_currencies)
    #logging.info('percentage_per_currency %s', percentage_per_currency)
        
    # if percent < 0.0 :
    #     logging.info('with negative percentage downgrade initial_balance to new value of: %s', str(total_balance))
    #     f = open(filename, "w")
    #     f.write(str(truncate(total_balance, 0)))
    #     f.close()
    #     logging.info('new initial_balance written into %s', filename)

    logging.info('-----------------')
    resp = {"code": "success","message": percent_for_total_balance_without_reserved} 
    return jsonify(resp)
  • Put in it a config.py file where in it you will store:
    WEBHOOK_PASSPHRASE = "A SECRET PASS PHRASE OF YOUR CHOICE"
    API_KEY = "[YOUR BINANCE API KEY]"
    API_SECRET = "[YOUR BINANCE SECRET API KEY]"
  • In the same directory put a some textual file:
    1. reserved.txt (in which you will put coin not effected by sell_all separated by commas);
    2. requirements.txt in which you will put:
          flask
          gunicorn
          python-binance
    3. a file called ten_percent.txt in which put the current amount of your USDT invested into Binance;
    4. a file called ten_percent_actual.txt in which put the last checked USDT amount;
    5. a file called percentage_for_panic.txt in which put a number like 5.0 (that means 5%);
    6. a file called percentage_for_panic_negative.txt put a negative percentage below which all will be sand (just in case. I setted it to -150.0 in order to not activate it). 7. create three template files in /var/www/binance/app/templates called:       index.html
          index_sum.html
          result.html
  • In the /home/pi directory create a file called bianance_flask.sh in which put this:
    cd /var/www/binance/app/
    /home/pi/.local/bin/gunicorn --reload -w 4 --threads=3 --timeout 360 -b 0.0.0.0:5000 app:app --reload-extra templates/result.html
    
    cd /home/pi/
    java -jar binance_flask.jar
    
  • And last but not least put the jar file generated with the next java code in /home/pi directory in order to run a monitor server:
package binanceServerFlask;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;


import com.google.gson.JsonObject;
import com.google.gson.JsonParser;




public class Test {
	private static HttpURLConnection con;
	
	public static void main(String[] args) {
		
		var url = "http://[YOUR_RASPBERRY_IP_ADDRESS IN YOUR LAN]:5000/check_balance_ten_percent";
 		var urlParameters = "passphrase=[YOUR WEBHOOK PASS PHRASE IN PYTHON SCRIPT]&ticker=PANIC_BUTTON";
 		byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);

 		try {
			var myurl = new URL(url);
			con = (HttpURLConnection) myurl.openConnection();

			con.setDoOutput(true);
			con.setRequestMethod("POST");
			con.setRequestProperty("Content-Type", "application/json; utf-8");
			//con.setRequestProperty("User-Agent", "Java client");
			con.setDoOutput(true);

			/*try (var wr = new DataOutputStream(con.getOutputStream())) {

			    wr.write(postData);
			}*/
            
			String jsonInputString = "{\n"
					+ "	\"passphrase\": \"[WEBHOOK_PASSPHRASE (the same used in the app.py script)]\",\n"
					+ "	\"time\": \"2021-02-14T18:24:01Z\",\n"
					+ "	\"exchange\": \"BINANCE\",\n"
					+ "	\"ticker\": \"PANIC_BUTTON\",\n"
					+ "	\"bar\": {\n"
					+ "		\"time\": \"2021-02-14T18:24:00Z\",\n"
					+ "		\"open\": 0.05551,\n"
					+ "		\"high\": 0.05551,\n"
					+ "		\"low\": 0.05551,\n"
					+ "		\"close\": 0.05551,\n"
					+ "		\"volume\": 194777.80114775\n"
					+ "	},\n"
					+ "	\"strategy\": {\n"
					+ "		\"position_size\": 10000,\n"
					+ "		\"order_action\": \"SELL\",\n"
					+ "		\"order_contracts\": 1382,\n"
					+ "		\"order_price\": 0.07651,\n"
					+ "		\"order_id\": \"door\",\n"
					+ "		\"market_position\": \"long\",\n"
					+ "		\"market_position_size\": 10000,\n"
					+ "		\"prev_market_position\": \"flat\",\n"
					+ "		\"prev_market_position_size\": 0\n"
					+ "	}\n"
					+ "}";
            
            try(OutputStream os = con.getOutputStream()) {
                byte[] input = jsonInputString.getBytes("utf-8");
                os.write(input, 0, input.length);			
            }
            
            
            StringBuilder content;

            try (var br = new BufferedReader(
                    new InputStreamReader(con.getInputStream()))) {

                String line;
                content = new StringBuilder();

                while ((line = br.readLine()) != null) {
                    content.append(line);
                    content.append(System.lineSeparator());
                }
            }

            System.out.println(content.toString());

            JsonObject jsonObjectAlt = JsonParser.parseString(content.toString()).getAsJsonObject();
            
            System.out.println(jsonObjectAlt.get("message"));
            
        } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

            con.disconnect();
        }

	}

}

  • Finally in your crontab -e put those lines:
          @reboot cd /home/pi & ./binance_flask.sh
          */5 * * * * cd /home/pi & ./binance_flask.sh

The Bitcoin price is now: USD 26,938.80 - GBP 22,509.84 - EUR 26,242.32

Bitcoin performed good in the last 10 days (0.64%) and bad (-1.26%) in the last five days. Also now BTC is performing bad (-0.72%) from the yesterday close.
nothing to say

Current EMA8: 27236.44, Current EMA24: 24995.89
Previous EMA8: 27321.12, Previous EMA24: 24826.84
Ema8 is over Ema24 so it's better to buy assets and if you have any asset it suggest to buy it again.

Binance will list these coins soon for trading:

Arbitrum (ARB)

List of some existing crypto:

PHT, DMLG, XDEFI, BOS, AUC, AAB, TOWN, KICK, FTRB, TANK, ITF, TTT, HLT, OLOID, FUJIN, TRR, CORGI, SCAT, VIPS, WLITI, POINTS, BTSC, ELIX, FOXF, DNS, MTEL, MV, PSM, XIDO, UBT, EBASE, EVMOS, GREENT, COLLG, SPI, PFID, XFI, COVA, CPD, LST, WAIF, PINK, UGAS, RMESH, LAIKA, YARL, XTK, AZART, BTCH, JST, DRKT, STAKE, REA, JVY, ZONO, ETZ, ZNY, GRON, NAOS, RCOIN, UNIC, PIB, XCF, CLT, EFL, JSE, PON, MAC, XPY, LAVA, LAMB, NXMC, DBTN, ECOREAL, MAEP, KSTT.BITCI, MIST, RAVEN, AION, ATMOS, CSNO, BTCB, VBK, PART, BDG, ROSE, PRARE, 3ULL, INTO, LOOTEX, BLP, VME, XAVA, YTN, BONES, BITCRATIC, JOYS, MGPT, OTO, SOP [...]