#!/usr/bin/env python

import sys
import subprocess
import datetime
import time
import statistics
import math
import matplotlib.pyplot as plt
from matplotlib.widgets import Button
from matplotlib.widgets import TextBox
from matplotlib.transforms import Bbox
#import matplotlib.backend_bases as bkb
import numpy as np
from binance.spot import Spot

client = Spot()

class index:
    def graphClose(self, event):
        plt.close()
        quit()

    def graphNext(self, event):
        plt.close()

    def graphcandles(self, event):
        global candles
        candles = not candles
        plt.close()

    def graphsupres(self, event):
        global supRes
        supRes = not supRes
        plt.close()

    def graphsupresplus(self, event):
        global _STEP
        _STEP += 1
        plt.close()

    def graphsupresmoins(self, event):
        global _STEP
        _STEP -= 1
        plt.close()

    def graphpolyreg(self, event):
        global polyReg
        polyReg = not polyReg
        plt.close()

    def graphordreplus(self, event):
        global ordre
        ordre += 1
        plt.close()

    def graphordremoins(self, event):
        global ordre
        ordre -= 1
        plt.close()

    def graphampliplus(self, event):
        global ampli
        ampli += 1
        plt.close()

    def graphamplimoins(self, event):
        global ampli
        ampli -= 1
        plt.close()

    def graph1h(self, event):
        global duree
        duree = '1h'
        plt.close()

    def graph1d(self, event):
        global duree
        duree = '1d'
        plt.close()

    def graph12h(self, event):
        global duree
        duree = '12h'
        plt.close()

    def graph8h(self, event):
        global duree
        duree = '8h'
        plt.close()

    def graph4h(self, event):
        global duree
        duree = '4h'
        plt.close()

    def graph2h(self, event):
        global duree
        duree = '2h'
        plt.close()

    def graph30m(self, event):
        global duree
        duree = '30m'
        plt.close()

    def graph15m(self, event):
        global duree
        duree = '15m'
        plt.close()

    def graph5m(self, event):
        global duree
        duree = '5m'
        plt.close()

    def graph1m(self, event):
        global duree
        duree = '1m'
        plt.close()

#
# L'initialisation des variables aux valeurs standard est nécessaire pour l'utilisation des boutons du graphe (risque de variables non-déclarées)
#
ar_args = sys.argv # '{tokenpair}' ou '{pair}' sous forme de commande(compare, diff, etc) + [durée] + [sample].
compGraph = False
twoTime = False
_STEP = 3
supRes = True # Support/résistance acivé par défaut
boll = False
candles = False
graphOnly = True # Pas d'affichage de la différence par défaut
polyReg = True # ***** BETA : POLYNOMIAL REGRESSION ****************** Activé par défaut
atl = []
ath = []
atlm = []
athm = 0.0
PREDICT_RANGE = -5
ordre = 7
ampli = 1
try:
    pair = ar_args[1]
except:
    pair = 'bnbusdt'
try:
    sample = int(ar_args[3])
except:
    sample = 160
try:
    duree = str(ar_args[2])
except:
    duree = '1h'

class colors:
    UP = '\033[1A' #Curseur UP

def graphpair(exp):
    global pair
    pair = exp.upper()
    #plt.close()

def graphsample(exp):
    global sample
    sample = int(exp)

def polynomialRegression(y, s, o, a, pr):                      # ****************** BETA : POLYNOMIAL REGRESSION ********************
    idx = 0              # y=valeurs moyennes (res6) ; s= nbre d'échantillons ; o=ordre de la régression ; a=+/-ordre pour les tracés secondaires ; pr=PREDICT_RANGE
    xp = []
    xp2 = []
    idx2 = int(s + 2)
    a= abs(a)

    for x in y :
        idx += 1 
        xp.append(idx)
        
    mymodel = np.poly1d(np.polyfit(xp[0:PREDICT_RANGE], y[0:PREDICT_RANGE], o))
    #coeffs = np.polyfit(xp, y, o)
    mymodel1 = np.poly1d(np.polyfit(xp[0:PREDICT_RANGE], y[0:PREDICT_RANGE], o-a))
    mymodel2 = np.poly1d(np.polyfit(xp[0:PREDICT_RANGE], y[0:PREDICT_RANGE], o+a))
    mymodel3 = np.poly1d(np.polyfit(xp[0:PREDICT_RANGE], y[0:PREDICT_RANGE], o-(a+1)))
    mymodel4 = np.poly1d(np.polyfit(xp[0:PREDICT_RANGE], y[0:PREDICT_RANGE], o+a+1))
    myline = np.linspace(1, idx2)
    if o > 0:
        if a != 0:
            if o-a > 0:
                plt.plot(myline, mymodel1(myline), linewidth='1.5', color = 'r', linestyle='--')
                if o-(a+1) != 0:
                    plt.plot(myline, mymodel3(myline), linewidth='1.5', color = 'orange', linestyle='--')
            plt.plot(myline, mymodel2(myline), linewidth='1.5', color = 'c', linestyle='dotted')
            plt.plot(myline, mymodel4(myline), linewidth='1.5', color = 'b', linestyle='dotted')
        plt.plot(myline, mymodel(myline), linewidth='2.5', color = 'y', linestyle='-.')
        #print(coeffs)

