Visualizzazione post con etichetta binance. Mostra tutti i post
Visualizzazione post con etichetta binance. Mostra tutti i post

mercoledì 26 agosto 2020

PYTHON - MA and BOOKORDER SCALPING


Scalping signal indicator written in python. It is based on Binance data.
The simpleBinanceFut.py module can be downloaded from GitHub.
https://github.com/DanielePorcari/simpleBinanceFutures

import simpleBinanceFut as sBF

def MA(dati,periodo):
    ris=0
    i=len(dati)-1
    for c in range(periodo):
        if i>=periodo:
            prezzo=(float(dati[i][4]))
            ris=ris+prezzo
            i-=1
    ris=ris/periodo
    return ris

def bookBot(up):
    volMax=0
    priceMax=0
    if up:
        for i in range(len(book['bids'])):
            price=float(book['bids'][i][0])
            vol=float(book['bids'][i][1])
            if float(vol)>float(volMax):
                volMax=vol
                priceMax=price
        print("Buy: ",priceMax)
        volMax=0
        priceMax=0
        for i in range(len(book['asks'])):
            price=book['asks'][i][0]
            vol=book['asks'][i][1]
            if float(vol)>float(volMax):
                volMax=vol
                priceMax=price
        print("TP: ",priceMax)
    else:
        for i in range(len(book['asks'])):
            price=float(book['asks'][i][0])
            vol=float(book['asks'][i][1])
            if float(vol)>float(volMax):
                volMax=vol
                priceMax=price
        print("Sell: ",priceMax)
        volMax=0
        priceMax=0
        for i in range(len(book['bids'])):
            price=book['bids'][i][0]
            vol=book['bids'][i][1]
            if float(vol)>float(volMax):
                volMax=vol
                priceMax=price
        print("TP: ",priceMax)

coppia=input("Insert asset: ")
print("Last price: ",sBF.fbin_ultimo_prezzo(coppia))
tf=input("Insert tf:")
book=sBF.fbin_book(coppia)
prezzi=sBF.fbin_candlestick(coppia,tf,"99")
ma9=MA(prezzi,50)
ma25=MA(prezzi,25)
if ma9>ma25:
    up=True
else:
    up=False
bookBot(up)

martedì 12 maggio 2020

PYTHON - AI SEE THE GRAPHIC PATTERNS

A prototype script that "sees" the configuration of graphic patterns. For now it only works on the pattern cup.
Download the data from Binance, draw the price line and compare it with the standard cup image.

#Riconoscimento pattern grafici tramite AI
#Porcari Daniele's code

from PIL import Image, ImageFilter
import imagehash
import matplotlib.pyplot as plt
import requests
import json

def binanceList(coppia,intervallo,limite):
    coppia=coppia.upper()
    indirizzo='https://fapi.binance.com/fapi/v1/klines?symbol='+coppia+'&interval='+intervallo+'&limit='+limite
    r=requests.get(indirizzo)
    file=r.text
    lista=json.loads(file)
    x=[]
    y=[]
    for i in range(len(lista)):
        x.append(lista[i][0])
        y.append(float(lista[i][4]))
    return x,y

def disegnaGrafico(x,y,asset):
    ok=False
    fig=plt.figure(figsize=(14,14))
    plt.plot(x,y,color='black')
    nome=asset+".png"
    plt.savefig(nome)
    return nome

def togliCornice(immagine,asset):
    ok=False
    img=Image.open(immagine)
    w,h=img.size
    l=180
    t=172
    r=w-159
    b=h-163
    nome=asset+"pronta.png"
    img.crop((l, t, r, b)).save(nome)
    img.close()
    return nome

def confronto(attuale,base,base2):
    tazza=True
    img = Image.open(base)
    image_one_hash = imagehash.whash(img)
    img2 = Image.open(attuale)
    image_two_hash = imagehash.whash(img2)
    similarity = image_one_hash - image_two_hash
    img.close()
    if similarity>20:
        img=Image.open(base2)
        image_one_hash = imagehash.whash(img)
        similarity2 = image_one_hash - image_two_hash
        if similarity>similarity2:
            similarity=similarity2
        tazza=False
    img.close()
    img2.close()
    return similarity,tazza

def confrontoTestaSpalle():
    ok=False
    return ok


