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

domenica 25 febbraio 2024

Python Thread e animazione barretta di caricamento

Un programma in python che dimostra l'uso di Thread e l'animazione su prompt di una barretta che gira su se stessa.

import threading
import time

def animazione_barra(termina):
    while not termina.is_set():
        for char in '|/-\\':
            print('\r' + char, end='', flush=True)
            time.sleep(0.1)

def conteggio_numeri(termina):
    for i in range(1, 11):
        print(f'\r {i}', end='', flush=True)
        time.sleep(1)
    
    termina.set()

if __name__ == '__main__':
    termina_animazione = threading.Event()
    
    thread_animazione = threading.Thread(target=animazione_barra, args=(termina_animazione,))
    thread_conteggio = threading.Thread(target=conteggio_numeri, args=(termina_animazione,))
    
    thread_animazione.start()
    thread_conteggio.start()
    
    thread_animazione.join()
    thread_conteggio.join()

domenica 6 agosto 2023

Grafico MACD e prezzo


import requests
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from datetime import datetime

def get_binance_data(symbol, interval, limit):
    url = f"https://api.binance.com/api/v3/klines?symbol={symbol}&interval={interval}&limit={limit}"
    response = requests.get(url)
    data = response.json()
    df = pd.DataFrame(data)
    df.columns = ['timestamp', '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['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
    df['close'] = df['close'].astype(float)
    return df

def calculate_moving_average(data, window):
    return data['close'].rolling(window=window).mean()

def calculate_macd(data, fast_period, slow_period, signal_period):
    macd = data['close'].ewm(span=fast_period, adjust=False).mean() - data['close'].ewm(span=slow_period, adjust=False).mean()
    signal = macd.ewm(span=signal_period, adjust=False).mean()
    histogram = macd - signal
    return macd, signal, histogram

def plot_chart(data, ma_50, ma_99, macd, signal, histogram):
    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(12, 8))

    ax1.plot(data['timestamp'], data['close'], label='Close')
    ax1.plot(data['timestamp'], ma_50, label='MA 50')
    ax1.plot(data['timestamp'], ma_99, label='MA 99')
    ax1.legend()

    ax2.plot(data['timestamp'], macd, label='MACD')
    ax2.plot(data['timestamp'], signal, label='Signal')
    ax2.bar(data['timestamp'], histogram, label='Histogram', color='gray')
    ax2.legend()

    plt.xlabel('Timestamp')
    plt.show()

symbol = 'BTCUSDT'
interval = '1d'
limit = 500

data = get_binance_data(symbol, interval, limit)
ma_50 = calculate_moving_average(data, 50)
ma_99 = calculate_moving_average(data, 99)
macd, signal, histogram = calculate_macd(data, 12, 26, 9)

plot_chart(data, ma_50, ma_99, macd, signal, histogram)

domenica 30 luglio 2023

Calcolo pivot point in automatico

Questa funzione Python trova la candela
 importante nel dataframe DF e ne 
calcola il Pivot Point e le due
 resistenze e due supporti.

def pivot_point(df):
        pp=0
        r1=0
        r2=0
        s1=0
        s2=0
        ppa=[]
        r1a=[]
        r2a=[]
        s1a=[]
        s2a=[]
        dd=30
        c=0
        important_cand=0
        for i in range(len(df)):
            comp_cand=abs(df['open'][i]-df['close'][i])
            if comp_cand>important_cand:
                important_cand=comp_cand
                nci=i
            pp=(df['high'][nci]+df['low'][nci]+df['close'][nci])/3
            ppa.append(pp)
            r1=(pp*2)-df['low'][nci]
            r1a.append(r1)
            r2=pp+(df['high'][nci]-df['low'][nci])
            r2a.append(r2)
            s1=(pp*2)-df['high'][nci]
            s1a.append(s1)
            s2=pp-(df['high'][nci]-df['low'][nci])
            s2a.append(s2)
            c+=1
            if (df['close'][i]>r2) | (df['close'][i]<s2) | (df['open'][i]>r2) | (df['open'][i]<s2): #il prezzo è fuori dai dati pp azzera la candela importante
                important_cand=0
        df['pp']=ppa
        df['r1']=r1a
        df['r2']=r2a
        df['s1']=s1a
        df['s2']=s2a
        return df
