-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPI_handler.py
More file actions
482 lines (302 loc) · 11.3 KB
/
Copy pathAPI_handler.py
File metadata and controls
482 lines (302 loc) · 11.3 KB
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
### Binance API handler
import random
import uuid
from collections import deque
from datetime import datetime , timedelta
from clint.textui import puts , colored
import pandas as pd
## binance lib by sam
from binance.client import *
from binance.enums import *
##
from toolkit import *
from mail_order_info import *
from models import db
from models import Test_Order
from models import Live_Order
from config import sec , pub
client = Client( pub , sec )
####################### define class ########################
class fetch_coin:
def __init__ (self , coin ):
''' this create an object for each coin to perform operations on using the methods '''
coin_info = client.get_symbol_info(coin)
sub_dict3 = (coin_info['filters'])[3]
sub_dict2 = (coin_info['filters'])[2]
sub_dict = (coin_info['filters'])[0]
self.coin = coin
#self.balance = 0
## the average buy and sell prices
self.AVG_BUY = 0
self.AVG_SELL = 0
### this is the que for the sell and buy orders , pop one of each que and calculate profit,fee
self.deque_buy = deque()
self.deque_sell = deque()
self.test_deque_buy = deque()
self.test_deque_sell = deque()
## get min max and not values for a single trade
# min_not is the smallest order value allowed (amt * price ) = MIN_NOT
self.MIN_NOT = float()
self.MIN_QTY = float()
self.MAX_QTY = float()
#self.model = model
### two lists to hold all buy and sell trades in this session
self.buy_lst = []
self.sell_lst = []
self.ATH = 0
self.ATL = 0
self.profit = 0
################################################################
################################################################
def percent_change(self):
'''returns the change in price in a period of time '''
res = client.get_ticker(symbol=self.coin)
self.last_percentChange = float(res['priceChangePercent'])
return float(res['priceChangePercent'])
################################################################
################################################################
def get_coin_price(self):
''' get currennt coin price '''
coin__price = client.get_symbol_ticker(symbol=self.coin)['price']
return float(coin__price)
################################################################
################################################################
def check_balance(self):
''' check base asset balance '''
if str(self.balance) == "None":
print (" NO FUNDS LEFT !!!! ")
else:
print ( " YOU HAVE " + str(self.balance['free']) +" "+ str(self.balance['asset']))
try:
return str(self.balance['free'])
except TypeError as f:
return 0
################################################################
################################################################
def test_order(self , order_side , order_type ):
''' create a test order, takes order type '''
puts(colored.cyan("Creating a test order of type : {}".format(order_type)))
## define the trading amount which is 10 times the least allowed amount to trade with
#print (self.MIN_NOT *10 )
#amt = float(self.MIN_NOT) *10
amt = 0.3
if order_type == "LIMIT":
test_order_info = client.create_test_order(symbol=str(self.coin),
side=order_side,
type=order_type,
price=self.get_coin_price(),
timeInForce="GTC",
quantity=amt)
else:
test_order_info = client.create_test_order(symbol=str(self.coin),
side=order_side,
type=order_type,
quantity=amt)
TEST_DATA = {
"date_time":f"{datetime.now()}",
"symbol":f"{self.coin}",
"order_side":order_side,
"order_type":order_type,
"quantity":amt,
"price":f"{self.get_coin_price()}"}
if order_side == "SELL":
self.sell_lst.append(self.get_coin_price())
send_test_order_info(SYMBOL_=self.coin , SIDE_=order_side ,TYPE_=order_type , AMT_=amt ,PRICE_=self.get_coin_price() , PRED_PRICE=TEST_DATA['price'])
new = Test_Order(dt=datetime.utcnow(),\
symbol=self.coin,\
order_side=order_side,\
order_type=order_type,\
amt=amt,\
price=self.get_coin_price(),\
fee=(float(amt)*float(self.get_coin_price())*0.0075 ))
db.session.add(new)
db.session.commit()
puts(colored.magenta("Added new test order"))
return TEST_DATA
elif order_side == "BUY":
self.buy_lst.append(self.get_coin_price())
send_test_order_info(SYMBOL_=self.coin , SIDE_=order_side ,TYPE_=order_type , AMT_=amt ,PRICE_=self.get_coin_price() , PRED_PRICE=TEST_DATA['price'])
new = Test_Order(dt=datetime.utcnow(),\
symbol=self.coin,\
order_side=order_side,\
order_type=order_type,\
amt=amt,\
price=self.get_coin_price(),\
fee=(float(amt)*float(self.get_coin_price())*0.0075 ))
db.session.add(new)
db.session.commit()
puts(colored.magenta("Added new test order"))
return TEST_DATA
else:
return {}
################################################################
################################################################
def forecast_coin(self):
"""
this method fetchs the coinpair performance data
returns a dataframe
"""
#### max allowed by binance is 500 data-points
#### but you can change the "KLINE_INTERVAL_1MINUTE" check binance docs
#### https://python-binance.readthedocs.io/en/latest/binance.html
puts(colored.blue(f"Fetching data for coin-pair -> {self.coin}"))
candles = client.get_klines(symbol=str(self.coin), interval=client.KLINE_INTERVAL_1MINUTE , limit=130)
date_time = []
open_lst = []
high_lst = []
low_lst = []
close_lst = []
volume_lst = []
for item in candles:
t_time = float(item[0])/1000
dt_obj = datetime.fromtimestamp(t_time)
date_time.append(datetime.fromtimestamp(t_time))
open_lst.append(float(item[1]))
high_lst.append(float(item[2]))
low_lst.append(float(item[3]))
close_lst.append(float(item[4]))
volume_lst.append(float(item[5]))
## creating data frame
coin_data_frame = {
'date_time' : date_time,
'open' : open_lst,
'high' : high_lst,
'low' : low_lst,
'close' : close_lst,
'volume': volume_lst,
}
df_ = pd.DataFrame(coin_data_frame , columns = [ 'date_time' , 'open' , 'high' , 'low' , 'close','volume' ])
rolling_mean = df_['close'].rolling(window=5, min_periods=5 ).mean()
rolling_mean2 = df_['close'].rolling(window=10, min_periods=10 ).mean()
df_['5_sma'] = rolling_mean
df_['10_sma'] = rolling_mean2
df_.dropna(subset = ["5_sma"], inplace=True)
df_.dropna(subset = ["10_sma"], inplace=True)
self.df = df_.tail(120).reset_index(drop=True)
return self.df
def check_orders(self):
''' check open orders of coin pair '''
open_orders_lst = client.get_open_orders(symbol=self.coin)
return open_orders_lst , len(open_orders_lst)
def limit_sell_order(self , sell_price):
''' a method to create a limit order of type sell this order will be open until the
current coin price reaches the limit then the order is excuted '''
quant = self.MIN_QTY * int (random.randrange(10, 20)) *10
order = client.order_limit_sell(
symbol=self.coin,
quantity="0.15",
timeInForce = "GTC",
price=sell_price)
return order
################################################################
################################################################
def limit_buy_order(self , buy_price):
''' a method to create a limit order of type buy this order will be open until the
current coin price reaches the limit then the order is excuted '''
quant = self.MIN_QTY * int (random.randrange(10, 20)) *10
order = client.order_limit_buy(
symbol=self.coin,
quantity="0.15",
timeInForce = "GTC",
price=buy_price)
return order
def market_BUY(self , amt ):
''' the bot executes a BUY with the market price at that moment '''
try:
BUY_order = client.create_order(symbol=self.coin ,type="MARKET" , quantity=str(amt), side="BUY" )
trade_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(BUY_order['transactTime']/1000)))
send_order_info(SYMBOL_=str(self.coin),\
TYPE_="BUY",\
AMT_=float(amt),\
PRICE_=str(BUY_order['fills'][0]['price']))
td = {"date_time":datetime.utcnow(),\
"symbol":str(self.coin),\
"order_side":"BUY",\
"order_type":"MARKET",\
"quantity":amt,\
"price":float(BUY_order['fills'][0]['price']),\
"fee":float(BUY_order['fills'][0]['commission'])}
add_order = Live_Order(dt=td["date_time"],\
symbol=td["symbol"],\
order_side=td["order_side"],\
order_type=td["order_type"],\
amt=td["quantity"],\
price=td["price"],\
fee=td["fee"],\
order_id=str(uuid.uuid4()))
db.session.add(add_order)
db.session.commit()
return td
except BinanceAPIException as e:
print (e.status_code)
return None
################################################################
################################################################
def market_SELL(self , amt ):
''' the bot executes a SELL with the market price at that moment '''
try:
SELL_order = client.create_order(symbol=self.coin ,type="MARKET" , quantity=str(amt), side="SELL" )
trade_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(SELL_order['transactTime']/1000)))
send_order_info(SYMBOL_=str(self.coin),\
TYPE_="SELL",\
AMT_=float(amt),\
PRICE_=str(SELL_order['fills'][0]['price']))
td = {"date_time":datetime.utcnow(),\
"symbol":str(self.coin),\
"order_side":"SELL",\
"order_type":"MARKET",\
"quantity":amt,\
"price":float(SELL_order['fills'][0]['price']),\
"fee":float(SELL_order['fills'][0]['commission'])}
add_order = Live_Order(dt=td["date_time"],\
symbol=td["symbol"],\
order_side=td["order_side"],\
order_type=td["order_type"],\
amt=td["quantity"],\
price=td["price"],\
fee=td["fee"],\
order_id=str(uuid.uuid4()))
db.session.add(add_order)
db.session.commit()
return td
except BinanceAPIException as e:
print (e.status_code)
return None
#try:
#obj = fetch_coin("BTCRUB")
#obj.market_SELL(amt=0.0001)
#obj.market_BUY(amt=0.0001)
#except:
# print ("Error")
#from toolkit import all_sells, all_buys
#lst = all_sells("BTCRUB", "MARKET", test=False)
#lst2 = all_buys("BTCRUB", "MARKET", test=False)
#print (len(lst2) , len(lst))
"""
if __name__ == "__main__":
clear_screen()
portfolio = ['BNBBUSD', 'BTCBUSD']#, 'BTCRUB','BNBBTC','BNBETH']
obj_lst = [ fetch_coin(item) for item in portfolio ]
for item in obj_lst:
response = parse_dataframe(item.forecast_coin() , item.coin)
item.limit_buy_order(buy_price)
item.limit_sell_order(sell_price)
if response == "SELL":
puts(colored.red("This is a SELL trade "))
elif response == "BUY":
puts(colored.green("This is a BUY trade "))
else:
puts(colored.yellow("This is a HOLD"))
puts(colored.blue("\n\n"))
#item.test_order(order_side="BUY" , order_type="MARKET")
#read_test_orders()
print ("\n\n")
RESULTS = get_symbol('BTCRUB')
print (f"Found {len(RESULTS)}")
"""
"""
if __name__ == "__main__":
obj = fetch_coin(coin="BNBBTC")
obj.forecast_coin()
parse_dataframe(obj , coinpair=obj.coin)
"""