linea=['BTCUSDT',
'LINKUSDT',
'BATUSDT',
'VETUSDT',
'TRXUSDT',
'ETHUSDT',
'BCHUSDT',
'LTCUSDT',
'XRPUSDT',
'EOSUSDT',
'ETCUSDT',
'XTZUSDT',
'BNBUSDT',
'ADAUSDT',
'NEOUSDT',
'XLMUSDT',
'DASHUSDT',
'ZECUSDT',
'XMRUSDT',
'ATOMUSDT',
'ONTUSDT',
'IOTAUSDT',
'QTUMUSDT',
'IOSTUSDT']

for i in range(len(linea)):
    print(linea[i])
    x,y=binanceList(linea[i],'4h','50')
    nomeGraf=disegnaGrafico(x,y,linea[i])
    grafOk=togliCornice(nomeGraf,linea[i])
    similarity,cup=confronto(grafOk,'tazza.png','tazza2.png')
    if cup==True:
        print("Possibile tazza ",similarity," - ",linea[i])
    else:
        print(similarity," - ",linea[i])

Copy and save the following images with the name of: cup.png and cup2.png
If you like the blog remember that you can support my work by donating cryptocurrencies to the addresses at the top right or at this link go fund me. 



domenica 3 maggio 2020

PYTHON - SIMPLE BINANCE FUTURES API

The Binance Futures API returned data as strings, and it was unmanageable (at least for me) so I wrote this form which returns the responses of the Binance Futures API in lists and dictionaries. 
You can use this module without logging in to Binance. I hope you find it useful.


#Porcari Daniele https://danieleporcaripython.blogspot.com
#Simple Binance Futures API for Python
import requests
import json

def fbin_ultimo_prezzo(coppia):
    coppia=coppia.upper()
    indirizzo='https://fapi.binance.com/fapi/v1/ticker/price?symbol='+coppia
    r=requests.get(indirizzo)
    file=r.text
    prezzo=json.loads(file)
    return prezzo['price']

def fbin_book(coppia):
    coppia=coppia.upper()
    indirizzo='https://fapi.binance.com/fapi/v1/depth?symbol='+coppia
    r=requests.get(indirizzo)
    file=r.text
    return json.loads(file)

def fbin_scambi24H(coppia,limite):
    coppia=coppia.upper()
    indirizzo='https://fapi.binance.com/fapi/v1/depth?symbol='+coppia+'&limit='+limite
    r=requests.get(indirizzo)
    file=r.text
    return json.loads(file)

def fbin_candlestick(coppia,intervallo,limite):
    coppia=coppia.upper()
    indirizzo='https://fapi.binance.com/fapi/v1/depth?symbol='+coppia+'&interval='+intervallo+'&limit='+limite
    r=requests.get(indirizzo)
    file=r.text
    return json.loads(file)

def fbin_prezzomercato(coppia):
    coppia=coppia.upper()
    indirizzo='https://fapi.binance.com//fapi/v1/premiumIndex?symbol='+coppia
    r=requests.get(indirizzo)
    file=r.text
    return json.loads(file)

def fbin_24h_statisticheprezzo(coppia):
    coppia=coppia.upper()
    if coppia=='NONE':
        indirizzo='https://fapi.binance.com/fapi/v1/ticker/24hr'
    else:
        indirizzo='https://fapi.binance.com/fapi/v1/ticker/24hr?symbol='+coppia
    r=requests.get(indirizzo)
    file=r.text
    return json.loads(file)

def fbin_book_migliorprezzo(coppia):
    coppia=coppia.upper()
    indirizzo='https://fapi.binance.com//fapi/v1/ticker/bookTicker?symbol='+coppia
    r=requests.get(indirizzo)
    file=r.text
    return json.loads(file)

giovedì 23 aprile 2020

PYTHON - IA TRADING CONVERGENCE MACD

This AI is done to find convergences between MACD and prices. 
Work on Binance's SPOT databases. 
You can enter the data manually; decide to make the program work on a pre-set text file; can understand the trend automatically.

You can choose the analysis on three time frames: DAY, 4 hour and 30 minute. 
This program is open source and licensed under GNUGPL v.3. 
Together with the automatic PIVOT POINT program it can be a useful and daily support for your trading strategies.
If you want you can support my works by donating BTC, BAT or LINK or by going to this link.
Download divMacd

venerdì 17 aprile 2020

PYTHON BINANCE API TRADING IA - EXAMPLE

What is an AI BOT trading? It's a software that trades for you. We must build the logic of the trading system.