# *****************************************************************************************************************************
# ntp() -> pas nécessaire avec bookworm (Debian 12)
def ntp():
    ntpClockAdjust = subprocess.run(["sudo", "ntpdate", "0.fr.pool.ntp.org"]) #Synchro horloge si erreur 

# support(data) dessine une ligne de support sur la durée spécifiée
# utilisation d'une régression linéaire sur les minimums de la courbe, maximums pour la résistance ?
#
def getAthAtl(data):
    global atlm, athm
    ath = []
    atl = []
    atlm = []
    
    for x in data:
        ath.append(float(x[2])) # Valeur high
        atl.append(float(x[3])) # Valeur low
        atlm.append((float(x[2])+float(x[3]))/2) # Valeur moyenne (correspond à l'affichage du tracé
    y1 = max(ath)
    y2 = min(atl)
    x1 = ath.index(y1)
    x2 = atl.index(y2)
    ath = [x1, y1]
    atl = [x2, y2]
    athm = max(atlm)
    atlm = min(atlm)
    return [ath, atl]

def support(data, difs, s):
    nStep = 0
    step = round(int(s) / _STEP)
    if step == 0: return False
    res9x = []
    res9y = []
    
    for x in range(0, s+1, step):
        if x >= step: nStep = round(step / 2)
        a = x-nStep
        b = max(x+nStep, step)
        r = min(data[a:b])
        
        if boll:
            idx = data[a:b].index(r)
            r -= abs(difs[a:b][idx])
        res9y.append(r)
        res9x.append(x)

    res9x = np.array(res9x)
    res9y = np.array(res9y)
    res10 = [res9x, res9y]
    return res10

# resistance(data) dessine la ligne de résistance sur la durée spécifiée    
def resistance(data, difs, s):
    nStep = 0
    step = round(int(s) / _STEP)
    if step == 0: return False
    res9x = []
    res9y = []
    
    for x in range(0, s+1, step):
        if x >= step: nStep = round(step / 2)
        a = x-nStep
        b = max(x+nStep, step)
        r = max(data[a:b])

        if boll:
            idx = data[a:b].index(r)
            r += abs(difs[a:b][idx])
        res9y.append(r)
        res9x.append(x)

    res9x = np.array(res9x)
    res9y = np.array(res9y)
    res10 = [res9x, res9y]
    return res10