DF deve contenere i campi open, close,
 high, low

sabato 29 luglio 2023

GPL3 e altre licenze

 Ecco un elenco di alcuni pacchetti Python con licenze diverse da GPL:


1. Requests: Licenza Apache 2.0

2. NumPy: Licenza BSD

3. Pandas: Licenza BSD

4. Matplotlib: Licenza BSD

5. Django: Licenza BSD

6. Flask: Licenza BSD

7. TensorFlow: Licenza Apache 2.0

8. Keras: Licenza MIT

9. Scikit-learn: Licenza BSD

10. SQLAlchemy: Licenza MIT

11. BeautifulSoup: Licenza MIT

12. Pygame: Licenza LGPL

13. PyTorch: Licenza BSD

14. OpenCV: Licenza BSD

15. PyQT: Licenza GPL con un'opzione commerciale


Ci sono diverse licenze compatibili con la GPL3, che permettono di distribuire il software sotto termini diversi ma ancora compatibili con la GPL3. Alcune di queste licenze includono:


- Licenza MIT: è una licenza permissiva che permette la distribuzione e la modifica del software, ma richiede solo l'inclusione del copyright e della licenza originale. È compatibile con la GPL3.


- Licenza Apache 2.0: è una licenza permissiva che permette la distribuzione, la modifica e la sublicenza del software, ma richiede l'inclusione del copyright, della licenza originale e dei riconoscimenti dei contributi. È compatibile con la GPL3.


- Licenza BSD: ci sono diverse varianti della licenza BSD, ma la maggior parte di esse sono compatibili con la GPL3. Queste licenze sono permissive e permettono la distribuzione, la modifica e la sublicenza del software, ma richiedono solo l'inclusione del copyright e della licenza originale.


- Licenza Creative Commons Attribution-ShareAlike (CC BY-SA): è una licenza che permette la distribuzione e la modifica del software, ma richiede l'attribuzione dell'autore originale e la condivisione delle opere derivate con la stessa licenza. È compatibile con la GPL3.


Queste sono solo alcune delle licenze compatibili con la GPL3. È importante leggere attentamente i termini di ogni licenza per assicurarsi che siano compatibili con i propri scopi e con la GPL3.


Si prega di notare anche che le licenze possono variare nel tempo, quindi è sempre consigliabile verificare la licenza ufficiale di ogni pacchetto prima di utilizzarlo.

giovedì 8 aprile 2021

PYTHON - Light database from json file

 A very light textual database, very simple and basic. 

Download the two files maker.py and lightdb.py in the same directory. Run lightdb.py to build the database on a json file. Then there is the possibility to add data directly from lightdb or you can build a .py file that will serve to manage the database. There is also the possibility to transform the json file into an excel file.

 You can download  the file from repo on github: lightdb

sabato 3 aprile 2021

PYTHON - Make and read JSON file with JSON library

Simple example for to show python power
import json
import sys
#Write and read json file with json library and dict
def makeJSON(jsFile):
    dict={}
    while True:
        chiave=input("Chiave> ")
        if chiave=='#e':
            break
        valori=input("Valori> ")
        lista=valori.split(' ')
        dict[chiave]=lista
    with open(jsFile,"w") as json_file:
        json.dump(dict, json_file)

def readJSON(jsFile):
    dict={}
    with open(jsFile,"r") as json_file:
        dict=json.load(json_file)
    return dict