If you want to help me you can choose to send me crypto currencies to my addresses indicated on the right of the blog or make a donation on gofundme.
This is a very trivial example of AI for trading. It is based only on book order volumes and two moving averages over a 5 minute time frame. 
I am developing algorithms for the recognition of graphic patterns, the management of the MACD (an example of MACD is already present in this blog). 
The function of the Pivot Point is already automated: my Pivot Point algorithm decides which is the right candle from which to extrapolate all the resistances and supports as well as the p.p.(.exe program for Windows here).

from binance.client import Client
from binance.enums import *
import string
import time
import dateparser
import sys

def accesso():
    f=open('chiavi.dat','r') #text file : pubblicAPIkey-privateAPIkey
    rawkeys=f.read()
    f.close()
    k=rawkeys.split('-')
    cl=Client(api_key=k[0], api_secret=k[1])
    return cl

def ultimoPrezzo(cl,coppia):
    lP=0.0
    while True:
        try:
            vPrz=cl.get_all_tickers()
            break
        except:
            print("Ticker connection - error")
    for i in range(len(vPrz)):
        if vPrz[i]['symbol']==coppia.upper():
            lP=vPrz[i]['price']
    return lP

def verificaTF(cl,tf):
    ok=False
    while True:
        try:
            t = cl.get_server_time()
            break
        except:
            print("Server Time Error")
    ms=str(t['serverTime'])
    data=dateparser.parse(ms)
    data=str(data)
    oD=data.split(" ")
    orario=oD[1].split(":")
    if tf=='4H':
        i=0
        d=4
    elif tf=='30M':
        i=1
        d=30
    elif tf=='15M':
        i=1
        d=15
    elif tf=='5M':
        i=1
        d=5
    resto=float(orario[i])%d
    if resto==0 and (int(orario[2])==0):
        ok=True
        time.sleep(10)
    return ok,oD[1]

def book(cl,cp):
    bidsPrice=[]
    asksPrice=[]
    while True:
        try:
            libro = cl.get_order_book(symbol=cp.upper())
            break
        except:
            print("book connection - error")
    for i in range(len(libro)):
        sumBidsVol=float(libro['bids'][i][1])
        sumAsksVol=float(libro['asks'][i][1])
    for i in range(30):
        bidsPrice.append(float(libro['bids'][i][0]))
        asksPrice.append(float(libro['asks'][i][0]))
    return bidsPrice, asksPrice,sumBidsVol,sumAsksVol

def MA(dati,periodo):
    prezzi=[]
    for i in range(len(dati)):
        prezzi.append(float(dati[i]))
    ris=0
    for i in range(periodo):
        ris=ris+prezzi[i]
    ris=ris/periodo
    return ris

def recuperoPrezzi(cl,coppia):
    vPrezzi=[]
    while True:
        try:
            vTot=cl.get_klines(symbol=coppia.upper(), interval=Client.KLINE_INTERVAL_5MINUTE)
            break
        except:
            print("kLines errore")
    for i in range(len(vTot)):
        vPrezzi.append(vTot[i][4])
    return vPrezzi

def main(coppia,diff):
    cl=accesso()
    vP=recuperoPrezzi(cl,coppia)
    buy=False
    sell=False
    inOp=False
    while True:
        stampa,ora=verificaTF(cl,'5M')#5M 15M 30M 4H
        prezzo = ultimoPrezzo(cl,coppia)
        if stampa:
            print("Prezzo ",prezzo," - ",ora)
            ma3=MA(vP,3)
            ma14=MA(vP,14)
            print("MA3 ",ma3,"\nMA14 ",ma14)
            vP.append(prezzo)
            bidsP,asksP,sumBV,sumAV=book(cl,coppia)#asset name
            f=open("dati.dat","a")
            stringa=str(prezzo)+","+str(ma3)+","+str(ma14)+","+str(ora)+"\n"
            f.write(stringa)
            f.close()
            if ((float(sumBV)-float(sumAV)) > 0) and (ma3>ma14) and not(inOp):
                print("BUY ",prezzo," ",ora)
                prezzoB=prezzo
                buy=True
                inOp=True
                sell=False
            elif ((float(sumBV)-float(sumAV)) < 0) and (ma3<ma14) and not(inOp):
                prezzoS=prezzo
                print("SELL ",prezzo," ",ora)
                buy=False
                inOp=True
                sell=True
        if buy:
            prezzo=ultimoPrezzo(cl,coppia)
            if float(prezzo)>(float(prezzoB)+float(diff)) :
                print("Preso Buy ",prezzoB," ",prezzo," ",ora)
                f=open("operazioni.dat","a")
                stringa="Prezzo Buy "+str(prezzoB)+" uscita: "+str(float(prezzoB)+float(diff))+"\n"
                f.write(stringa)
                f.close()
                buy=False
                inOp=False
        if sell:
            prezzo=ultimoPrezzo(cl,coppia)
            if float(prezzo)<(float(prezzoS)-float(diff)):
                print("Preso sell ",prezzoS," ",prezzo," ",ora)
                f=open("operazioni.dat","a")
                stringa="Prezzo Sell "+str(prezzoS)+" uscita: "+str(float(prezzoS)-float(diff))+"\n"
                f.write(stringa)
                f.close()
                sell=False
                inOp=False
