-
Notifications
You must be signed in to change notification settings - Fork 36
/
TradingBot.py
214 lines (159 loc) · 6.31 KB
/
TradingBot.py
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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
# -*- coding: utf-8 -*-
"""
@author: Harnick Khera (Github.com/Hephyrius)
Use this class to trade using the model trained using the TrainBot class. This model is loaded from the "Models" folder.
"""
from numpy import *
import numpy as np
import pandas as pd
import time
from binance.client import Client
from binance.enums import *
import datetime
import CoreFunctions as cf
from joblib import dump, load
#%%
api_key = 'INSERT YOUR KEY'
api_secret = 'INSERT YOUR SECRET'
client = Client(api_key, api_secret)
model = load("Models/model.mdl")
firstRun = True
makeTrade = False
state = 0
prevTime = 0
data = []
MLData = []
currentBtc = cf.getCoinBalance(client, 'btc')
print(currentBtc)
currentUSDT = cf.getCoinBalance(client, 'USDT')
print(currentUSDT)
hasToken = False
currentTokenBalance = 0
market = "BTCUSDT"
trade = "BTC"
sellToBuyTransition = True
buyPrice = 0
bestPrice = 0
sinceBest = 0
while(True):
#check time stamp if its different then add to list and change state
if state == 0:
candles = client.get_klines(symbol=market, interval=Client.KLINE_INTERVAL_1HOUR)
if firstRun == True:
prevTime = datetime.datetime.fromtimestamp(candles[498][0]/ 1e3)
firstRun = False
makeTrade = False
for i in range(499):
data.append(candles[i])
else:
currTime = datetime.datetime.fromtimestamp(candles[498][0]/ 1e3)
if prevTime != currTime:
if candles[498] not in data:
data.append(candles[498])
prevTime = currTime
makeTrade = True
else:
makeTrade = False
print(makeTrade)
state = 1
#Trailing Stoploss at 1% of highest price since entering trade. Checking highest value every 10 seconds, helps prevent against BIG dumps or bad predictions
#in the hour
if state == 1:
if hasToken == True:
try:
prices = client.get_order_book(symbol=market)
price = prices['bids'][0][0]
if float(price) > float(bestPrice):
bestPrice = price
elif bestPrice * 0.99 > price:
print("Selling")
sellAmt = cf.getCoinBalance(client, trade)
currentBtc = str(sellAmt)
qty = ""
for q in range(8):
qty += currentBtc[q]
currentBtc = qty
cf.executeSell(client, market, currentBtc)
currentTokenBalance = 0
hasToken = False
sellToBuyTransition = False
buyPrice = 0
bestPrice = 0
sinceBest = 0
currentBtc = cf.getCoinBalance(client, 'btc')
print("Trailing Stop Trigger")
state = 0
time.sleep(10)
except Exception as e:
print(e)
# if timestamp is different then we update the
if makeTrade == True:
state = 2
makeTrade = False
else:
state = 0
time.sleep(10)
#make feature data used to make prediction
if state == 2:
#data = cf.makeTrainingData(data)
MLData = cf.FeatureCreation(data)
print(1)
state = 3
#make trade based on predicted signal
if state == 3:
pred = model.predict_proba(MLData[len(MLData)-1:len(MLData)])
print(pred[0])
signal = np.argmax(pred[0])
print(signal)
#If the model buys then market buy as long as we do not currently have BTC and as long as we are going from a Sell signal previously,
#to a buy signal now
if signal == 1:
print("Buy Signal")
if hasToken == False and sellToBuyTransition == True:
try:
print("Buying")
currentUSDT = cf.getCoinBalance(client, 'USDT')
prices = client.get_order_book(symbol=market)
price = prices['asks'][0][0]
buyPrice = price
bestPrice = buyPrice
buyAmt = currentUSDT/float(price)
buyAmt = str(buyAmt)
qty = ""
for q in range(8):
qty += buyAmt[q]
buyAmt = qty
cf.executeBuy(client, market, buyAmt)
currentTokenBalance = buyAmt
hasToken = True
state = 0
time.sleep(10)
except Exception as e:
print(e)
else:
state = 0
time.sleep(10)
#Only sells when we actually have BTC to market sell!
if signal == 0:
print("Sell Signal")
if sellToBuyTransition == False:
sellToBuyTransition = True
if hasToken == True:
try:
print("Selling")
currentBtc = cf.getCoinBalance(client, 'BTC')
currentBtc = str(currentBtc)
qty = ""
for q in range(8):
qty += currentBtc[q]
currentBtc = qty
cf.executeSell(client, market, currentBtc)
currentTokenBalance = 0
hasToken = False
state = 0
time.sleep(10)
except Exception as e:
print(e)
else:
state = 0
time.sleep(10)