def understandvalues(dict):
    n=0
    f=0.0
    l=[]
    d={}
    klist=list(dict.keys())
    for i in range(len(klist)):
        val=dict[klist[i]]
        if type(val)==type(l):
            print("Lista")
        elif type(val)==type(n) or type(val)==type(f):
            print("numero")
        elif type(val)==type(d):
            print("dizionario")

if __name__ == "__main__":
    comandi="Ho to use: ej3.py (r or w) (file name) \nr read json file\nw write json file"
    try:
        if sys.argv[1]=='r':
            d=readJSON(sys.argv[2])
            understandvalues(d)
            print(d)
        elif sys.argv[1]=='w':
            makeJSON(sys.argv[2])
        else:
            print(comandi)
    except:
        print(comandi)

PYTHON - Building a memory based on external stimuli

This script parses the incoming phrase with the keys contained in the json file, if it finds the key it processes a response, otherwise it adds the key and rewrites the json file.
import json
#Da stimoli esterni il software allarga le proprie conoscenze

def caricaCoscienza(nomeCoscienza):
    with open(nomeCoscienza,"r") as json_file:
        dictFromJSon=json.load(json_file)
    return dictFromJSon

def memorizza(valori,dict,nomeCoscienza):
    chiave=valori[0]
    lista=[]
    for i in range(len(valori)):
        if i>0:
            lista.append(valori[i])
    dict[chiave]=lista
    with open(nomeCoscienza,"w") as json_file:
            json.dump(dict, json_file)
    with open(nomeCoscienza,"r") as json_file:
        dictFromJSon=json.load(json_file)
    return dictFromJSon

def elabora(valori,ch,keys,dict):
    chiave=keys[ch]
    risposta=dict[chiave]
    return risposta

def ricerca(ingresso,dict,nomeCoscienza):
    keys=list(dict.keys())
    valori=ingresso.split(' ')
    trovato=False
    r=''
    for i in range(len(keys)):
        for c in range(len(valori)):
            if keys[i]==valori[c]:
                trovato=True
                ch=i
    if not(trovato):
        dict=memorizza(valori,dict,nomeCoscienza)
    else:
        r=elabora(valori,ch,keys,dict)
    return r


if __name__ == "__main__":
    dict=caricaCoscienza("result.json")
    dato=input(">")
    print(ricerca(dato,dict,"result.json"))

PYTHON - FROM DICTIONARIES to JSON

Python dictionaries: a power; python dictionaries + JSON: super power.
import json
#HOW TO MANAGE DICTIONARY
#+-+-+-+-+-+-+-+-+-+-+-+#
d = {
  "Chiave": "Codice",
  "Costo": 1.23,
  "Ricarico": 30,
  "Listino": 3.00
}
c = d.items()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
c = d.keys()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
c=d.values()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
nd = {
    "dizionario":{"subDict":["ch1","ch2","ch3"],
                "other":"otherSub"
                },
    "numero":2,
    "codice":"codice"
}
c=nd.items()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
c = nd.keys()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
c=nd.values()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
newD=lista[0]
c=newD.values()
print(c)
lista=list(c)
for i in range(len(lista)):
    print(lista[i])
nuovaLista=lista[0]
for i in range(len(nuovaLista)):
    print(nuovaLista[i])
print("Costruzione JSON")
with open("result.json", "w") as json_file:
    json.dump(nd, json_file)
json_string = json.dumps(nd)
print(json_string)
with open("result.json","r") as json_file:
    dictFromJSon=json.load(json_file)
print(dictFromJSon)

giovedì 1 aprile 2021

PYTHON - JSON MAKER

Maker JSON Files
Writing a json file can be boring, with this very simple script it's boring all the same, but at least in the end everything is correct.
########################################
# json files editor to use as database #
########################################

import sys,os
import curses
import json