def candlesticks(data, pr):
    idx = 0
    xpoints = []
    ypointscdl = []
    ypointsflm = []
    if sample > 200:
        candleWidth = 1000 / sample
    else:
        candleWidth = (1000 / sample)-(250 / sample)

    xpointslimit = len(data)+int(pr) # Après cette limite on utilise magenta + cyan


    for i in data:
        xpoints = []
        ypointscdl = []
        ypointsflm = []
        
        for j in range(0,2):
            xpoints.append(idx)
        idx += 1
            
        ypointscdl.append(float(i[1])) # open
        ypointscdl.append(float(i[4])) # close
        ypointsflm.append(float(i[3])) # low
        ypointsflm.append(float(i[2])) # high
        ypointscdl = np.array(ypointscdl)
        ypointsflm = np.array(ypointsflm)
        xpoints = np.array(xpoints)
        indexofdata = data.index(i)

        if float(i[1])-float(i[4]) <= 0.0:
            if int(indexofdata) < int(xpointslimit):
                plt.plot(xpoints, ypointscdl, color='g', linewidth=candleWidth)
                plt.plot(xpoints, ypointsflm, color='g', linewidth=1)
            else:
                if polyReg:
                    plt.plot(xpoints, ypointscdl, color='c', linewidth=candleWidth)
                    plt.plot(xpoints, ypointsflm, color='c', linewidth=1)
                else:
                    plt.plot(xpoints, ypointscdl, color='g', linewidth=candleWidth)
                    plt.plot(xpoints, ypointsflm, color='g', linewidth=1)

        else:
            if int(indexofdata) >= int(xpointslimit):
                if polyReg:
                    plt.plot(xpoints, ypointscdl, color='m', linewidth=candleWidth)
                    plt.plot(xpoints, ypointsflm, color='m', linewidth=1)
                else:
                    plt.plot(xpoints, ypointscdl, color='r', linewidth=candleWidth)
                    plt.plot(xpoints, ypointsflm, color='r', linewidth=1)

            else:
                plt.plot(xpoints, ypointscdl, color='r', linewidth=candleWidth)
                plt.plot(xpoints, ypointsflm, color='r', linewidth=1)
        
    return


#print("""
    #########################################################################
    #                                                                       #
    #        Affiche l'écart maximum pour une paire selon la durée          #
    #        ainsi que le graphique correspondant (défaut : BTCUSDT)        #
    #                                                                       #
    #    Syntaxe : [compare]{[supres]||[boll]}[candles][polyreg][diff]      #
    #              pair [pair]⤶ time [time]⤶ samples⤶ [intervalle]⤶         #
    #              [p.reg=ordre]⤶ [p.reg=amplitude]⤶ [p.reg=profondeur]     #
    #                                                                       #
    #                   (Important: COMPARE doit être le premier            #
    #                   argument de la commande s'il est utilisé.           #
    #                   Les autres commandes peuvent être placées           #
    #                   indifféremment avant ou après la/les paire.s)       #
    #        Exemples : bnbbusd, 1d, 365                                    #
    #                   compare bnbbusd ethbusd, 1d, 365                    #
    #                   bnbbusd ethbusd, 1h, 240                            #
    #                   bnbbusd ethbusd, 1h 2h, 120                         #
    #                   compare bnbbusd, 1h 4h, 240                         #
    #                   supres bnbbusd, 1h, 240, [6]                        #
    #                   boll bnbbusd, 1h, 480                               #
    #                   candles bnbbusd, 1h, 240                            #
    #                   diff bnbbusd candles, 1d                            #
    #         Régression polynomiale (ordre 7 par défaut):                  #
    #                   polyreg bswbnb, 1h, 500, [6], [1]                   #
    #         Quitter le programme :                                        #
    #                   bye                                                 #
    #                                                                       #
    #########################################################################\n""")


#pair = input(" Paire : ")
if pair == '':
    pair = "bnbusdt"
pair = pair.upper()
pair2 = pair.split()

if 'SUPRES' in pair2:
    pair2.remove('SUPRES')
    pair = pair.replace('SUPRES', '')
    pair = pair.strip()
    supRes = True

if 'DIFF' in pair2:
    pair2.remove('DIFF')
    pair = pair.replace('DIFF', '')
    pair = pair.strip()
    graphOnly = False

if 'BOLL' in pair2:
    pair2.remove('BOLL')
    pair = pair.replace('BOLL', '')
    pair = pair.strip()
    supRes = True
    boll = True

if 'CANDLES' in pair2:
    pair2.remove('CANDLES')
    pair = pair.replace('CANDLES', '')
    pair = pair.strip()
    candles = True

if 'POLYREG' in pair2:                      # **** 
    pair2.remove('POLYREG')                 # ****
    pair = pair.replace('POLYREG', '')      # ****
    pair = pair.strip()                     # ****
    polyReg = True                          # ****
    #ordre = input(" Régression polynomiale d'ordre n (défaut : 7 [recommandé]) : ")
    #ordre = 7 if ordre == '' else int(ordre)
    #ampli = input(" Trace également la courbe d'ordre +n et -n (défaut : 2 [ 0 n'affiche rien, recommandé : 2]) : ")
    #ampli = 2 if ampli == '' else int(ampli)
    
