-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtBot.py
329 lines (264 loc) · 10.8 KB
/
rtBot.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
from binance.client import AsyncClient
from dotenv import dotenv_values
from enum import Enum
from random import randint
import asyncio
import json
import re
import time
config = dotenv_values(".env")
class rtSide(Enum):
OPEN = "OPEN"
CLOSE = "CLOSE"
class orderSide(Enum):
BUY = "BUY"
SELL = "SELL"
class orderStatus(Enum):
CANCELED = "CANCELED"
EXPIRED = "EXPIRED"
FILLED = "FILLED"
NEW = "NEW"
PARTIALLY_FILLED = "PARTIALLY_FILLED"
PENDING_CANCEL = "PENDING_CANCEL"
REJECTED = "REJECTED"
class orderType(Enum):
LIMIT = "LIMIT"
LIMIT_MAKER = "LIMIT_MAKER"
MARKET = "MARKET"
STOP_LOSS = "STOP_LOSS"
STOP_LOSS_LIMIT = "STOP_LOSS_LIMIT"
TAKE_PROFIT = "TAKE_PROFIT"
TAKE_PROFIT_LIMIT = "TAKE_PROFIT_LIMIT"
class timeInForce(Enum):
FOK = "FOK"
GTC = "GTC"
IOC = "IOC"
class rtBot:
"""Range Trading Bot"""
def __init__(self, symbol="BUSDUSDT", baseAsset="BUSD", quoteAsset="USDT", lowerBound=0.9990, upperBound=1.0010):
self.accountInfo = None
self.apiKey = config.get("api_key")
self.apiSecret = config.get("api_secret")
self.assets = {}
self.baseAsset = baseAsset
self.binance = None
self.lowerBound = lowerBound
self.orderIdPrefix = "RT1"
self.orders = {
"all": [],
"filled": [],
"new": [],
"rt": []
}
self.quoteAsset = quoteAsset
self.rdbHost = config.get("rdbHost") or "localhost"
self.rdbPort = config.get("rdbPort") or 28015
self.rtTable = config.get("rdbTable") or "rtBot"
self.symbol = symbol
self.takeProfitAmount = 0.0001
self.upperBound = upperBound
def createOrderId(self, side=False, id=False):
if (not side):
return False
if (id):
return f'{self.orderIdPrefix}_{side}_{id}'
else:
return f'{self.orderIdPrefix}_{side}_{int(time.time())}_{randint(1000, 9999999)}'
def createTakeProfitOrder(self, order={}):
rtOrder = self.isRtOrder(order)
if (not rtOrder or
not float(order.get("price")) or
rtOrder.groups()[0] != rtSide.OPEN.name
):
return False
newClientOrderId = self.createOrderId(
rtSide.CLOSE.name, rtOrder.groups()[1])
if (order.get("side") == orderSide.BUY.name):
targetSide = orderSide.SELL.name
targetPrice = float(order.get("price")) + self.takeProfitAmount
else:
targetSide = orderSide.BUY.name
targetPrice = float(order.get("price")) - self.takeProfitAmount
return {
"newClientOrderId": newClientOrderId,
"quantity": order.get("executedQty") if order.get("executedQty") else order.get("quantity"),
"price": targetPrice,
"side": targetSide,
"symbol": order.get("symbol"),
"timeInForce": timeInForce.GTC.name,
"type": orderType.LIMIT.name
}
def determinNewRtOrders(self, price=0, maxOrders=2):
iteration = 0
nextOrders = []
if price < 1 and price > self.lowerBound:
while iteration < maxOrders:
nextOrders.append({
"newClientOrderId": self.createOrderId(rtSide.OPEN.name),
"quantity": 20,
"price": round(round(price, 4) - self.takeProfitAmount * iteration, 4),
"side": orderSide.BUY.name,
"symbol": self.symbol,
"timeInForce": timeInForce.GTC.name,
"type": orderType.LIMIT.name
})
iteration += 1
elif price > 1 and price < self.upperBound:
while iteration < maxOrders:
nextOrders.append({
"newClientOrderId": self.createOrderId(rtSide.OPEN.name),
"quantity": 20,
"price": round(price + self.takeProfitAmount * iteration, 4),
"side": orderSide.SELL.name,
"symbol": self.symbol,
"timeInForce": timeInForce.GTC.name,
"type": orderType.LIMIT.name
})
iteration += 1
return nextOrders
def existsTakeProfitOrder(self, checkOrder={}):
for order in self.orders.get("rt"):
rtOrder = self.isRtOrder(order)
rtCheckOrder = self.isRtOrder(checkOrder)
if (rtCheckOrder and
rtOrder.groups()[0] == rtSide.CLOSE.name and
rtOrder.groups()[1] == rtCheckOrder.groups()[1]
):
return True
return False
def setupRdb(self):
pass
#self.rdbConnection = r.connect(host=self.rdbHost)
def isRtOrder(self, order={}):
# print("search 4", order)
regExp = f'^{self.orderIdPrefix}_({rtSide.CLOSE.name}|{rtSide.OPEN.name})_(.*)'
# print("regexp", regExp)
if (order.get("clientOrderId")):
return re.search(regExp, order.get("clientOrderId"))
if (order.get("newClientOrderId")):
return re.search(regExp, order.get("newClientOrderId"))
return False
def isRtOrderAlreadyOpen(self, checkOrder={}):
for rtOrder in self.orders.get("rt"):
matchRtOrder = self.isRtOrder(rtOrder)
matchCheckOrder = self.isRtOrder(checkOrder)
if (
matchRtOrder and
matchCheckOrder and
matchRtOrder.groups()[0] == matchCheckOrder.groups()[0] and
matchRtOrder.groups()[1] == matchCheckOrder.groups()[1]
):
return True
if (rtOrder.get("status") == "NEW" and
float(rtOrder.get("origQty")) == float(checkOrder.get("quantity")) and
float(rtOrder.get("price")) == float(checkOrder.get("price")) and
rtOrder.get("symbol") == checkOrder.get("symbol") and
rtOrder.get("side") == checkOrder.get("side")):
return True
return False
async def placeOrder(self, order={}):
try:
await self.binance.create_order(
newClientOrderId=order.get("newClientOrderId"),
price=order.get("price"),
quantity=order.get("quantity"),
side=order.get("side"),
symbol=order.get("symbol"),
timeInForce=order.get("timeInForce"),
type=order.get("type"))
await self.syncOrders()
return True
except:
print("Error placeOrder")
return False
def printOrders(self, orders=[{}]):
for order in orders:
print(order.get("clientOrderId"), order.get("price"),
order.get("side"), order.get("status"))
def setOrders(self, orders=[]):
self.orders.update(all=orders)
self.orders.update(filled=[])
self.orders.update(new=[])
self.orders.update(rt=[])
for order in self.orders.get("all"):
isRtOrder = self.isRtOrder(order)
if (order.get("status") == orderStatus.FILLED.name):
self.orders.get("filled").append(order)
if (order.get("status") == "NEW"):
self.orders.get("new").append(order)
if (isRtOrder and
(order.get("status") == orderStatus.FILLED.name or
order.get("status") == "NEW"
)
):
self.orders.get("rt").append(order)
def setRdbConnection(self, host):
pass
""" self.rdbConnection = r.connect(host=self.rdbHost, port=self.rdbPort)
try:
r.db_create(self.rtTable).run(self.rdbConnection)
except RqlRuntimeError:
print 'App database already exists. Run the app without --setup.'
finally:
self.rdbConnection.close() """
async def setTakeProfitOrders(self):
for order in self.orders.get("rt"):
if (order.get("status") == orderStatus.FILLED.name and
not self.existsTakeProfitOrder(order)):
takeProfitOrder = self.createTakeProfitOrder(order)
print("open tp order", takeProfitOrder)
await self.placeOrder(order=takeProfitOrder)
self.printOrders(orders=self.orders.get("new"))
async def startTrading(self):
try:
if not self.binance:
self.binance = await AsyncClient.create(self.apiKey, self.apiSecret)
if not await self.syncOrders() or not self.binance:
return False
avgPrice = await self.binance.get_avg_price(symbol=self.symbol)
price = round(float(avgPrice.get("price")), 4)
print("price", price)
await self.setTakeProfitOrders()
nextOrders = self.determinNewRtOrders(price)
# print("next orders", nextOrders)
balanceBaseAsset = await self.binance.get_asset_balance(asset=self.baseAsset)
balanceQuoteAsset = await self.binance.get_asset_balance(asset=self.quoteAsset)
for newOrder in nextOrders:
takeProfitOrder = self.createTakeProfitOrder(newOrder)
if (not self.isRtOrderAlreadyOpen(newOrder) and
not self.isRtOrderAlreadyOpen(takeProfitOrder)):
balance = balanceQuoteAsset if newOrder.get(
"side") == orderSide.BUY.name else balanceBaseAsset
if (float(balance.get("free")) > float(newOrder.get("quantity"))):
print("open new order", newOrder, balance.get(
"free"), newOrder.get("quantity"), balance.get("asset"))
await self.placeOrder(order=newOrder)
else:
print("NICHT GENUG GELD!!!")
self.printOrders(orders=self.orders.get("new"))
return True
except:
print("Fehler beim Trading")
return False
async def syncBalance(self, asset=""):
self.assets[asset] = await self.binance.get_asset_balance(asset=self.baseAsset)
async def syncOrders(self, symbol="BUSDUSDT"):
try:
allOrders = await self.binance.get_all_orders(symbol=symbol)
self.setOrders(allOrders)
return True
except:
print("Error syncOrders")
return False
async def main():
# initialise the client
bot = rtBot("BUSDUSDT")
run = True
while run:
await bot.startTrading()
time.sleep(10)
await bot.binance.close_connection()
if __name__ == "__main__":
print("start rtBot")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())