def interpreta(o,file,next,cont):
    if next=='#k' and cont==0:
        file=file+'\"'+o+'\":'
        next=''
        cont+=1
    elif next=='#k' and cont>0:
        file=file+',\"'+o+'\":'
        next=''
    elif next=='#v':
        file=file+'\"'+o+'\"'
        next=''
    elif next=='#vl':
        c=o.split(',')
        file=file+'['
        for i in range(len(c)):
            file=file+'\"'+c[i]+'\"'
            if i!=len(c)-1:
                file=file+','
        file=file+']'
        next=''
    if o=='#k' and cont==0:
        file='{'
        next='#k'
    if o=='#k' and cont>0:
        next='#k'
    if o=='#v':
        next='#v'
    elif o=='#vl':
        next='#vl'
    elif o=='#vd':
        next='#vd'
    return file,next,cont

def main():
    print("JSON maker")
    print("commands: #k new key - #v new value - #vl new list value - #e save and exit")
    file=''
    cont=0
    next=''
    nomeFile=''
    while True:
        o=input(">")
        if o=='#e':
            file=file+"}"
            nomeFile=input("Nome del file >")
            f=open(nomeFile,"w")
            f.write(file)
            f.close()
            sys.exit()
        file,next,cont=interpreta(o,file,next,cont)


if __name__ == "__main__":
    main()

domenica 28 marzo 2021

PYTHON - MAKE A JSON FILE FROM DICT

Practical example of how to transform a dictionary into a json file.
The filename is updated using a variable contained in "count.py". Each file is added to the "listalogiche.dat" file.
From here we start for artificial intelligence.
import json
import conteggio
import sys

lista2={}
while True:
v1=input('Parola ')
if v1=='fine':
break
elif v1=='annulla':
sys.exit()
else:
v2=input('comando ')
lista2[v1]=v2
nomefile="comandi"+str(conteggio.conta)+".json"
#save lista2 as .json file
with open(nomefile, "w") as json_file:
json.dump(lista2, json_file)
#aggiornamento dei file di configurazione
f=open("conteggio.py","w")
n=conteggio.conta
n+=1
f.write('conta='+str(n))
f.close()
f=open("listalogiche.dat","a")
f.write(nomefile)
f.close()

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)

sabato 2 maggio 2020

PYTHON - AI TESTING BOT TRADING SIGNALS

Some signals from the BOT that I am testing. It is not my responsibility to use these signals; the use of these signs is at your own risk. I remember that trading is a high risk investment and it is possible to lose all the capital invested.
BATUSDT Binance

03/05/2020   06:47:01
BATUSDT   DAY   10   1
23-Apr-20
Op:  Buy  Prezzo:  0.1914 
TP1: 0.20450  TP2: 0.19795  TP3: 0.19577
Il prezzo è tra 0.19610  e 0.18680 
The BOT I am testing has calculated an upward trend and proposes a long operation with three possible targets. It also indicates the price between which resistances and support. 

Same reading of the BOT signals on the next pairs 

03/05/2020   06:47:01
LINKUSDT   DAY   10   1
23-Apr-20
Op:  Buy  Prezzo:  3.824 
 TP1: 3.99728  TP2: 3.91064  TP3: 3.88176
Il prezzo è tra 3.83657  e 3.68133  vicino al livello massimo

03/05/2020   06:47:01
TRXUSDT   DAY   10   1
23-Apr-20
Op:  Buy  Prezzo:  0.01642 
 TP1: 0.01762  TP2: 0.01702  TP3: 0.01682
Il prezzo è tra 0.01740  e 0.01630 
03/05/2020   06:47:01
VETUSDT   DAY   10   1
23-Apr-20
Op:  Buy  Prezzo:  0.004557 
 TP1: 0.00484  TP2: 0.00470  TP3: 0.00465
Il prezzo è tra 0.00464  e 0.00439 
 
 
03/05/2020   07:16:54
BTCUSDT   DAY   10   1
23-Apr-20
Op:  Buy  Prezzo:  9101.81 
TP1: 9489.80920  TP2: 9295.80960  TP3: 9231.14307
Il prezzo è tra 9250.95667  e 8480.50333 