if len(pair2) == 2 and 'COMPARE' not in pair2:   # Si le mot 'compare' est omis mais qu'il y a deux paires dans l'input, on l'ajoute
    pair2.reverse()   # avec un petit trick genre SWAP ROT
    pair2.append('COMPARE')
    pair2.reverse()
    pair = 'COMPARE ' + pair
#print(pair, pair2)
if pair == 'BYE':
    #ntp()
    quit()

#Si la comparaison porte sur deux échelles de temps différentes, entrer une chaine avec 
#les deux unités de temps  (ex : '1h 1d')
#duree = input(" Durée ('1m', '5m', '15m', '30m', '1h' (défaut), '2h', '4h', '8h', '12h', '1d'): ")
#duree = '1h' if duree == '' else str(duree)
try:
    duree2 = duree.split()
    duree = duree2[0]
    duree2 = duree2[1]
    twoTime = True
    #print("test ", duree, duree2)
except:
    duree2 = duree

#sample = input(" Échantillon (défaut=160, max=1000) : ")
#sample = 160 if sample == '' else int(sample)
#sample = min(sample, 1000)

#if supRes:
#    _STEP = input(" Diviseur pour le calcul support/résistance (défaut= nombre d'échantillons/20) : ")
#    _STEP = int(sample/20) if _STEP == '' else abs(int(_STEP))
#    _STEP = min(_STEP, int(sample/2))
#    _STEP = max(2, _STEP)

#if polyReg:
#    PREDICT_RANGE = input(" Profondeur de prédiction sur le graphique (Défaut: 5) : ")
#    PREDICT_RANGE = -5 if PREDICT_RANGE == '' else -abs(int(PREDICT_RANGE))
#graphColor = input(" Couleur d'affichage du graphe principal ('r', 'g', 'b', 'c', 'm', 'y', 'k', 'w') : ")

while True:
    if 'COMPARE' in pair:
        compGraph = True
        try:
            t = pair2[2]
        except:
            pair2.append(pair2[1])
        pair = pair2[1]
        kpriceComp = client.klines(pair2[2], duree2, limit=sample)

    kprice = client.klines(pair, duree, limit=sample)

    kplabel = pair + " : Récupération des " + str(sample) + " dernières valeurs [" + str(duree) + "]"
    if duree != duree2:
        kplabel = kplabel + "[" + str(duree2) + "]"
    print(kplabel)
    res0 = []
    res6 = []
    resComp0 = []
    resComp6 = []

    for x in kprice:
        refDate = str(x[0])
        refDate = refDate[0:-3]
        refDate = datetime.datetime.fromtimestamp(int(refDate))
        refDate = refDate.strftime("%x %X")
        res1 = float(x[4]) - float(x[1])
        #print("Prix ouverture : " + x[1] + " Fermeture : " + x[4] + " Écart : \t" + str(res1) + " " + str(refDate))
        res6.append((float(x[4]) + float(x[1]))/2)
        res0.append(res1)
 
    if compGraph:
        for x in kpriceComp:
            refDate = str(x[0])
            refDate = refDate[0:-3]
            refDate = datetime.datetime.fromtimestamp(int(refDate))
            refDate = refDate.strftime("%x %X")
            res1 = float(x[4]) - float(x[1])
            #print("Prix ouverture : " + x[1] + " Fermeture : " + x[4] + " Écart : \t" + str(res1) + " " + str(refDate))
            resComp6.append((float(x[4]) + float(x[1]))/2)
            resComp0.append(res1)

    res7 = " Max : " + str(max(res0)) + " Min : " + str(min(res0)) + " Avg : " + str(statistics.mean(res0))
    res8 = " Max : " + str(max(res6)) + " Min : " + str(min(res6)) + " Avg : " + str(statistics.mean(res6))
    if compGraph:
        res8 += "\n" + pair2[2] + " Max : " + str(max(resComp6)) + " Min : " + str(min(resComp6)) + " Avg : " + str(statistics.mean(resComp6))

    if compGraph:
        ypointsComp = np.array(resComp0)
        resComp3 = []
        resComp4 = statistics.mean(resComp0)/len(resComp0)
        resComp5 = 0.0
        for z in resComp0:
            resComp3.append(resComp5)
            resComp5 += resComp4
        ypointsComp2 = np.array(resComp3)
    
    ypoints = np.array(res0)
    res3 = []
    res4 = statistics.mean(res0)/len(res0)
    res5 = 0.0
    for z in res0:
        res3.append(res5)
        res5 += res4
    
    ypoints2 = np.array(res3)

    if not graphOnly:
        plt.subplot(2, 1, 1)
        plt.plot(ypoints, color='b') # écart de prix
        if compGraph:
            plt.plot(ypointsComp, color='g', linestyle='dotted') # écart de prix 2
        plt.plot(ypoints2, color='r') # moyenne des écarts 1
        if compGraph:
            plt.plot(ypointsComp2, color='y', linestyle='dotted') # moyenne des écarts 2
        plt.grid()
        plt.title(pair + res7, loc='left')
        if twoTime:
            plt.xlabel(str(sample) + " x " + duree + "  /  " + str(sample) + " x " + duree2)
        else:
            plt.xlabel(str(sample) + " x " + duree)
        plt.ylabel("Écart de prix")
        plt.subplot(2, 1, 2)

    if candles:
        candlesticks(kprice, PREDICT_RANGE)
    
    ypoints3 = np.array(res6)

    if compGraph:
        ypointsComp3 = np.array(resComp6)

    if not candles:    
        plt.plot(ypoints3, color='b') # prix moyen 1

    if compGraph:
        plt.plot(ypointsComp3, color='c', linestyle='dotted', linewidth=2.5) #prix moyen 2

    if supRes:
        rS = support(res6, res0, int(sample))
        if rS != False:
            plt.plot(rS[0], rS[1], 'g-.', linewidth=0.7)
        rR = resistance(res6, res0, int(sample))
        if rR != False:
            plt.plot(rR[0], rR[1], 'r-.', linewidth=0.7)

