1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
| # Tout d'abord, nous importons les bibliothèques et définissons la clé API et la clé secrète.
import random
import pandas as pd
import time
import numpy as np
import datetime as dt
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly
import plotly.io as pio
import pandas as pd
import datetime
from futurespy import Client
from binance.client import Client as ClientReal
import talib
api_key='****'
api_secret='****'
client = Client(api_key, api_secret, testnet=True)
clientreal = ClientReal(api_key, api_secret)
# Afin de gérer la commande et de vérifier le signal, nous définissons une classe.
# La fonction get_signal prend les données des 40 dernières minutes de Binance. Nous nous intéressons au cours de clôture, car nous pouvons calculer la moyenne mobile des poids. Qu'avec data['action'] nous savons s'il y a un croisement entre WMA7 et WMA14.
# Lorsque WMA7>WMA14 la data['action'] est égale à 1 et c'est le signal d'achat.
# L'inverse lorsque WMA7<WMA14 la data['action'] est égale à -1 et c'est le signal de vente.
class Order():
def __init__(self, DATASET):
#init
self.DATASET=DATASET
self.count_step = 0
self.INVEST = 0.001
self.FlagBuy = False
self.FlagSell = False
self.trak_profit = [0]
#general
self.INIT_BALANCE=float(client.balance()[0]['balance'])
self.balance=self.INIT_BALANCE
#to track
self.history_balance=[self.INIT_BALANCE]
self.profit = [0]
self.comulative_profit = [0]
self.comulative_accuracy = [0]
self.correct = 0
self.wrong = 0
def get_signal(self):
candles = clientreal.get_klines(symbol=self.DATASET[0],
interval=clientreal.KLINE_INTERVAL_1MINUTE,
limit=40)
data = pd.DataFrame({'close':np.asarray(candles)[:,4]})
data['close'] = data['close'].astype(float)
data['wma7'] = talib.WMA(data['close'], timeperiod=7)
data['wma14'] = talib.WMA(data['close'], timeperiod=14)
data['signal'] = np.where(data['wma14'] > data['wma7'], 1, 0)
data['action'] = data['signal'].diff()
if list(data['action'])[-1]==1:
self.action=1
elif list(data['action'])[-1]==-1:
self.action=-1
else:
self.action=0
self.action_open()
# Nous exécutons l'action appelant la fonction action_open().
# En plus de l'exécution de la commande, certaines variables permettent de suivre nos performances.
def action_open(self):
self.start_balance=self.balance
if self.action==1:
client.new_order(side='BUY',
quantity=self.INVEST,
symbol=self.DATASET[0],
orderType='MARKET')
self.FlagBuy=True
elif self.action==-1:
client.new_order(side='SELL',
quantity=self.INVEST,
symbol=self.DATASET[0],
orderType='MARKET')
self.FlagSell=True
self.balance=float(client.balance()[0]['balance'])
if (self.balance-self.start_balance)>0:
self.correct+=1
else:
self.wrong+=1
print('net', self.balance-self.start_balance)
self.profit.append(self.balance-self.start_balance)
self.comulative_profit.append(self.comulative_profit[-1]+self.profit[-1])
self.comulative_accuracy.append(self.correct/(self.corect+self.wronk))
self.history_balance.append(self.balance)
# La dernière fonction est de tracer les performances.
def render(self):
fig0 = make_subplots(rows=4, cols=1, shared_xaxes=False, vertical_spacing=0.1,
subplot_titles=('Profit', 'Accuracy', 'Comulative Profit', 'Balance'))
rw_plot=go.Scatter(mode="lines", y=self.profit, name='Profit', line=dict(width=3))
fig0.add_trace(rw_plot, row=1, col=1)
rw_plot=go.Scatter(mode="lines", y=self.comulative_accuracy, name='Accuracy', line=dict(width=3))
fig0.add_trace(rw_plot, row=2, col=1)
rw_mean_plot=go.Scatter(mode="lines", y=self.comulative_profit,
name='Comulative Profite', line=dict(width=3))
fig0.add_trace(rw_mean_plot, row=3, col=1)
bl_plot=go.Scatter(mode="lines", y=self.history_balance, name='Balance', line=dict(width=3))
fig0.add_trace(bl_plot, row=4, col=1)
fig0=go.Figure(fig0)
#fig0.write_image(f'{path}/performance.svg')
plotly.offline.plot(fig0, show_link=False, filename = f' {path}/performance.html', include_plotlyjs="cdn")
# La classe Order est définie et nous pouvons appeler la classe dans le main.
# L'ensemble de données indique la crypto-monnaie à échanger. Le chemin indique où stocker le graphique de performance.
# Le while permet de recevoir le signal toutes les minutes et d'exécuter l'action.
if __name__=='__main__':
DATASET=['BTCUSDT']#, 'ETHUSDT', 'LTCUSDT']
path='/BINANCE/wma_bot/'
order=Order(DATASET)
new_history=len(order.profit)
while True:
if time.localtime().tm_sec==1:
order.get_signal()
print('time', datetime.datetime.now().strftime("%H:%M:%S"))
print('buy:', order.FlagBuy, 'sell:', order.FlagSell)
print('balance %', order.balance/order.INIT_BALANCE)
if len(order.profit)>new_history:
print('render')
new_history=len(order.profit)
order.render() |
Partager