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

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)

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()

domenica 21 marzo 2021

PYTHON and CURSES - Stupid text editor

I needed a light and simple text editor.
Sometimes I need to write micro programs in python or batch, with this little script I solved my problem.
How to use:
py ste.py "filename I want to save"
import sys,os
import curses
#ste : simple(or stupid) text editor

def editor(stdscr):
k = 0
h = 0
cursor_x = 0
cursor_y = 0
stdscr.clear()
stdscr.refresh()
curses.start_color()
curses.init_pair(1, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(2, curses.COLOR_GREEN, curses.COLOR_BLACK)
while (True):
height, width = stdscr.getmaxyx()
if k == curses.KEY_DOWN:
cursor_y += 1
elif k == curses.KEY_UP:
cursor_y -= 1
elif k == curses.KEY_RIGHT:
cursor_x += 1
elif k == curses.KEY_LEFT:
cursor_x -= 1
elif k == 10: #ENTER
cursor_x=1
cursor_y+=1
h=cursor_y
elif k == 9: #tab
cursor_x = cursor_x +3
elif k == 265: #F1
break
elif k == 266: #
stringa=''
outstr=''
f=open(sys.argv[1],"wb+")
for i in range(h+1):
outstr=stdscr.instr(i, 1) #Read the screen
f.write(outstr)
acapo='\n'
f.write(acapo.encode())
f.close()
else:
stdscr.attron(curses.color_pair(2))
curses.echo()
cursor_x = cursor_x+1
cursor_x = max(0, cursor_x)
cursor_x = min(width-1, cursor_x)
cursor_y = max(0, cursor_y)
cursor_y = min(height-1, cursor_y)
statusbarstr = "Press 'F1' to exit | 'F2' to save | https://danieleporcaripython.blogspot.com"
stdscr.attron(curses.color_pair(1))
stdscr.addstr(height-1, 0, statusbarstr)
stdscr.addstr(height-1, len(statusbarstr), " " * (width - len(statusbarstr) - 1))
stdscr.attroff(curses.color_pair(1))
stdscr.move(cursor_y, cursor_x)
stdscr.refresh()
stdscr.attron(curses.color_pair(2))
k = stdscr.getch()

def main():
curses.wrapper(editor)

if __name__ == "__main__":
main()

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



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 

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.

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