#default_x_ticks = range(sample)
#plt.xticks(default_x_ticks, xp)
    plt.tick_params(axis='x', colors='red', direction='in', length=3, width=1)
    xpbis = []
    xpter = []
    if graphOnly:
        try:
            if duree == '1h':
                for x in range(sample):
                    xpbis.append(x)
                    if x % 12 == 0:
                        if x > 24:
                            z45 = x / 24
                            xpter.append(str(z45) + ' jours')
                        else:
                            xpter.append(str(x) + 'h')
                    else:
                        xpter.append(' ')
                xpter[0] = 'Actuel'
                xpter.reverse()
                ax1 = plt.subplot()
                ax1.set_xticks(xpbis)
                ax1.set_xticklabels(xpter, rotation=45)    

            if duree == '1m':
                for x in range(sample):
                    xpbis.append(x)
                    if x % 60 == 0:
                        if x > 59:
                            z45 = x / 60
                            xpter.append(str(z45) + 'h')
                        else:
                            xpter.append(str(x) + 'm')
                    else:
                        xpter.append(' ')
                xpter[0] = 'Actuel'
                xpter.reverse()
                ax1 = plt.subplot()
                ax1.set_xticks(xpbis)
                ax1.set_xticklabels(xpter, rotation=45)    
    
            if duree == '5m':
                for x in range(sample):
                    xpbis.append(x)
                    if x % 12 == 0:
                        if x > 11:
                            z45 = x / 12
                            xpter.append(str(int(z45)) + 'h')
                        else:
                            xpter.append(str(x) + 'm')
                    else:
                        xpter.append(' ')
                xpter[0] = 'Actuel'
                xpter.reverse()
                ax1 = plt.subplot()
                ax1.set_xticks(xpbis)
                ax1.set_xticklabels(xpter, rotation=45)    

            if duree == '1d':
                for x in range(sample):
                    xpbis.append(x)
                    if x % 15 == 0:
                        if x > 29:
                            z45 = x / 15
                            xpter.append(str(z45/2) + ' mois')
                        else:
                            xpter.append(str(x) + ' jours')
                    else:
                        xpter.append(' ')
                xpter[0] = 'Actuel'
                xpter.reverse()
                ax1 = plt.subplot()
                ax1.set_xticks(xpbis)
                ax1.set_xticklabels(xpter, rotation=45)    
        
            if duree == '30m':
                for x in range(sample):
                    xpbis.append(x)
                    if x % 12 == 0:
                        if x > 11:
                            z45 = (x / 12)*6
                            if z45 < 25:
                                xpter.append(str(z45) + 'h')
                            else:
                                xpter.append(str(z45/24) + ' jours')
                        else:
                            xpter.append(str(x) + 'm')
                    else:
                        xpter.append(' ')
                xpter[0] = 'Actuel'
                xpter.reverse()
                ax1 = plt.subplot()
                ax1.set_xticks(xpbis)
                ax1.set_xticklabels(xpter, rotation=45)    
        
            if duree == '15m':
                for x in range(sample):
                    xpbis.append(x)
                    if x % 12 == 0:
                        if x > 11:
                            z45 = x / 4
                            if z45 < 25:
                                xpter.append(str(z45) + 'h')
                            else:
                                xpter.append(str(z45/24) + ' jours')
                        else:
                            xpter.append(str(x) + 'm')
                    else:
                        xpter.append(' ')
                xpter[0] = 'Actuel'
                xpter.reverse()
                ax1 = plt.subplot()
                ax1.set_xticks(xpbis)
                ax1.set_xticklabels(xpter, rotation=45)    
        except:
            print('')

    plt.grid(color='lightgray', linewidth=0.5, linestyle='--')
    plt.title(pair + res8 + " - " + str(datetime.datetime.now())[:-7], loc='left')
    if twoTime:
        plt.xlabel(str(sample) + " x " + duree + "  /  " + str(sample) + " x " + duree2)
    else:
        plt.xlabel(str(sample) + " x " + duree)
    tickerPrice = client.ticker_price(pair)
    tickerPrice = float(tickerPrice['price'])
    plt.text(sample, tickerPrice, str(tickerPrice), fontsize=8)
    athl = getAthAtl(kprice)
    ath = athl[0]
    atl = athl[1]
    if not candles:
        plt.text(ath[0], athm * 0.985, str(ath[1]), fontsize=8)
        plt.text(atl[0], atlm * 1.01, str(atl[1]), fontsize=8)
    if candles:
        plt.text(ath[0], ath[1], str(ath[1]), fontsize=8)
        plt.text(atl[0], atl[1], str(atl[1]), fontsize=8)    
    plt.ylabel("Prix moyen")

    if polyReg:                                                 # ********************* POLYNOMIAL REGRESSION BETA ************************
        polynomialRegression(res6, sample, ordre, ampli, PREDICT_RANGE)