#name asset takeprofit
main(sys.argv[1],sys.argv[2])

Sorry, alittle mistake in def MA: replace this with the one in the main listing.
def MA(dati,periodo):
    ris=0
    i=len(dati)-1
    for c in range(periodo):
        prezzo=(float(dati[i]))
        ris=ris+prezzo
        i-=1
    ris=ris/periodo
    return ris

PYTHON - BINANCE API - PRINT THE LATEST PRICE AT EACH TIME FRAME

This Python script print the last price for each time frame. 
TIME FRAME: 4H 30M 15M 5M
COUPLE: all those on spot Binance

from binance.client import Client
from twisted.internet import reactor
from binance.enums import *
import string
import time
import dateparser
import sys

def accesso():
    f=open('chiavi.dat','r') #text file : pubblicAPIkey-privateAPIkey
    rawkeys=f.read()
    f.close()
    k=rawkeys.split('-')
    cl=Client(api_key=k[0], api_secret=k[1])
    return cl

def ultimoPrezzo(cl,coppia):
    lP=0.0
    vPrz=cl.get_all_tickers()
    for i in range(len(vPrz)):
        if vPrz[i]['symbol']==coppia.upper():
            lP=vPrz[i]['price']
    return lP

def verificaTF(cl,tf):
    ok=False
    t = cl.get_server_time()
    ms=str(t['serverTime'])
    data=dateparser.parse(ms)
    data=str(data)
    oD=data.split(" ")
    orario=oD[1].split(":")
    if tf=='4H':
        i=0
        d=4
    elif tf=='30M':
        i=1
        d=30
    elif tf=='15M':
        i=1
        d=15
    elif tf=='5M':
        i=1
        d=5
    resto=float(orario[i])%d
    if resto==0 and (int(orario[2])==0):
        ok=True
        time.sleep(10)
    return ok,oD[1]

client=accesso()
while True:
    stampa,ora=verificaTF(client,sys.argv[2])#5M 15M 30M 4H
    if stampa:
        prezzo = ultimoPrezzo(client,sys.argv[1])#asset name
        print(prezzo," ",ora)

You must make a text file containing: public key API binance (dash) -private key API binance. You don't have to type send at the end of the line. You have to save it as: chiavi.dat .
This program is part of the next AI Signal Bot that I am programming.

martedì 14 aprile 2020

PYTHON - TELEGRAM IA TRADING SIGNAL INDICATOR CRYPTOCOINS -

The first BOT written in Python for Telegram is ready. Currently it communicates the trend of the couple, the pivot point with graph, and the maximum lows (in the test phase). 
 If you want to be inserted in the Telegram channel you can write me an email. 
If you want to help me you can support me with gofundme, or by sending me BTC, BAT or LINK to the addresses on the side. 
Send me an email for more information. 
I hope soon to be able to leave the BOT active 24 hours a day 7 days a week. The next features will be: entry and exit prices for scalping, recognition of graphic patterns such as cup and head and shoulders, recognition of differences. 
Here is the list of the main program of the bot with the Telegram API.
import time
import telepot
from pprint import pprint
import trFunz
import utils
import os
import sys
import keys