venerdì 1 maggio 2020

PYTHON - INTERROGATE THE WEB WITH APIs

With python's REQUEST and JSON module it's simple. Below is an example of a query to the GNEWS.IO API
This very simple script allows you to search for articles related to the keywords you enter, using the GNEWS.IO API

import requests
import json
#http://gnews.io
api_token=''#here your gnews api

keywords=input('Parole chiave:')
indirizzo='https://gnews.io/api/v3/search?q='+keywords+'&token='+api_token
print(indirizzo)
r=requests.get(indirizzo)
file=r.text
output=json.loads(file)
for i in range(len(output['articles'])):
    print('Articoli: '+output['articles'][i]['title'])
    print('Descrizione: '+output['articles'][i]['description'])
    print('URL: '+output['articles'][i]['url'])
    print('Pubblicato il: '+output['articles'][i]['publishedAt'])

The web is full of APIs that can be used to collect any type of data.
If you like the blog remember to support my work through gofundme or by sending cryptocurrencies. Thanks

lunedì 20 aprile 2020

PYTHON - LE BASI DELLA PROGRAMMAZIONE

English translation after Italian. 

C'è chi cerca soluzioni di algoritmi e chi le basi per iniziare a programmare in python e il mio blog è ben lontano da fornire informazioni di questo tipo, dato il già esteso numero di siti e blog pieni delle basi, ma il pdf a questo link credo che sia un eccezzionale libro thinkpython_italian.pdf che bisogna avere.
Oltre che spiegare bene la sintassi, spiega anche la logica del programmatore, cosa da non sottovalutare: un programma, a differenza di tante altre cose, può funzionare anche se scritto male. 

Quando ho iniziato a studiare informatica alle superiori oltre cha valutare se il programma funzionava veniva fatto anche il calcolo computazionale di tale programma, poichè le risorse dei PC erano limitate; ai giorni nostri ci sono PC molto potenti e le grandi software house commerciali tendono a sfruttare questa potenza nello spreco, allenarsi a sfruttare la potenza del linguaggio per sfruttare al meglio, senza sprechi, la potenza del PC.
 Qualcuno potrebbe obiettare che a livello commerciale non conviene "perdere tempo" ad ottimizzare i programmi, e potrei anche dargli ragione, ma credo che per quello che si chiama "amor proprio" ottimizzare ogni programma è una grande soddisfazione.


There are those looking for algorithm solutions and those who have the basics to start programming in python and my blog is far from providing information of this type, given the already extensive number of sites and blogs full of bases, but the pdf to this link I think it is an exceptional thinkpython_italian.pdf book that you must have. 
In addition to explaining the syntax well, it also explains the programmer's logic, which should not be underestimated: a program, unlike many other things, can work even if written poorly. 
When I started studying computer science in high school, besides evaluating if the program worked, the computational calculation of this program was also done, as the PC resources were limited; nowadays there are very powerful PCs and the big commercial software houses tend to exploit this power in waste, train to exploit the power of language to make the best use, without waste, of the power of the PC. 
Some might argue that on a commercial level it is not convenient to "waste time" on optimizing programs, and I might even agree with it, but I believe that for what is called "self-love" optimizing each program is a great satisfaction.

domenica 19 aprile 2020

PYTHON - MACD ALGORITHM

MACD is a momentum indicator. This algorithm will search for the divergences between price and indicator independently. It will find the trend automatically and then look for convergence.
Here you can see the script that builds only the MACD.

The vectorMA function builds the two moving average lists that will be used to build the MACD.
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

PYTHON IA BINANCE API PIVOT CALCULATOR V.2

In this new version there is the possibility to automatically calculate the Fibonacci levels between the levels where the price is located. 


If you like you can help me continue the research on my AI written in Python by donating crypto currencies or by donating here

You can download the software from this link: PivotCalculator. If you are interested in the sources contact me.

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)