# Sauvegarde de la figure, à travailler, le format de sortie est trop compact
    manager = plt.get_current_fig_manager()
    manager.resize(1600, 850)
    filename = pair + "_" + str(datetime.datetime.now())[:-7]
    filename = filename.replace(":", "-")
    filename = filename.replace(" ", "_")
    manager.set_window_title(filename)
#    zebox = Bbox([[-0.3, -0.4], [6.5, 4.25]])
#    plt.savefig('/home/loukoumaki/Programmes/screenshots/auto/'+filename+'.png', dpi=172, format='png', bbox_inches=zebox, pad_inches=0.0, orientation='landscape', transparent=True)

    if polyReg:
        if ampli != 0:
            labelAmpli = " | Orange: " + str(ordre - (ampli+1)) + " | Rouge: " + str(ordre - ampli) + " | Cyan: " + str(ordre + ampli) + " | Bleu: " + str(ordre+ampli+1)
        else:
            labelAmpli = ''
        labelAmpli = labelAmpli + " | Prédiction : " + str(abs(PREDICT_RANGE)) + " unités"
        #plt.text(sample, atlm * 0.99, "Régression polynomiale d'ordre " + str(ordre) + labelAmpli, color = 'r', verticalalignment='bottom', horizontalalignment='right', fontsize=12)
        plt.annotate("Régression polynomiale d'ordre " + str(ordre) + labelAmpli, xy=(30, 60), xytext=None, xycoords='figure pixels')
    if supRes:
        if polyReg:
            plt.annotate(" | Support/Résistance : " + str(_STEP) + " |", xy=(710, 60), xytext=None, xycoords='figure pixels')
        else:
            plt.annotate(" | Support/Résistance : " + str(_STEP) + " |", xy=(600, 60), xytext=None, xycoords='figure pixels')

