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

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 3 aprile 2021

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

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)

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

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

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)

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