def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    if content_type == 'text':
        txt=msg['text']
        if txt.startswith('/help'):
            bot.sendMessage(chat_id,'Bot analizzatore di trading su crypto valute presenti sull\'exchange Binance')
            help=utils.archivioR("txt/help.bot")
            bot.sendMessage(chat_id,help)
        if txt.startswith('/email'):
            params=txt.split()
            if len(params) == 1:
                bot.sendMessage(chat_id,'Ti saranno inviate email con segnali di trading sulla coppia voluta\n/email  ')
            else:
                try:
                    dati=params[1]+","+params[2]+"\n"
                    utils.archivio('txt/email.bot','a',dati)
                    bot.sendMessage(chat_id,'Eseguito')
                except:
                    bot.sendMessage(chat_id,'Errore nel passaggio dei parametri')
        if txt.startswith('/pivot'):
            params = txt.split()
            if len(params) == 1:
                bot.sendMessage(chat_id, 'Uso: /pivot    Calcola il Pivot Point in automatico  DAY/4H')
            else:
                try:
                    client=utils.accesso()
                    print (params[1])
                    print (params[2])
                    coppia=params[1].upper()
                    periodo=int(params[2])
                    tf=params[3].upper()
                    print(tf)
                    bot.sendMessage(chat_id,(trFunz.calcPP(client,coppia,periodo,tf)))
                    bot.sendPhoto(chat_id, photo=open('img/pp.png', 'rb'))
                except:
                    bot.sendMessage(chat_id, 'Errore nei parametri')
        if txt.startswith('/trend'):
            params = txt.split()
            if len(params) == 1:
                bot.sendMessage(chat_id,'Uso: /trend   rileva il trend con le medie mobili')
            else:
                try:
                    client=utils.accesso()
                    coppia=params[1].upper()
                    term=params[2].upper()
                    trend=trFunz.scopriTrend(client,coppia,term,200)
                    trend=coppia+" "+trend
                    bot.sendMessage(chat_id,trend)
                except:
                    bot.sendMessage(chat_id,'Errore nei parametri')
        if txt.startswith('/ph'):
            bot.sendPhoto(chat_id, photo=open('img/test.png', 'rb'))
        if txt.startswith('/mm'):
            params = txt.split()
            if len(params) == 1:
                bot.sendMessage(chat_id,'Uso: /mm      Trova i massimi ed i minimi nel periodo n.giorni indicato. MAXVAL: il valore di soglia sotto il quale si vogliono trovare i minimi oppure per scelta automatica digitare \'a\'. N.DEC numero di decimali desiderati dopo la virgola.\nACorHL: 0 per lavorare su prezzi apertura/chiusura, 1 per lavorare su prezzi high/low')
            else:
                try:
                    client=utils.accesso()
                    giorni=int(params[1])
                    print(giorni)
                    coppia=params[2].upper()
                    print(coppia)
                    maxval=params[3]
                    print(maxval)
                    ndec=params[4]
                    print(ndec)
                    ACHL=int(params[5])
                    vMax,vmin=trFunz.minemax(client,giorni,coppia,maxval,ndec,ACHL)
                    bot.sendMessage(chat_id,'Massimi:'+str(vMax))
                    bot.sendMessage(chat_id,'Minimi:'+str(vmin))
                except:
                    bot.sendMessage(chat_id,'Errore nei parametri')

TOKEN = keys.Token
bot = telepot.Bot(TOKEN)
response = bot.getUpdates()
pprint(response)
bot.message_loop(handle)
print ('Listening ...')
while 1:
    time.sleep(20)

sabato 11 aprile 2020

PYTHON BINANCE API - HOW TO MAKE: A LIST OF SMA and MACD

This little python script uses the Binance API.
The customer position is opened to access the data.
Data on the chosen pair are retrieved in the chosen time frame.
The moving average vector is constructed.
The macd vector is constructed.
The macd vector is drawn.
As always if you like the blog you can help me by going on by donating BTC, Link, BAT or by donating through gofundme.
from binance.client import Client
from twisted.internet import reactor
from binance.enums import *
import matplotlib.pyplot as plt
import dateparser

def recuperoDati(coppia,tf):
    f=open('chiavi.dat')
    #esempio di chiavi.dat file: chiavepubblicabinance-chiaveprivatabinance
    #tra le due chiavi deve esserci '-' senza spazi, alla fine della riga non
    #deve essere battuto invio
    rawkeys=f.read()
    f.close()
    k=rawkeys.split('-')
    client=Client(api_key=k[0], api_secret=k[1])
    if tf=='DAY':
        rawData=client.get_klines(symbol=coppia, interval=client.KLINE_INTERVAL_1DAY)
    elif tf=='4H':
        rawData=client.get_klines(symbol=coppia, interval=client.KLINE_INTERVAL_4HOUR)
    elif tf=='30M':
        rawData=client.get_klines(symbol=coppia, interval=client.KLINE_INTERVAL_30MINUTE)
    elif tf=='15M':
        rawData=client.get_klines(symbol=coppia, interval=client.KLINE_INTERVAL_15MINUTE)
    elif tf=='5M':
        rawData=client.get_klines(symbol=coppia, interval=client.KLINE_INTERVAL_5MINUTE)
    return rawData

