Neste vídeo vamos explicar como monitoras múltiplas cripto moedas por meio de um script em Python e enviar notificação pelo telegram
keys.py
# BINANCE
API_KEY = 'XXXXXXXXXXXXXXXXXXX'
API_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
# TELEGRAM
TOKEN = "XXXXXXXXXXXXXXXXXXXXX"
BOTCHATID = 'XXXXXXXXXXXXXXXXXXXXX'
config.py
#SYMBOLS = ['GALAUSDT','BNBUSDT','BTCUSDT','SOLUSDT','ADAUSDT','ETHUSDT','MANAUSDT','SANDUSDT','AXSUSDT']
#SYMBOLS = ['GALAUSDT','SOLUSDT','ADAUSDT','MANAUSDT','SANDUSDT','AXSUSDT']
#SYMBOLS = ['BNBUSDT']
SYMBOLS = ['BNBUSDT','BTCUSDT']
telegramMSF.py
import requests
import urllib.parse
import json
class BotTelegram:
def __init__(self,token,chatid):
pass
self.TOKEN = token
self.BOTCHATID = chatid
self.URL = "https://api.telegram.org/bot{}/".format(token)
def send_msg(self,msg):
safe_string = urllib.parse.quote_plus(msg)
send_text = self.URL + 'sendMessage?chat_id=' + self.BOTCHATID + '&parse_mode=Markdown&text=' + safe_string
response = requests.get(send_text)
return response.json()
multitrade1.py
#! /usr/bin/python3
# -*- coding: utf-8 -*-
import config
from binance.client import Client
import sys
import numpy as np
import pandas as pd
import asyncio
from binance import AsyncClient, BinanceSocketManager
from datetime import datetime
import keys
import telegramMSG as tlg
import talib
TIME_INTERVAL ='1m'
RSI_PERIOD = 7
RSI_OVERBOUGHT = 75
RSI_OVERSOLD = 30
RSIS_OVERBOUGHT = 80
RSIS_OVERSOLD = 25
def binanceDataFrame( klines):
# df = pd.DataFrame(klines.reshape(-1,12),dtype=float, columns = ('Open Time',
# 'Open',
# 'High',
# 'Low',
# 'Close',
# 'Volume',
# 'Close time',
# 'Quote asset volume',
# 'Number of trades',
# 'Taker buy base asset volume',
# 'Taker buy quote asset volume',
# 'Ignore'))
# df['Open Time'] = pd.to_datetime(df['Open Time'], unit='ms')
df = pd.DataFrame(klines.reshape(-1,12),dtype=float, columns=['T',
'open',
'high',
'low',
'close',
'V',
'CT',
'QV',
'N',
'TB',
'TQ',
'I'])
df['T'] = pd.to_datetime(df['T'], unit='ms')
return df
def get_timeInterval(ti,Client):
if ti == '1m':
return Client.KLINE_INTERVAL_1MINUTE
elif ti == '5m':
return Client.KLINE_INTERVAL_5MINUTE
elif ti == '1h':
return Client.KLINE_INTERVAL_1HOUR
elif ti == '4h':
return Client.KLINE_INTERVAL_4HOUR
elif ti == '1d':
return Client.KLINE_INTERVAL_1DAY
else:
return Client.KLINE_INTERVAL_15MINUTE
def removeExcedent(df,qtmanter):
if len(df) > qtmanter:
qt2remove = len(df) - qtmanter
df.drop(index=df.index[:qt2remove],
axis=0,
inplace=True)
return df
def createframe(msg):
df = pd.DataFrame([msg['data']])
return (df)
def on_message(message):
global klines_df, closes
TRADE_SYMBOL = message['s'][0]
candle = message['k'][0]
close = candle['c']
is_candle_closed = candle['x']
if is_candle_closed:
print(TRADE_SYMBOL+" \t"+str(candle['x'])+"\t"+str(datetime.fromtimestamp(int(candle['T'])/1000)))
df2 = pd.DataFrame({"T": [datetime.fromtimestamp(int(candle['T'])/1000)],
"open":[float(candle['o'])],
"high":[float(candle['h'])],
"low": [float(candle['l'])],
"close":[float(candle['c'])],
"V": [float(candle['v']) ],
"CT": [0],
"QV":[float(candle['q'])],
"N": [0],
"TB":[ 0],
"TQ": [0],
"I":[0]}
)
klines_df[TRADE_SYMBOL] = pd.concat([klines_df[TRADE_SYMBOL], df2])
klines_df[TRADE_SYMBOL] = removeExcedent(klines_df[TRADE_SYMBOL],30)
closes[TRADE_SYMBOL].append(float(close))
np_closes = np.array(closes[TRADE_SYMBOL])
if len(closes[TRADE_SYMBOL]) > 19 :
upper, middle, lower = talib.BBANDS(np_closes, 21, 2, 2)
if len(closes[TRADE_SYMBOL]) > 26:
macd, macdsignal, macdhist = talib.MACD(np_closes, fastperiod=12, slowperiod=26, signalperiod=9)
if len(closes[TRADE_SYMBOL]) > 21:
fastk, fastd = talib.STOCHRSI(np_closes,timeperiod=21, fastk_period=21, fastd_period=3, fastd_matype=3)
rsi = talib.RSI(np_closes, RSI_PERIOD)
last_rsi = rsi[-1]
print("CRYPTO :\t",TRADE_SYMBOL)
print("Closed value :\t",format(float(close),'.6f'))
print("RSI :\t",format(float(last_rsi),'.4f'))
print("RSI STOCK :\t",format(fastk[-1],'.2f'),format(fastd[-1],'.2f'))
print("macdhist :\t",format(macdhist[-1],'.5f'))
print("BBANDS :\t",format(float(upper[-1]),'.5f'),format(float(lower[-1]),'.5f'))
# telegram.send_msg("CRYPTO :\t"+TRADE_SYMBOL
# +"\nClosed value :\t"+format(float(close),'.6f')
# +"\nRSI :\t"+format(float(last_rsi),'.4f')
# +"\nRSI STOCK :\t"+format(fastk[-1],'.2f')+' ' +format(fastd[-1],'.2f')
# +"\nmacdhist :\t"+format(macdhist[-1],'.5f')
# +"\nBBANDS :\t"+format(float(upper[-1]),'.5f')+format(float(lower[-1]),'.5f'))
if (last_rsi > RSI_OVERBOUGHT and fastk[-1] > RSIS_OVERBOUGHT and fastd[-1] > RSIS_OVERBOUGHT) :
telegram.send_msg("---------- *VENDER {}* ------------".format(TRADE_SYMBOL)
+"\nClose value U$.............."+str(format(float(close),'.6f'))
+"\nRSI........................."+str(format(last_rsi,'.2f'))
+"\nRSI STOCH FASTK....."+str(format(fastk[-1],'.2f'))
+"\nRSI STOCH FASTD....."+str(format(fastd[-1],'.2f'))
+"\nmacdhist...................."+str(format(macdhist[-1],'.4f')))
if last_rsi < RSI_OVERSOLD and fastk[-1] < RSIS_OVERSOLD and fastd[-1] < RSIS_OVERSOLD:
telegram.send_msg("===============*COMPRAR {}*============".format(TRADE_SYMBOL)
+"\nClose value U$.............."+str(format(float(close),'.6f'))
+"\nRSI........................."+str(format(last_rsi,'.2f'))
+"\nRSI STOCH FASTK....."+str(format(fastk[-1],'.2f'))
+"\nRSI STOCH FASTD....."+str(format(fastd[-1],'.2f'))
+"\nmacdhist...................."+str(format(macdhist[-1],'.4f')))
async def main():
#inicializa o cliente
client = await AsyncClient.create()
# Instantiate a BinanceSocketManager, passing in the client that you instantiated
bm = BinanceSocketManager(client)
# Create a socket combining multiple streams.
ms = bm.multiplex_socket(multi)
# create listener using async with
async with ms as tscm:
while True:
res = await tscm.recv()
if res:
df = createframe(res)
on_message(df)
if __name__ == "__main__":
telegram = tlg.BotTelegram(keys.TOKEN,keys.BOTCHATID)
telegram.send_msg("Bot inicializdo")
client = Client(keys.API_KEY, keys.API_SECRET)
if len(sys.argv) > 1:
relevant = config.SYMBOLS
else:
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)]
relevant = [symbol for symbol in non_lev if symbol.endswith('USDT')]
multi = [i.lower() + '@kline_'+TIME_INTERVAL for i in relevant]
print(multi)
klines = dict()
closes = dict()
klines_df = dict()
klines_np = dict()
for i in relevant:
print("Carregando dados históricos de "+i)
klines[i] = client.get_historical_klines(i, get_timeInterval(TIME_INTERVAL,client), "1 day ago UTC")
closes[i] = []
for candles in range(len(klines[i])-1):
closes[i].append(float(klines[i][candles][4]))
klines_np[i] = np.array(klines[i])
klines_df[i] = binanceDataFrame(klines_np[i])
klines_df[i] = klines_df[i][:-1]
print(klines_df[i],len(klines_df[i]))
klines_df[i] = removeExcedent(klines_df[i],30)
# print(klines_df[i],len(klines_df[i]))
print("Monitorando....")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Comentários
Postar um comentário