-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbugtoei2.py
More file actions
483 lines (427 loc) · 18.4 KB
/
bugtoei2.py
File metadata and controls
483 lines (427 loc) · 18.4 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
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 09:35:14 2022
@author: pascharapun.j
"""
import hashlib
import hmac
import json
import requests
import sched, time
API_HOST = 'https://api.bitkub.com'
apikey = 'APIKEY_BITKUB'
apisecret = b'APISECRET_BITKUB'
fund = 21000
gap = 13
MyWatcher = ['BTC','KUB','DOGE','MANA','IOST','SOL','LUNA','ZIL','XLM']
API_KEY = apikey
API_SECRET = apisecret
condition = {'THB_KUB':{'buy':90,'sell':200},
'THB_DOGE':{'buy':2.9,'sell':15},
'THB_MANA':{'buy':30,'sell':99},
'THB_IOST':{'buy':0.55,'sell':2},
'THB_SOL':{'buy':1700,'sell':3000},
'THB_ZIL':{'buy':1.7,'sell':5},
'THB_XLM':{'buy':3.7,'sell':14},
'THB_LUNA':{'buy':0.001,'sell':1000},
}
# rebalanceTarget = { 'THB_KUB':6400,
# 'THB_DOGE':6571,
# 'THB_MANA':10,
# 'THB_IOST':10,
# 'THB_SOL':5000,
# 'THB_ZIL':1000,
# 'THB_XLM':497,
# 'THB_LUNA':534,
# }
rebalanceTarget = { 'THB_SUSHI':400 }
s = sched.scheduler(time.time, time.sleep)
errorCode = {
0:'No error',
1:'Invalid JSON payload',
2:'Missing X-BTK-APIKEY',
3:'Invalid API key',
4:'API pending for activation',
5:'IP not allowed',
6:'Missing / invalid signature',
7:'Missing timestamp',
8:'Invalid timestamp',
9:'Invalid user',
10:'Invalid parameter',
11:'Invalid symbol',
12:'Invalid amount',
13:'Invalid rate',
14:'Improper rate',
15:'Amount too low',
16:'Failed to get balance',
17:'Wallet is empty',
18:'Insufficient balance',
19:'Failed to insert order into db',
20:'Failed to deduct balance',
21:'Invalid order for cancellation',
22:'Invalid side',
23:'Failed to update order status',
24:'Invalid order for lookup',
25:'KYC level 1 is required to proceed',
30:'Limit exceeds',
40:'Pending withdrawal exists',
41:'Invalid currency for withdrawal',
42:'Address is not in whitelist',
43:'Failed to deduct crypto',
44:'Failed to create withdrawal record',
45:'Nonce has to be numeric',
46:'Invalid nonce',
47:'Withdrawal limit exceeds',
48:'Invalid bank account',
49:'Bank limit exceeds',
50:'Pending withdrawal exists',
51:'Withdrawal is under maintenance',
52:'Invalid permission',
53:'Invalid internal address',
54:'Address has been deprecated',
55:'Cancel only mode',
90:'Server error (please contact support)',
}
def json_encode(data):
return json.dumps(data, separators=(',', ':'), sort_keys=True)
def sign(data):
j = json_encode(data)
# print('Signing payload: ' + j)
h = hmac.new(API_SECRET, msg=j.encode(), digestmod=hashlib.sha256)
return h.hexdigest()
def getServerTime():
response = requests.get(API_HOST + '/api/servertime')
ts = int(response.text)
# print('Server time: ' + response.text)
return(ts)
def CheckCondition(sc,coin,price):
# coin= 'THB_BTC', price = 1050000
text = ''
check_buy = condition[coin]['buy']
if price <= check_buy:
txt = '{} ราคาลงแล้ว เหลือ: {:,.3f} รีบซื้อด่วน!\n(ราคาที่อยากได้: {:,.3f})'.format(coin,price,check_buy)
#print(txt)
text += txt + '\n'
sendLine(text)
check_sell = condition[coin]['sell']
if price >= check_sell:
txt = '{} ราคาขึ้นแล้ว ล่าสุดเป็น: {:,.3f} รีบขายด่วน!\n(ราคาที่อยากขาย: {:,.3f})'.format(coin,price,check_sell)
#print(txt)
text += txt + '\n'
sendLine(text)
print('CheckCondition',coin,price)
# s.enter(10, 1, CheckCondition, kwargs={'sc':s,'coin': coin,'price': price})
return text
def buy(_pair,_amt,_rat):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': API_KEY,
}
data = {
'sym': _pair,
'amt': _amt, # THB amount you want to spend
'rat': _rat,
'typ': 'limit',
'ts': getServerTime(),
}
signature = sign(data)
data['sig'] = signature
print('Payload with signature: ' + json_encode(data))
response = requests.post(API_HOST + '/api/market/place-bid', headers=header, data=json_encode(data))
res = response.json()
if(res['error']==0):
sendLine('ซื้อเข้า :{} ที่ราคา : {:,.3f} จำนวน : {} โดนค่า Fee {:,.3f}฿'.format(_pair,_rat,_amt,res['result']['fee']))
else:
sendLine('ซื้อเข้า :{} ที่ราคา : {:,.3f} จำนวน : {} ผลลัพธ์ {}฿'.format(_pair,_rat,_amt,errorCode[res['error']]))
return response
def sell(_pair,_amt,_rat):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': API_KEY,
}
data = {
'sym': _pair,
'amt': _amt, # THB amount you want to spend
'rat': _rat,
'typ': 'limit',
'ts': getServerTime(),
}
signature = sign(data)
data['sig'] = signature
print('Payload with signature: ' + json_encode(data))
response = requests.post(API_HOST + '/api/market/place-ask', headers=header, data=json_encode(data))
res = response.json()
#data = data['result']
if(res['error']==0):
sendLine('ขายออก :{} ที่ราคา : {:,.3f} จำนวน : {} โดนค่า Fee {:,.3f}฿'.format(_pair,_rat,_amt,res['result']['fee']))
else:
sendLine('ขายออก :{} ที่ราคา : {:,.3f} จำนวน : {} แต่ Error {}฿'.format(_pair,_rat,_amt,errorCode[res['error']]))
return response
def checkBalance():
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': API_KEY,
}
data = {
'ts': getServerTime(),
}
signature = sign(data)
data['sig'] = signature
# print('Payload with signature: ' + json_encode(data))
response = requests.post(API_HOST + '/api/market/balances', headers=header, data=json_encode(data))
data = response.json()
data = data['result']
# print(response.json())
return(data)
def sendLine(_msg):
token = 'LINENOTIFYTOKEN'
url = "https://notify-api.line.me/api/notify"
headers = {'content-type':'application/x-www-form-urlencoded','Authorization':'Bearer '+token}
r = requests.post(url, headers=headers, data = {'message':_msg})
# print (r.text)
def getAllPrice():
response = requests.get(API_HOST + '/api/market/ticker')
result = response.json()
return result
def calc(sc):
allText = ''
dataBalance = checkBalance()
THB = dataBalance['THB']['available']
THBReserve = dataBalance['THB']['reserved']
AllMyMoney = 0
THBinCOIN = 0
result = getAllPrice()
for i in dataBalance:
if dataBalance[i]['reserved'] > 0 or dataBalance[i]['available'] > 0 :
dataBalance[i]['symbol'] = i
# for c in MyWatcher:
sym = dataBalance[i]['symbol']
currentSym = 'THB_'+sym
if currentSym in rebalanceTarget:
rebalText = rebalance('THB_'+sym,sym,rebalanceTarget['THB_'+sym],True,gap)
dataBalance = checkBalance()
THB = dataBalance['THB']['available']
THBReserve = dataBalance['THB']['reserved']
result = getAllPrice()
else:
rebalText = 'ไม่เปิดบอท'
available = dataBalance[i]['available']
reserved = dataBalance[i]['reserved']
try:
data = result['THB_'+sym]
last = data['last']
myMoney = (reserved + available) * last
# xx = THBinCOIN + myMoney
THBinCOIN += myMoney
# AllMyMoney += xx
text = ' {} : {}\n Has : {}{} \n Order : {} {}\n THB : {:,.2f}฿ \n {} \n\n'.format(str(sym),str(last),str(available),str(sym),str(reserved),str(sym),myMoney,rebalText)
allText += text
except KeyError:
continue
if(THBReserve==0):
x =(THB + THBinCOIN) - fund
else:
x = (THBReserve +(THB + THBinCOIN)) - fund
xText = '{:,.2f}฿'.format(x)
AllMyMoney = (THB+THBinCOIN+THBReserve )
sendBalanceText =' ทุนให้บอท : {}฿ \n {} : {}฿ \n เงินในเหรียญ : {:,.2f}฿ \n เงินใน Order : {:,.2f}฿ \n กำไรขาดทุน {:,.2f}฿ \n รวม {:,.2f}฿ \n '.format(str(fund),str('เงินสด'),str(THB),THBinCOIN,THBReserve,x,AllMyMoney)
sendLine( '```'+allText+'```' + '\n ' + '```' + sendBalanceText + '```')
# def calc(sc):
# result = getAllPrice()
# dataBalance = checkBalance()
# THB = dataBalance['THB']['available']
# THBReserve = dataBalance['THB']['reserved']
# THBinCOIN = 0
# allText = ''
# for c in MyWatcher:
# sym = c
# data = result['THB_'+sym]
# last = data['last']
# available = dataBalance[c]['available']
# reserved = dataBalance[c]['reserved']
# myMoney = (reserved + available) * last
# xx = THBinCOIN + myMoney
# THBinCOIN = xx
# print(sym, last)
# rebalText = rebalance('THB_'+sym,sym,rebalanceTarget['THB_'+sym])
# text = ' \n {} : {}\n Has : {}{} \n Order : {} {}\n THB : {:,.2f}฿ \n {} \n'.format(str(sym),str(last),str(available),str(sym),str(reserved),str(sym),myMoney,rebalText)
# allText += text
# if(THBReserve==0):
# x =(THB + THBinCOIN) - fund
# else:
# x = (THBReserve +(THB + THBinCOIN)) - fund
# xText = '{:,.2f}฿'.format(x)
# sendBalanceText =' ทุน : {}฿ \n {} : {}฿ \n เงินในเหรียญ : {:,.2f}฿ \n เงินใน Order : {:,.2f}฿ \n กำไรขาดทุน {:,.2f}฿ \n '.format(str(fund),str('เงินสด'),str(THB),THBinCOIN,THBReserve,x)
# sendLine( '``` '+xText+ ' \n '+allText+'```' + '\n ' + '```' + sendBalanceText + '```')
# # sc.enter(60, 1, calc, (sc,))
# def balances():
# header = {
# 'Accept': 'application/json',
# 'Content-Type': 'application/json',
# 'X-BTK-APIKEY': API_KEY,
# }
# data = {
# 'ts': getServerTime(),
# }
# signature = sign(data)
# data['sig'] = signature
# # print('Payload with signature: ' + json_encode(data))
# response = requests.post(API_HOST + '/api/market/balances', headers=header, data=json_encode(data))
# data = response.json()
# #data = data['result']
# # print(response.json())
# return(data)
def ticker(_sym):
# header = {
# 'Accept': 'application/json',
# 'Content-Type': 'application/json',
# 'X-BTK-APIKEY': API_KEY,
# }
# data = {
# 'ts': getServerTime(),
# }
# signature = sign(data)
# data['sig'] = signature
# print('Payload with signature: ' + json_encode(data))
response = requests.get(API_HOST + '/api/market/ticker?sym='+_sym)
data = response.json()
#data = data['result']
# print(response.json())
return(data)
def balances():
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': API_KEY,
}
data = {
'ts': getServerTime(),
}
signature = sign(data)
data['sig'] = signature
# print('Payload with signature: ' + json_encode(data))
response = requests.post(API_HOST + '/api/market/balances', headers=header, data=json_encode(data))
data = response.json()
#data = data['result']
# print(response.json())
return(data)
def rebalance(_pair , _token_name , _target,_OrderActivate,_gap):
returnText = ''
pair = _pair#'THB_KUB' #เหรียญ
token_name =_token_name #'KUB' #เหรียญ
balance_coin=balances()
balance_coin=balance_coin['result'][token_name]['available'] + balance_coin['result'][token_name]['reserved']
#print('จำนวนเหรียญในบัญชี' , balance_coin , 'เหรียญ')
balance_thb=balances()
balance_thb=balance_thb['result']['THB']['available'] + balance_thb['result']['THB']['reserved']
#print('จำนวนเงินในบัญชี' , balance_thb , 'บาท')
last_price = ticker(pair)
last_price = last_price[pair]['last']
#print('ราคาเหรียญล่าสุด' , last_price , 'บาท')
balance_value = balance_coin*last_price
#print('มูลค่าเหรียญ' , balance_value , 'บาท')
# port = balance_thb + balance_value
# portfolio = 'มูลค่าพอร์ต {:,.2f} บาท'.format(port)
# print('มูลค่าพอร์ต' , portfolio , 'บาท')
fix_value = _target #ใส่จำนวนเงินที่ต้องการrebalance
amount = balance_value - fix_value
print(balance_value , ': balance_value <> fix_value :',fix_value , ' amount :' , amount)
if balance_value > fix_value:
amount = balance_value - fix_value
amountToSell = amount / last_price
# print(amount)
if amount > _gap: #มูลค่าเพิ่มมากกว่าเท่าไหร่ถึงจะแจ้งเตือน
print('ขายออก' , amount , 'บาท')
#print(type(amount))
#messenger.sendtext('Sell ' + str(float(amount)) +' Baht')
# sendLine('{} Sell {:,.2f} baht @ {:,.2f} '.format(_pair,amount,last_price))
if _OrderActivate == True:
sell(_pair,amountToSell,last_price)
returnText = '{} Sell {:,.2f} baht @ {:,.2f} '.format(_pair,amountToSell,last_price)
else:
# print('Rebalance : Waiting')
returnText = 'Rebalance : Waiting'
# messenger.sendtext('Rebalance : Waiting')
elif balance_value < fix_value:
amount = fix_value - balance_value
# print(amount)
if amount > _gap: #มูลค่าลดมากกว่าเท่าไหร่ถึงจะแจ้งเตือน
print('ซื้อเข้า' , amount , 'บาท')
# sendLine('{} Buy {:,.2f} baht @ {:,.2f} '.format(_pair,amount,last_price))
if _OrderActivate == True:
buy(_pair,amount,last_price)
returnText = '{} Buy {:,.2f} baht @ {:,.2f} '.format(_pair,amount,last_price)
else:
# print('Rebalance : Waiting')
returnText = 'Rebalance : Waiting'
#messenger.sendtext('Rebalance : Waiting')
else:
# print('Not yet')
returnText = 'Not yet'
return returnText
# def rebalance(_pair , _token_name , _target):
# returnText = ''
# pair = _pair#'THB_KUB' #เหรียญ
# token_name =_token_name #'KUB' #เหรียญ
# balance_coin=balances()
# balance_coin=balance_coin['result'][token_name]['available'] + balance_coin['result'][token_name]['reserved']
# #print('จำนวนเหรียญในบัญชี' , balance_coin , 'เหรียญ')
# balance_thb=balances()
# balance_thb=balance_thb['result']['THB']['available'] + balance_thb['result']['THB']['reserved']
# #print('จำนวนเงินในบัญชี' , balance_thb , 'บาท')
# last_price = ticker(pair)
# last_price = last_price[pair]['last']
# #print('ราคาเหรียญล่าสุด' , last_price , 'บาท')
# balance_value = balance_coin*last_price
# #print('มูลค่าเหรียญ' , balance_value , 'บาท')
# port = balance_thb + balance_value
# # portfolio = 'มูลค่าพอร์ต {:,.2f} บาท'.format(port)
# # print('มูลค่าพอร์ต' , portfolio , 'บาท')
# fix_value = _target #ใส่จำนวนเงินที่ต้องการrebalance
# if balance_value > fix_value:
# amount = balance_value - fix_value
# if amount > 10: #มูลค่าเพิ่มมากกว่าเท่าไหร่ถึงจะแจ้งเตือน
# #print('ขายออก' , amount , 'บาท')
# #print(type(amount))
# #messenger.sendtext('Sell ' + str(float(amount)) +' Baht')
# # sendLine('{} Sell {:,.2f} baht @ {:,.2f} '.format(_pair,amount,last_price))
# returnText = '{} Sell {:,.2f} baht @ {:,.2f} '.format(_pair,amount,last_price)
# else:
# # print('Rebalance : Waiting')
# returnText = 'Rebalance : Waiting'
# # messenger.sendtext('Rebalance : Waiting')
# elif balance_value < fix_value:
# amount = fix_value - balance_value
# if amount > 10: #มูลค่าลดมากกว่าเท่าไหร่ถึงจะแจ้งเตือน
# # print('ซื้อเข้า' , amount , 'บาท')
# # sendLine('{} Buy {:,.2f} baht @ {:,.2f} '.format(_pair,amount,last_price))
# returnText = '{} Buy {:,.2f} baht @ {:,.2f} '.format(_pair,amount,last_price)
# else:
# # print('Rebalance : Waiting')
# returnText = 'Rebalance : Waiting'
# #messenger.sendtext('Rebalance : Waiting')
# else:
# # print('Not yet')
# returnText = 'Not yet'
# return returnText
def main():
# s.enter(1, 1, calc, (s,))
calc(sc=None)
# dataPrice = getAllPrice()
# allText = ''
# for c in MyWatcher:
# sym = c
# rebalance('THB_'+sym,sym,rebalanceTarget['THB_'+sym])
# data = dataPrice['THB_'+sym]
# last = data['last']
# CheckCondition(sc=None,coin='THB_'+sym , price=last)
# s.enter(5, 1, CheckCondition, kwargs={'sc':s,'coin': 'THB_'+sym,'price': last})
# s.run()
print('-----')
# exit()
# time.sleep(60)
if __name__ == "__main__":
main()