-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapibutkib.py
More file actions
1329 lines (1145 loc) · 55.3 KB
/
apibutkib.py
File metadata and controls
1329 lines (1145 loc) · 55.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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- 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
import pandas as pd
import pandas_ta as ta
import datetime
import os
from uuid import uuid4
from termcolor import colored
import cowsay
import talib
import numpy as np
import asyncio
from numpy import mean
import math
class BugKib:
API_HOST = 'https://api.bitkub.com'
fund = 500
gap = 10
MyWatcher = ['ZIL']
# API_KEY = apikey
# API_SECRET = apisecret
API_BITKUB_HOST='https://api.bitkub.com'
API_BITKUB_CURRENCY='THB'
API_BITKUB_TIMEFRAME='30,60,240,1D'
API_LIMIT=50
API_EMA_FAST=9
API_EMA_SLOW=26
condition = {
'THB_ZIL':{'buy':0.55,'sell':25},
}
rebalanceTarget = {
'THB_ZIL':250,
}
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)',
}
ENDPOINTS = {
"API_ROOT": "https://api.bitkub.com",
"STATUS_PATH": "/api/status",
"SERVERTIME_PATH": "/api/servertime",
"MARKET_SYMBOLS_PATH": "/api/market/symbols",
"MARKET_TICKER_PATH": "/api/market/ticker?sym={sym}",
"MARKET_TRADES_PATH": "/api/market/trades?sym={sym}&lmt={lmt}",
"MARKET_BIDS_PATH": "/api/market/bids?sym={sym}&lmt={lmt}",
"MARKET_ASKS_PATH": "/api/market/asks?sym={sym}&lmt={lmt}",
"MARKET_BOOKS_PATH": "/api/market/books?sym={sym}&lmt={lmt}",
"MARKET_TRADING_VIEW_PATH": "/tradingview/history?symbol={sym}&resolution={int}&from={frm}&to={to}",
"MARKET_DEPTH_PATH": "/api/market/depth?sym={sym}&lmt={lmt}",
"MARKET_WALLET": "/api/market/wallet",
"MARKET_BALANCES": "/api/market/balances",
"MARKET_PLACE_BID": "/api/market/place-bid",
"MARKET_PLACE_BID_TEST": "/api/market/place-bid/test",
"MARKET_PLACE_ASK": "/api/market/place-ask",
"MARKET_PLACE_ASK_TEST": "/api/market/place-ask/test",
"MARKET_PLACE_ASK_BY_FIAT": "/api/market/place-ask-by-fiat",
"MARKET_CANCEL_ORDER": "/api/market/cancel-order",
"MARKET_MY_OPEN_ORDERS": "/api/market/my-open-orders",
"MARKET_MY_ORDER_HISTORY": "/api/market/my-order-history",
"MARKET_ORDER_INFO": "/api/market/order-info",
"CRYPTO_ADDRESSES": "/api/crypto/addresses?p={p}&lmt={lmt}",
"CRYPTO_WITHDRAW": "/api/crypto/withdraw",
"CRYPTO_INTERNAL_WITHDRAW": "/api/crypto/internal-withdraw",
"CRYPTO_DEPOSIT_HISTORY": "/api/crypto/deposit-history?p={p}&lmt={lmt}",
"CRYPTO_WITHDRAW_HISTORY": "/api/crypto/withdraw-history?p={p}&lmt={lmt}",
"CRYPTO_GENERATE_ADDRESS": "/api/crypto/generate-address?sym={sym}",
"FIAT_ACCOUNTS": "/api/fiat/accounts?p={p}&lmt={lmt}",
"FIAT_WITHDRAW": "/api/fiat/withdraw",
"FIAT_DEPOSIT_HISTORY": "/api/fiat/deposit-history?p={p}&lmt={lmt}",
"FIAT_WITHDRAW_HISTORY": "/api/fiat/withdraw-history",
"MARKET_WSTOKEN": "/api/market/wstoken",
"USER_LIMITS": "/api/user/limits",
"USER_TRADING_CREDITS": "/api/user/trading-credits",
}
s = sched.scheduler(time.time, time.sleep)
def __init__(self,_apiKey='APIKEY_BITKUB' ,_apisecret = b'APISECRET_BITKUB'):
"""
Library นี้ Copy มาไอวัว
"""
# apikey = 'APIKEY_BITKUB'
# apisecret = b'APISECRET_BITKUB'
# API info
self.API_HOST = self.API_HOST
self.API_KEY = _apiKey
self.API_SECRET = _apisecret
self.API_CURRENCY = self.API_BITKUB_CURRENCY
self.API_TIMEFRAME = self.API_BITKUB_TIMEFRAME
self.API_LIMIT = int(self.API_LIMIT)
self.API_EMA_FAST = int(self.API_EMA_FAST)
self.API_EMA_SLOW = int(self.API_EMA_SLOW)
self.apiKey = _apiKey
self.apisecret = _apisecret
self.API_HEADER = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
def routeAPI(self, _endpoint, **kwargs):
"""
Get full endpoint for a specific path.
"""
return self.API_HOST + self.ENDPOINTS[_endpoint].format(**kwargs)
def json_encode(self,data):
return json.dumps(data, separators=(',', ':'), sort_keys=True)
@staticmethod
def __json_encode(data):
return json.dumps(data, separators=(',', ':'), sort_keys=True)
def sign(self,data):
j = self.json_encode(data)
# print('Signing payload: ' + j)
h = hmac.new(self.API_SECRET, msg=j.encode(), digestmod=hashlib.sha256)
return h.hexdigest()
def getServerTime(self):
response = requests.get(self.API_HOST + '/api/servertime')
ts = int(response.text)
return(ts)
def timeserver(self):
response = requests.get(self.API_HOST + '/api/servertime')
ts = int(response.text)
return(ts)
def get_wallets_assets(self):
data = {
'ts': self.timeserver(),
}
signature = self.sign(data)
data['sig'] = signature
response = requests.post(self.API_HOST + '/api/market/wallet',
headers=self.API_HEADER, data=self.__json_encode(data))
obj = json.loads(response.text)
return(obj)
def get_balance_assets(self):
data = {
'ts': self.timeserver(),
}
signature = self.sign(data)
data['sig'] = signature
response = requests.post(self.API_HOST + '/api/market/balances',
headers=self.API_HEADER, data=self.__json_encode(data))
obj = json.loads(response.text)
# print(obj)
data = [{
'available': float(obj['result'][self.API_CURRENCY]['available']),
'reserved': obj['result'][self.API_CURRENCY]['reserved'],
'symbol': self.API_CURRENCY
}]
msg = ""
if obj['error'] == 0:
currency = obj['result']
for i in currency:
if currency[i]['reserved'] > 0 or currency[i]['available'] > 0 :
currency[i]['symbol'] = i
data.append(currency[i])
msg += f"""
Symbol: {currency[i]['symbol']}
Available: {obj['result'][currency[i]['symbol']]['available']}
Reserved: {obj['result'][currency[i]['symbol']]['reserved']}
"""
# print(msg)
return(data,obj)
def get_balance_assets_dict(self):
data = {
'ts': self.timeserver(),
}
signature = self.sign(data)
data['sig'] = signature
response = requests.post(self.API_HOST + '/api/market/balances',
headers=self.API_HEADER, data=self.__json_encode(data))
obj = json.loads(response.text)
print(obj)
data = [{
'available': float(obj['result'][self.API_CURRENCY]['available']),
'reserved': obj['result'][self.API_CURRENCY]['reserved'],
'symbol': self.API_CURRENCY
}]
msg = ""
if obj['error'] == 0:
currency = obj['result']
for i in currency:
if currency[i]['reserved'] > 0 or currency[i]['available'] > 0 :
currency[i]['symbol'] = i
data.append(currency[i])
msg += f"""
Symbol: {currency[i]['symbol']}
Available: {obj['result'][currency[i]['symbol']]['available']}
Reserved: {obj['result'][currency[i]['symbol']]['reserved']}
"""
# print(msg)
return(obj,data)
def get_order_history(self,p_sym,_lmt=50,_start=1600756416,_end=9610756416):
self.getServerTime()
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'ts': self.getServerTime(),
'sym':p_sym,
'lmt':_lmt,
'start':_start,
'end':_end
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + json_encode(data))
response = requests.post(self.API_HOST + self.ENDPOINTS['MARKET_MY_ORDER_HISTORY'], headers=header, data=self.json_encode(data))
data = response.json()
data = data['result']
# print(response.json())
return(data)
def get_assets(self):
response = requests.get(
self.API_HOST + "/api/market/symbols", headers={}, data={})
obj = json.loads(response.text)
if obj['error'] == 0:
i = 0
while i < len(obj['result']):
symbol = str(obj['result'][i]['symbol'])
obj['result'][i]["global"] = symbol
obj['result'][i]['symbol'] = symbol[4:]
obj['result'][i]["currency"] = self.API_CURRENCY
i += 1
return obj['result']
return obj['error']
def get_last_price(self, symbol):
try:
rticker = requests.get(
f'{self.API_HOST}/api/market/ticker?sym={symbol}')
rticker = rticker.json()
price = rticker[symbol]
return price
except Exception as e:
print(f"Error: {e}")
return False
def zero_div(x, y):
try:
return x / y
except ZeroDivisionError:
return 0
def Average(self,l):
avg = sum(l) / len(l)
return avg
def getLastBuyAverage(self,symbol):
listOfBuys = []
order= {}
_pair = 'THB_'+symbol
order[symbol] = self.get_order_history(_pair)
for ordBuy in order[symbol]:
if(ordBuy['side']=='buy'):
print(f"""Side : {ordBuy['side']} ราคา : {ordBuy['rate']} จำนวน : {ordBuy['amount']}""" )
listOfBuys.append(round(float(ordBuy['rate']),10))
else:
print(f"""Side : {ordBuy['side']} ราคา : {ordBuy['rate']} จำนวน : {ordBuy['amount']}""" )
break
# average = self.Average(listOfBuys)
average = mean(listOfBuys)
print('getLastBuyAverage : ' , symbol , ':',average)
return average
def getLastBuyAverageNew(self,symbol):
a = self.get_order_history('THB_'+symbol,200,1653436800,round(time.time()))
df = pd.DataFrame(
a, columns=['side', 'type', 'rate', 'fee', 'credit', 'amount','ts']
)
df['ts'] = pd.to_datetime(df['ts'], unit='s')
df = df.rename({'ts': 'datetime'}, axis=1)
df = df.sort_values(by="datetime")
df['Ticker'] = 'NEAR'
df['amount'] =pd.to_numeric(df['amount'], downcast='float')
df['rate'] = pd.to_numeric(df['rate'], downcast='float')
df['THB_InStock']=df['amount'] * df['rate']
df['TotalQty'] = df['amount'].where(df['side'].eq('buy'), -df['amount']).cumsum()
df['Averaged'] = df.apply(lambda x: ((x.side == "buy") - (x.side == "sell")) * x['THB_InStock'], axis = 1)
df['TotalQty'] = df['TotalQty'].apply(lambda x: float('%.10f' % x))
df['Averaged'] = df.groupby('Ticker')['Averaged'].cumsum().div(df['TotalQty'])
res = df.loc[df.index[-1], "Averaged"]
return res
def costBasisAveragePrice(self,symbol,timestamp=1653436800,limit=555):
try:
a = self.get_order_history('THB_'+symbol,limit,timestamp,round(time.time()))
df = pd.DataFrame(
a, columns=['side', 'type', 'rate', 'fee', 'credit', 'amount','ts']
)
df['ts'] = pd.to_datetime(df['ts'], unit='s')
df = df.rename({'ts': 'datetime'}, axis=1)
df = df.sort_values(by="datetime")
df['Ticker'] = symbol
df['amount'] =pd.to_numeric(df['amount'], downcast='float')
df['rate'] = pd.to_numeric(df['rate'], downcast='float')
df['fee'] = pd.to_numeric(df['fee'], downcast='float')
df['credit'] = pd.to_numeric(df['credit'], downcast='float')
df['THB_InStock']=df['amount'] * df['rate']
df['TotalQty'] = df['amount'].where(df['side'].eq('buy'), -df['amount']).cumsum()
df['TotalQty'] = df['TotalQty'].apply(lambda x: float('%.10f' % x))
df1 = (df.copy()[df['side'] == 'buy']
.assign(CumAmountBuy=df.groupby('Ticker')['THB_InStock'].cumsum())
.assign(CumQtyBuy=df.groupby('Ticker')['amount'].cumsum()))
df2 = pd.merge(df,df1,how='left',
on=['datetime','side', 'Ticker', 'amount', 'rate',
'THB_InStock', 'TotalQty']).ffill()
s = df2['CumAmountBuy'] / df2['CumQtyBuy']
df2['AverageCost'] = np.select([((df2['side'] == 'buy') & (df2['side'].shift() == 'sell')),
(df2['side'] == 'sell')],
[((df2['amount'] * df2['rate'] + df2['TotalQty'].shift() * s.shift()) / df2['TotalQty']),
np.nan],
s)
df2['AverageCost'] = round(df2['AverageCost'],3).ffill()
df2 = df2.drop(['CumQtyBuy', 'CumAmountBuy'], axis=1)
return df2.loc[df2.index[-1], "AverageCost"]
except IndexError:
return math.nan
def costBasisAveragePriceWithDF(self,symbol,timestamp=1653436800,limit=555):
try:
a = self.get_order_history('THB_'+symbol,limit,timestamp,round(time.time()))
df = pd.DataFrame(
a, columns=['side', 'type', 'rate', 'fee', 'credit', 'amount','ts']
)
df['ts'] = pd.to_datetime(df['ts'], unit='s')
df = df.rename({'ts': 'datetime'}, axis=1)
df = df.sort_values(by="datetime")
df['Ticker'] = symbol
df['amount'] =pd.to_numeric(df['amount'], downcast='float')
df['rate'] = pd.to_numeric(df['rate'], downcast='float')
df['fee'] = pd.to_numeric(df['fee'], downcast='float')
df['credit'] = pd.to_numeric(df['credit'], downcast='float')
df['THB_InStock']=df['amount'] * df['rate']
df['TotalQty'] = df['amount'].where(df['side'].eq('buy'), -df['amount']).cumsum()
df['TotalQty'] = df['TotalQty'].apply(lambda x: float('%.10f' % x))
df1 = (df.copy()[df['side'] == 'buy']
.assign(CumAmountBuy=df.groupby('Ticker')['THB_InStock'].cumsum())
.assign(CumQtyBuy=df.groupby('Ticker')['amount'].cumsum()))
df2 = pd.merge(df,df1,how='left',
on=['datetime','side', 'Ticker', 'amount', 'rate',
'THB_InStock', 'TotalQty']).ffill()
s = df2['CumAmountBuy'] / df2['CumQtyBuy']
df2['AverageCost'] = np.select([((df2['side'] == 'buy') & (df2['side'].shift() == 'sell')),
(df2['side'] == 'sell')],
[((df2['amount'] * df2['rate'] + df2['TotalQty'].shift() * s.shift()) / df2['TotalQty']),
np.nan],
s)
df2['AverageCost'] = round(df2['AverageCost'],3).ffill()
df2 = df2.drop(['CumQtyBuy', 'CumAmountBuy'], axis=1)
return df2.loc[df2.index[-1], "AverageCost"] , df
except IndexError:
return math.nan
def getMyMoney(self):
result = 0
bal,aData = self.get_balance_assets()
THB = 0
THBinCOIN = 0
THBReserve = 0
for ba in bal:
if(ba['symbol']=='THB' or ba['symbol']=='DON' or ba['symbol']=='LUNA2'):
if(ba['symbol']=='THB'):
THB = ba['available']
THBReserve = ba['reserved']
else:
symbol = ba['symbol']
# amt = ba['available']
_pair = 'THB_'+symbol
available = ba['available']
reserved = ba['reserved']
try:
currentPrice = self.get_last_price(_pair)
except :
currentPrice = 0
try:
# balance_value = amt *currentPrice['last']
# result + balance_value
myMoney = (reserved + available) * currentPrice['last']
THBinCOIN += myMoney
except TypeError:
myMoney = (reserved + available) * currentPrice['last']
THBinCOIN += myMoney
result = (THB+THBinCOIN+THBReserve)
return result
def checkBalanceAndEmergencySell(self , StopLoss = 8000 , dictExclude = {},_token = ''):
bal,aData = self.get_balance_assets()
allMoney = self.getMyMoney()
result = False
if(float(allMoney)<=float(StopLoss)):
for ba in bal:
if(ba['symbol']=='THB' or ba['symbol']=='DON' or ba['symbol']=='LUNA2'):
if(ba['symbol']=='THB'):
pass
else:
symbol = ba['symbol']
amt = ba['available']
_pair = 'THB_'+symbol
if(symbol in dictExclude):
continue
else:
self.sendLine('เริ่มขายราคาตลาด แบบฉุกเฉิน BTC กำลังจะตาย !!!!!',_token)
print('checkBalanceAndEmergencySell market : ', _pair, ' ',amt,' ', 0,' ', _token ,'\n')
self.sellMarket(_pair, amt, 0, _token ,'')
result = True
print('CheckBalanceAndEmergencySell : STOPLOSS at :',StopLoss , ' Now All Money : ' ,allMoney ,' Result :' , result )
return result
def emergencySell(self,_dictExclude,_token):
bal,aData = self.get_balance_assets()
self.sendLine('เริ่มขายราคาตลาด แบบฉุกเฉิน',_token)
for ba in bal:
if(ba['symbol']=='THB' or ba['symbol']=='DON'):
if(ba['symbol']=='THB'):
pass
else:
symbol = ba['symbol']
amt = ba['available']
_pair = 'THB_'+symbol
if(symbol in _dictExclude):
continue
else:
self.sellMarket(_pair, amt, 0, _token ,'')
def buy(self,_pair,_amt,_rat,_token,_txtOptional=''):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'sym': _pair,
'amt': _amt, # THB amount you want to spend
'rat': _rat,
'typ': 'limit',
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + self.json_encode(data))
response = requests.post(self.API_HOST + '/api/market/place-bid', headers=header, data=self.json_encode(data))
res = response.json()
if(res['error']==0):
self.sendLine('ซื้อ Order :{} \n ที่ราคา : {:,.3f} \n จ่ายไป : {}฿ \n ได้มา : {} \n โดนค่า Fee {:,.3f}฿ \n ใช้ Credit Fee {}฿ {}'.format(_pair,_rat,_amt,res['result']['rec'],res['result']['fee'],res['result']['cre'],_txtOptional),token=_token)
else:
self.sendLine('ซื้อ Error :{} ที่ราคา : {:,.3f} จำนวน : {} ผลลัพธ์ {} {}'.format(_pair,_rat,_amt,self.errorCode[res['error']],_txtOptional),token=_token)
obj = json.loads(response.text)
return obj
async def buyAsync(self,_pair,_amt,_rat,_token,_txtOptional=''):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'sym': _pair,
'amt': _amt, # THB amount you want to spend
'rat': _rat,
'typ': 'limit',
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
res = True
# print('Payload with signature: ' + self.json_encode(data))
response = requests.post(self.API_HOST + '/api/market/place-bid', headers=header, data=self.json_encode(data))
res = response.json()
if(res['error']==0):
self.sendLine('ซื้อ Order :{} \n ที่ราคา : {:,.3f} \n จ่ายไป : {}฿ \n ได้มา : {} \n โดนค่า Fee {:,.3f}฿ \n ใช้ Credit Fee {}฿ {}'.format(_pair,_rat,_amt,res['result']['rec'],res['result']['fee'],res['result']['cre'],_txtOptional),token=_token)
else:
self.sendLine('ซื้อ Error :{} ที่ราคา : {:,.3f} จำนวน : {} ผลลัพธ์ {} {}'.format(_pair,_rat,_amt,self.errorCode[res['error']],_txtOptional),token=_token)
res = False
obj = json.loads(response.text)
return obj , res
def buyMarket(self,_pair,_amt,_rat,_token,_txtOptional=''):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'sym': _pair,
'amt': _amt, # THB amount you want to spend
'rat': 0,
'typ': 'market',
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + self.json_encode(data))
response = requests.post(self.API_HOST + '/api/market/place-bid', headers=header, data=self.json_encode(data))
res = response.json()
if(res['error']==0):
self.sendLine('ซื้อ Order :{} \n ที่ราคา : {:,.3f} \n จ่ายไป : {}฿ \n ได้มา : {} \n โดนค่า Fee {:,.3f}฿ \n ใช้ Credit Fee {}฿ {}'.format(_pair,_rat,_amt,res['result']['rec'],res['result']['fee'],res['result']['cre'],_txtOptional),token=_token)
else:
self.sendLine('ซื้อ Error :{} ที่ราคา : {:,.3f} จำนวน : {} ผลลัพธ์ {} {}'.format(_pair,_rat,_amt,self.errorCode[res['error']],_txtOptional),token=_token)
obj = json.loads(response.text)
return obj
def sell(self,_pair,_amt,_rat,_token ,_txtOptional=''):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'sym': _pair,
'amt': _amt, # amount you want to spend
'rat': _rat,
'typ': 'limit',
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + self.json_encode(data))
response = requests.post(self.API_HOST + '/api/market/place-ask', headers=header, data=self.json_encode(data))
res = response.json()
#data = data['result']
if(res['error']==0):
self.sendLine('ขาย Order :{} \n ที่ราคา : {:,.3f} \n จำนวน : {} \n ได้เงิน : {} \n โดนค่า Fee {:,.3f}฿ \n ใช้ Credit Fee {}฿ {}'.format(_pair,_rat,_amt,res['result']['rec'],res['result']['fee'],res['result']['cre'],_txtOptional),token=_token)
else:
self.sendLine('ขาย Error :{} ที่ราคา : {:,.3f} จำนวน : {} ผลลัพธ์ {} {}'.format(_pair,_rat,_amt,self.errorCode[res['error']],_txtOptional),token=_token)
obj = json.loads(response.text)
return obj
async def sellAsync(self,_pair,_amt,_rat,_token ,_txtOptional=''):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'sym': _pair,
'amt': _amt, # amount you want to spend
'rat': _rat,
'typ': 'limit',
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + self.json_encode(data))
response = requests.post(self.API_HOST + '/api/market/place-ask', headers=header, data=self.json_encode(data))
res = response.json()
#data = data['result']
if(res['error']==0):
self.sendLine('ขาย Order :{} \n ที่ราคา : {:,.3f} \n จำนวน : {} \n ได้เงิน : {} \n โดนค่า Fee {:,.3f}฿ \n ใช้ Credit Fee {}฿ {}'.format(_pair,_rat,_amt,res['result']['rec'],res['result']['fee'],res['result']['cre'],_txtOptional),token=_token)
else:
self.sendLine('ขาย Error :{} ที่ราคา : {:,.3f} จำนวน : {} ผลลัพธ์ {} {}'.format(_pair,_rat,_amt,self.errorCode[res['error']],_txtOptional),token=_token)
obj = json.loads(response.text)
return obj
def getBankAccount(self):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'ts': self.getServerTime()
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + self.json_encode(data))
response = requests.post(self.API_HOST + '/api/fiat/accounts', headers=header, data=self.json_encode(data))
res = response.json()
#data = data['result']
return res
def withdrawFiat(self,_bankAccount,_Amount,_token):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'id': _bankAccount,
'amt': _Amount ,# amount
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
response = requests.post(self.API_HOST + '/api/fiat/withdraw', headers=header, data=self.json_encode(data))
res = response.json()
#data = data['result']
if(res['error']==0):
self.sendLine('ถอนเงินไปที่ : ' + str(_bankAccount) + ' จำนวน : ' +str(_Amount),token=_token)
else:
self.sendLine('ถอนเงิน Error : {} '.format(self.errorCode[res['error']]),token=_token)
print('fiat Withdrawal : ' + str(res))
return res
def sellMarket(self,_pair,_amt,_rat,_token ,_txtOptional=''):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'sym': _pair,
'amt': _amt, # amount you want to spend
'rat': 0,
'typ': 'market',
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + self.json_encode(data))
response = requests.post(self.API_HOST + '/api/market/place-ask', headers=header, data=self.json_encode(data))
res = response.json()
#data = data['result']
if(res['error']==0):
self.sendLine('ขายราคาตลาดสด :{} \n ที่ราคา : {:,.3f} \n จำนวน : {} \n ได้เงิน : {} \n โดนค่า Fee {:,.3f}฿ \n ใช้ Credit Fee {}฿ {}'.format(_pair,_rat,_amt,res['result']['rec'],res['result']['fee'],res['result']['cre'],_txtOptional),token=_token)
else:
self.sendLine('ขายราคาตลาดสด Error :{} ที่ราคา : {:,.3f} จำนวน : {} ผลลัพธ์ {} {}'.format(_pair,_rat,_amt,self.errorCode[res['error']],_txtOptional),token=_token)
return response
def CheckCondition(self,sc,coin,price):
# coin= 'THB_BTC', price = 1050000
text = ''
check_buy = self.condition[coin]['buy']
if price <= check_buy:
txt = '{} ราคาลงแล้ว เหลือ: {:,.3f} รีบซื้อด่วน!\n(ราคาที่อยากได้: {:,.3f})'.format(coin,price,check_buy)
#print(txt)
text += txt + '\n'
self.sendLine(text)
check_sell = self.condition[coin]['sell']
if price >= check_sell:
txt = '{} ราคาขึ้นแล้ว ล่าสุดเป็น: {:,.3f} รีบขายด่วน!\n(ราคาที่อยากขาย: {:,.3f})'.format(coin,price,check_sell)
#print(txt)
text += txt + '\n'
self.sendLine(text)
# print('CheckCondition',coin,price)
# s.enter(10, 1, CheckCondition, kwargs={'sc':s,'coin': coin,'price': price})
return text
def checkBalance(self):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + json_encode(data))
response = requests.post(self.API_HOST + '/api/market/balances', headers=header, data=self.json_encode(data))
data = response.json()
data = data['result']
# print(response.json())
return(data)
def getSymOpenOrder(self,_sym ):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'ts': self.getServerTime(),
'sym':_sym,
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + json_encode(data))
response = requests.post(self.API_HOST + '/api/market/my-open-orders', headers=header, data=self.json_encode(data))
data = response.json()
# data = data['result']
# print(response.json())
return(data)
def cancelOpenOrder(self,_sym,_id ,_sd ,_hash,_rate,_amount, _token ):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'ts': self.getServerTime(),
'sym':_sym,
'id':_id,
'sd':_sd,
'hash':_hash,
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + json_encode(data))
response = requests.post(self.API_HOST + '/api/market/cancel-order', headers=header, data=self.json_encode(data))
data = response.json()
# print('order Cancel',data)
# data = data['result']
# print(response.json())
if(data['error']==0):
self.sendLine('Cancel Order SYM:{} \n SIDE:{} \n RATE:{} \n AMOUNT:{}'.format(_sym,_sd,_rate,_amount),token=_token)
else:
self.sendLine('Cancel Order Error {} , {} , {} '.format(_sym,_id,_sd,self.errorCode[data['error']]),token=_token)
return(data)
def sendLine(self,_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(self):
response = requests.get(self.API_HOST + '/api/market/ticker')
result = response.json()
return result
def calc(self):
allText = ''
for c in self.MyWatcher:
sym = c
pairedSym = 'THB_'+sym
rebalText = self.rebalance(pairedSym , sym , self.rebalanceTarget[pairedSym] , False ,self.gap)
result = self.getAllPrice()
dataBalance = self.checkBalance()
THB = dataBalance['THB']['available']
THBReserve = dataBalance['THB']['reserved']
THBinCOIN = 0
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],True)
text = ' {} : {}\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) - self.fund
else:
x = (THBReserve +(THB + THBinCOIN)) - self.fund
xText = '{:,.2f}฿'.format(x)
sendBalanceText =' ทุน : {}฿ \n {} : {}฿ \n เงินในเหรียญ : {:,.2f}฿ \n เงินใน Order : {:,.2f}฿ \n กำไรขาดทุน {:,.2f}฿ \n '.format(str(self.fund),str('เงินสด'),str(THB),THBinCOIN,THBReserve,x)
self.sendLine( '```'+allText+'```' + '\n ' + '```' + sendBalanceText + '```',token=_token)
# sc.enter(60, 1, calc, (sc,))
def balances(self):
header = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-BTK-APIKEY': self.API_KEY,
}
data = {
'ts': self.getServerTime(),
}
signature = self.sign(data)
data['sig'] = signature
# print('Payload with signature: ' + json_encode(data))
response = requests.post(self.API_HOST + '/api/market/balances', headers=header, data=self.json_encode(data))
data = response.json()
#data = data['result']
# print(response.json())
return(data)
def ticker(self,_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(self.API_HOST + '/api/market/ticker?sym='+_sym)
data = response.json()
#data = data['result']
# print(response.json())
return(data)
def rebalance(self,_pair , _token_name , _target , _OrderActivate , _gap):
returnText = ''
pair = _pair#'THB_KUB' #เหรียญ
token_name =_token_name #'KUB' #เหรียญ
balance_coin=self.balances()
balance_coin=balance_coin['result'][token_name]['available'] + balance_coin['result'][token_name]['reserved']
#print('จำนวนเหรียญในบัญชี' , balance_coin , 'เหรียญ')
balance_thb=self.balances()
balance_thb=balance_thb['result']['THB']['available'] + balance_thb['result']['THB']['reserved']
#print('จำนวนเงินในบัญชี' , balance_thb , 'บาท')
last_price = self.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 > 10: #มูลค่าเพิ่มมากกว่าเท่าไหร่ถึงจะแจ้งเตือน
# 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:
self.sell(_pair,amountToSell,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
# print(amount)
if amount > 10: #มูลค่าลดมากกว่าเท่าไหร่ถึงจะแจ้งเตือน
# print('ซื้อเข้า' , amount , 'บาท')
# sendLine('{} Buy {:,.2f} baht @ {:,.2f} '.format(_pair,amount,last_price))
if _OrderActivate == True:
self.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 trand_ema(self, symbol, df, fast_length=9, slow_length=26, export_limit=7, export_full=False):
SIGNAL = None
TREND = None
EMA_FAST_A = 0
EMA_FAST_B = 0
EMA_SLOW_A = 0
EMA_SLOW_B = 0
AVG_MIN = 0
if len(df) >= 3:
if len(df) < slow_length:
df_length = (len(df) - 1)
EMA_FAST_A = df['close'][df_length]
EMA_FAST_B = df['close'][df_length - 2]
EMA_SLOW_A = df['close'][df_length]
EMA_SLOW_B = df['close'][df_length - 2]
df_ohlcv = df
else:
# print(f"trend up {fast_length} {slow_length}")
# เรียกโมดูล EMS
EMA_FAST = df.ta.ema(fast_length)
EMA_SLOW = df.ta.ema(slow_length)
## เพิ่มคอลั่ม EMA
data = pd.concat([df, EMA_FAST], axis=1)
df_ohlcv = pd.concat([data, EMA_SLOW], axis=1)
df_length = (len(df_ohlcv) - 1)
EMA_FAST_A = df_ohlcv['EMA_' + str(fast_length)][df_length]
EMA_FAST_B = df_ohlcv['EMA_' + str(fast_length)][df_length - 2]