# Définition des boutons :
    # Axes :
    callback = index()
    axclose = plt.axes([0.90, 0.01, 0.05, 0.045])
    axnext = plt.axes([0.845, 0.01, 0.05, 0.045])
    axcandles = plt.axes([0.435, 0.01, 0.05, 0.045])
    axsupres =  plt.axes([0.380, 0.01, 0.05, 0.045])
    axsupresplus = plt.axes([0.370, 0.03, 0.01, 0.025])
    axsupresmoins = plt.axes([0.370, 0.01, 0.01, 0.024])
    axpolyreg = plt.axes([0.282, 0.01, 0.05, 0.045])
    axordreplus = plt.axes([0.268, 0.03, 0.015, 0.025])
    axordremoins = plt.axes([0.268, 0.01, 0.015, 0.024])
    axampliplus = plt.axes([0.329, 0.03, 0.015, 0.025])
    axamplimoins = plt.axes([0.329, 0.01, 0.015, 0.024])
    axpair = plt.axes([0.050, 0.01, 0.07, 0.045])
    axsample = plt.axes([0.185, 0.01, 0.05, 0.045])
# Changement de durée
    ax1d = plt.axes([0.801, 0.01, 0.03, 0.035])
    ax12h = plt.axes([0.767, 0.01, 0.03, 0.035])
    ax8h = plt.axes([0.734, 0.01, 0.03, 0.035])
    ax4h = plt.axes([0.701, 0.01, 0.03, 0.035])
    ax2h = plt.axes([0.668, 0.01, 0.03, 0.035])
    ax1h = plt.axes([0.635, 0.01, 0.03, 0.035])
    ax30m = plt.axes([0.602, 0.01, 0.03, 0.035])
    ax15m = plt.axes([0.569, 0.01, 0.03, 0.035])
    ax5m = plt.axes([0.536, 0.01, 0.03, 0.035])
    ax1m = plt.axes([0.503, 0.01, 0.03, 0.035])
    # Boutons : 
    bclose = Button(axclose, 'Fermer')
    bclose.on_clicked(callback.graphClose)
    bnext = Button(axnext, 'Actualiser')
    bnext.on_clicked(callback.graphNext)
    if candles:
        bcandles = Button(axcandles, 'Ligne')
    else:
        bcandles = Button(axcandles, 'Chandelles')
    bcandles.on_clicked(callback.graphcandles)
    bsupres = Button(axsupres, 'Sup/Res')
    bsupres.on_clicked(callback.graphsupres)
    bsupresplus = Button(axsupresplus, '+')
    bsupresplus.on_clicked(callback.graphsupresplus)    
    bsupresmoins = Button(axsupresmoins, '-')
    bsupresmoins.on_clicked(callback.graphsupresmoins)    
    bpolyreg = Button(axpolyreg, 'Poly. Reg.')
    bpolyreg.on_clicked(callback.graphpolyreg)
    bordreplus = Button(axordreplus, 'O+')
    bordreplus.on_clicked(callback.graphordreplus)
    bordremoins = Button(axordremoins, 'O-')
    bordremoins.on_clicked(callback.graphordremoins)
    bampliplus = Button(axampliplus, 'A+')
    bampliplus.on_clicked(callback.graphampliplus)
    bamplimoins = Button(axamplimoins, 'A-')
    bamplimoins.on_clicked(callback.graphamplimoins)

    bpair = TextBox(axpair, 'Paire : ', label_pad=0.01, textalignment='center')
    bpair.on_submit(graphpair)
    bpair.set_val(pair)
    bsample = TextBox(axsample, 'Échantillons: ', label_pad=0.01, textalignment='center')
    bsample.on_submit(graphsample)
    bsample.set_val(str(sample))

    b1h = Button(ax1h, '1h')
    b1h.on_clicked(callback.graph1h)
    b1d = Button(ax1d, '1d')
    b1d.on_clicked(callback.graph1d)
    b12h = Button(ax12h, '12h')
    b12h.on_clicked(callback.graph12h)
    b8h = Button(ax8h, '8h')
    b8h.on_clicked(callback.graph8h)
    b4h = Button(ax4h, '4h')
    b4h.on_clicked(callback.graph4h)
    b2h = Button(ax2h, '2h')
    b2h.on_clicked(callback.graph2h)
    b30m = Button(ax30m, '30m')
    b30m.on_clicked(callback.graph30m)
    b15m = Button(ax15m, '15m')
    b15m.on_clicked(callback.graph15m)
    b5m = Button(ax5m, '5m')
    b5m.on_clicked(callback.graph5m)
    b1m = Button(ax1m, '1m')
    b1m.on_clicked(callback.graph1m)

# fin de définition des boutons

    plt.subplots_adjust(left=0.05, right=0.95, bottom=0.20)
    plt.show()