def vettoreMA(dati,periodo):
    itad=[]
    vMediaINV=[]
    mediaFinale=[]
    i=len(dati)
    c=0
    prov=0
    conta=0
    while i >0 :
        itad.append(dati[c])
        c+=1
        i-=1
    long1=len(itad)//int(periodo)
    for i in range(len(itad)-int(periodo)):
        for c in range(periodo):
            prov=float(itad[i+c][4])+prov
        vMediaINV.append(prov/periodo)
        prov=0
    i=len(vMediaINV)
    c=0
    while i >0:
        mediaFinale.append(vMediaINV[c])
        c+=1
        i-=1
    return mediaFinale

def vettoreMACD(mediasmall,mediabig):
    macd=[]
    for i in range(len(mediabig)):
        macd.append(mediabig[i]-mediasmall[i])
    return macd

def asseX(l,dati):
    x=[]
    for i in range(l):
        data=dateparser.parse(str(dati[i][0]))
        data=str(data)
        oD=data.split(" ")
        x.append(oD[0])
    return x

rawData=recuperoDati('BATUSDT','DAY')
ms=vettoreMA(rawData,12)
mb=vettoreMA(rawData,26)
macd=vettoreMACD(ms,mb)
x=asseX(len(macd),rawData)
fig=plt.figure(figsize=(20,17))
plt.plot(x, macd, color = 'black')
plt.show()

giovedì 9 aprile 2020

PYTHON API BINANCE - IA - PIVOT POINT AUTOMATIC -

BOT trading for crypto currencies based on Binance API. The pivot point is automatically calculated on the last important candle of the selected time frame, over the chosen days. The candle is selected based on its amplitude and volume. The results are printed on the monitor and on a graph.


BOT di trading per crypto valute basato su Binance API. Il pivot point viene calcolato in automatico sull'ultima candela importante del time frame selezionato, nell'arco dei giorni scelti. La candela viene selezionata in base all'ampiezza e il volume. I risultati sono stampati a monitor e su grafico.


You can download the zip of the executable file on windows from this link
Puoi scaricare lo zip del file eseguibile su windows da questo link:  Pivot Calc






sabato 4 aprile 2020

PYTHON - API BINANCE: BUY/SELL AUTOMATICO

Potete scaricare il pacchetto zippato dei sorgenti da qui
Per utilizzarlo bisogna avere PYTHON installato insieme alle API BINANCE
Se vuoi sapere come installare python e API Binance lascia un commento.

Cosa fa questo script?
Al momento l'exchange Binance, sulla parte SPOT, non permette di settare dei take profit automatici, quindi questo script, sulle tue indicazioni di prezzo e quantità, piazza l'ordine e una volta eseguito piazza il contr'ordine di pari quantità.

Esempio:
voglio comprare sulla coppia BTC/USDT una quantità di BTC pari a 0.01 al volore
di 6000 USDT e rivendere la stessa quantità a 6100 USDT

> Coppia: btcusdt
> Ordine[BUY] or [SELL]: buy
> Prezzo di ingresso: 6000
> Prezzo di uscita: 6100
> Quantità: 0.01

fatto questo lo script piazza l'ordine, una volta che l'ordine è FILLED,
piazza l'ordine inverso, nel nostro caso un sell limit, e manda una email.
Perchè tutto funzioni correttamente il programma deve rimanere connesso al
server Binance.

Ricorda, se ti piace DONA e condividi il mio blog




martedì 31 marzo 2020

PYTHON - TRASFORMAZIONE MILLI SECONDI IN DATA

PYTHON e BINANCE API
Binance rilascia le date in millisecondi, per renderle capibili basta importare dateparser.
File di esempio

from binance.client import Client
from binance.enums import *
import sys
import keys #un file contenente le chiavi Binance Pkeys la pubblica / Skeys la privata
import dateparser #per il parsing della data
'''
Trasformazione dei milli secondi in data e ora umanamente
capibili
'''
client=Client(api_key=keys.Pkeys, api_secret=keys.Skeys)
v=client.get_klines(symbol=sys.argv[1], interval=client.KLINE_INTERVAL_1DAY)
for i in range(len(v)):
    data=dateparser.parse(str(v[i][0]))#passaggio del valore in millisecondi
    data=str(data)#trasformo il tutto in stringa
    oD=data.split(" ")#splitto la stringa con lo spazio
    #oD è una lista composta da oD[0] e oD[1]
    print(oD[0],v[i][1],v[i][4])

L'esempio qui sopra riportato funziona solo se avete le chiavi per le API Binance.