-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathStartBot.py
More file actions
1212 lines (1092 loc) · 69.9 KB
/
StartBot.py
File metadata and controls
1212 lines (1092 loc) · 69.9 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 -*-
# import websocket
import json
import pandas as pd
import pickle
import talib
from datetime import datetime
import numpy
import os
import asyncio
import aiofiles
# import websockets
import pprint
import websocket as wb
from apibutkib import BugKib
from pymongo import MongoClient
import datetime
import sys
from termcolor import colored
import numpy as np
from uuid import uuid4
import math
SOCKET = 'wss://api.bitkub.com/websocket-api/'
#Parameters of the RSI Strategy
pair = {
'KUB':'market.trade.thb_kub'
}
RSI_PERIOD = 14
RSI_OVERBOUGHT =70
RSI_OVERSOLD = 30
#Symbol of Ethereum
TRADE_SYMBOL = "ETHUSD"
#Quantity of ETH for a trade
TRADE_QUANTITY = 1
in_position = False
df = pd.DataFrame()
API_KEY = 'xxx'
API_SECRET = 'xxx'
HISTORY_PATH = os.path.join(os.getcwd(), "data_history")
WSS_URL = "wss://api.bitkub.com/websocket-api/"
DATA_STR = ""
Stop_Loss_at_Money = 4000
coinList = {'ZIL'}
excludeProfit = {'LUNA','IOST','ADA'}
excludeEmergency = {'LUNA','LUNA2','XLM','ZIL'}
# FTM SOL DOGE ZIL KUB BNB
# tradeLists = {'GT','GRT','MANA','ALPHA','SOL','GALA','SUSHI','NEAR','APE','ETH','JFIN','FTM','GF','MKR','BAND','GLM','SAND'}
bitkubFee = 0.0025
APIKEYBITKUB='APIKEY_BITKUB'
bitkub = BugKib(_apiKey=APIKEYBITKUB,_apisecret = b'APISECRET_BITKUB')
client = MongoClient('mongodbAddress',27017)
db = client.bitkub
trend_db = db.trends
subscribe_db = db.subscribe
stochrsi_db = db.stochrsis
macd_db = db.macds
profitDb = db.profits
botStopLossDb = db.botStopLoss
buyDb = db.buys
sellDb = db.sells
assetDb = db.assets
joblogDb = db.joblogs
cancleDb = db.cancleLogs
botActivateDb = db.botactivate
lineOrderToken = 'LINENOTIFYTOKEN'
# lineSignalToken = 'LINENOTIFYTOKEN'
lineSignalToken = 'LINENOTIFYTOKEN'
buyBtcRSI = 20
tradeLists = {'NEAR','KUB','ADA','DOGE'}
tradeOption = {
'DEFAULT':{'Buy':50,'Sell':295,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'GT':{'Buy':50,'Sell':295,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'KUB':{'Buy':200,'Sell':295,'MaxAmt':600,'firstInitial':200,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'ADA':{'Buy':200,'Sell':295,'MaxAmt':600,'firstInitial':200,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'CHZ':{'Buy':250,'Sell':295,'MaxAmt':500,'firstInitial':250,'timeframe':'5','profitTotake':15,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'GRT':{'Buy':250,'Sell':295,'MaxAmt':500,'firstInitial':250,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'MANA':{'Buy':50,'Sell':295,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':5,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'BNB':{'Buy':50,'Sell':594,'MaxAmt':150,'firstInitial':100,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'ALPHA':{'Buy':50,'Sell':295,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'SOL':{'Buy':50,'Sell':195,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'GALA':{'Buy':50,'Sell':195,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'SUSHI':{'Buy':50,'Sell':195,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'BTC':{'Buy':50,'Sell':495,'MaxAmt':150,'firstInitial':200,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'NEAR':{'Buy':500,'Sell':495,'MaxAmt':1000,'firstInitial':500,'timeframe':'5','profitTotake':20,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-50},
'APE':{'Buy':50,'Sell':495,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'ETH':{'Buy':50,'Sell':495,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'JFIN':{'Buy':50,'Sell':495,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'FTM':{'Buy':50,'Sell':495,'MaxAmt':150,'firstInitial':50,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
'DOGE':{'Buy':200,'Sell':495,'MaxAmt':2200,'firstInitial':200,'timeframe':'5','profitTotake':10,'tradeStyle':'stepProfit','stopLossWhenLossInTHB':-15},
}
tradeStyleStep = { # SYMBOL : {'RSI':'PERCENT TO SELL'}
'DEFAULT':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
'BTC':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
'BNB':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
'GT':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
'MANA':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
'ALPHA':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
'SOL':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
'GALA':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
'SUSHI':{
'Range':{'Min':30,'Max':40,'PercentToSell':20},
'Range2':{'Min':40,'Max':50,'PercentToSell':30},
'Range3':{'Min':50,'Max':60,'PercentToSell':40},
'Range4':{'Min':60,'Max':70,'PercentToSell':50},
'Range5':{'Min':70,'Max':80,'PercentToSell':60},
'Range6':{'Min':80,'Max':90,'PercentToSell':80},
'Range7':{'Min':90,'Max':100,'PercentToSell':99}
},
}
# 'LUNA':{'Buy':200,'Sell':195,'MaxAmt':200,'firstInitial':194814},
# bitkub = BugKib(_apiKey='APIKEY_BITKUB' ,_apisecret = b'APISECRET_BITKUB')
def prepare_data_dir():
print(f"checking history path ({HISTORY_PATH})")
if not os.path.exists(HISTORY_PATH):
os.mkdir(HISTORY_PATH)
# print(f"history path is created")
return
# print(f"history path already exists")
def create_wss_url():
global WSS_URL
# symbols = [s for s in list(os.environ.get("CAPTURE_COIN", "").split(","))]
stream_name = ",".join(
[f"market.ticker.thb_{s.lower()}" for s in coinList])
# print(stream_name)
WSS_URL = f"{WSS_URL}{stream_name}"
# print(WSS_URL)
#################################################### MAIN ####################################################
if __name__ == "__main__":
# prepare_data_dir()
# create_wss_url()
tb_name = datetime.datetime.now().strftime('%Y%m%d')
assets = bitkub.get_assets()
bal,aData = bitkub.get_balance_assets()
cash =0
orig_stdout = sys.stdout
log_path = 'E:\\LogBot\\'
if not os.path.exists(log_path):
os.makedirs(log_path)
f = open(log_path+'BotLogOut'+str(APIKEYBITKUB)+'_'+str(tb_name)+'.txt', 'a')
sys.stdout = f
print('Starting Bot Task :', datetime.datetime.now())
try:
botActivate = { "Instance": APIKEYBITKUB }
botActivateDoc = botActivateDb.find_one(botActivate)
Stop_Loss_at_Money = botActivateDoc['Stop_Loss_at_Money']
tradeOptions_mongo = botActivateDoc['tradeOptions']
tradeStyleSteps_mongo = botActivateDoc['tradeStyleSteps']
tradeLists_mongo = botActivateDoc['tradeLists']
lineOrderToken = botActivateDoc['lineOrderToken']
lineSignalToken = botActivateDoc['lineSignalToken']
buyBtcRSI = botActivateDoc['buyBtcRSI']
# stopLossWhenLossInTHB = botActivateDoc['stopLossWhenLossInTHB']
if(botActivateDoc['Activate']==False):
logSave = {
"CASH": bitkub.getMyMoney(),
"Asset": "BOT IS DEACTIVATE",
"Signal": "BOT IS DEACTIVATE",
"StochRSI": "BOT IS DEACTIVATE",
"AssetInTHB":"BOT IS DEACTIVATE",
"AvgBuyPrice":"BOT IS DEACTIVATE",
"CurrentPrice":"BOT IS DEACTIVATE",
"Available":"BOT IS DEACTIVATE",
"Reserved":"BOT IS DEACTIVATE",
"Profit":"BOT IS DEACTIVATE",
"ProfitGoal":"BOT IS DEACTIVATE",
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
joblogDb[APIKEYBITKUB].insert_one(logSave)
botActivateDb.update_one({'Instance': APIKEYBITKUB},
{'$set': {'Activate': False}
}
,upsert=True
)
bitkub.sendLine('Stop Loss บอทไม่ทำงาน เพราะตั้ง Stop Loss ไว้ที่ : ' + str(Stop_Loss_at_Money) + ' \n เงินคุณมี : '+ str(bitkub.getMyMoney()),token=lineOrderToken)
sys.exit("BOT IS DEACTIVATE")
except KeyError as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
bitkub.sendLine('Exception KeyError : ' + str(exc_type) + ' \n '+ str(fname) + '\n' + str(exc_tb.tb_lineno),token=lineOrderToken)
botActivateDb.update_one(
{'Instance': APIKEYBITKUB},
{
'$set': {
'tradeOptions': tradeOption,
'tradeStyleSteps':tradeStyleStep,
'tradeLists':list(tradeLists),
'lineOrderToken' : lineOrderToken,
'lineSignalToken' : lineSignalToken,
'buyBtcRSI' : float(buyBtcRSI)
}
},upsert=True
)
botActivate = { "Instance": APIKEYBITKUB }
botActivateDoc = botActivateDb.find_one(botActivate)
tradeOptions_mongo = botActivateDoc['tradeOptions']
tradeStyleSteps_mongo = botActivateDoc['tradeStyleSteps']
tradeLists_mongo = botActivateDoc['tradeLists']
lineOrderToken = botActivateDoc['lineOrderToken']
lineSignalToken = botActivateDoc['lineSignalToken']
buyBtcRSI = botActivateDoc['buyBtcRSI']
# stopLossWhenLossInTHB = botActivateDoc['stopLossWhenLossInTHB']
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
bitkub.sendLine('Exception : ' + str(exc_type) + ' \n '+ str(fname) + '\n' + str(exc_tb.tb_lineno),token=lineOrderToken)
pass
StopLossMai = bitkub.checkBalanceAndEmergencySell(StopLoss = Stop_Loss_at_Money , dictExclude = excludeEmergency , _token = lineOrderToken)
# for signal in [bitkub.STOCHRSIsignal, bitkub.MACDsignal]:
# for stock in [x for x in df.columns if 'stock' in x]:
# df['Close'] = df[stock]
# indicator = signal(df)
# for sig in indicator.keys():
# table.loc[sig, stock] = str(indicator[sig])[:4]
if(StopLossMai == True):
print('In Remaining on Stop Loss No Running Bot')
bitkub.sendLine('Stop Loss No Bot DeActivaed',token=lineOrderToken)
logSave = {
"CASH": bitkub.getMyMoney(),
"Asset": "StopLoss",
"Signal": "StopLoss",
"StochRSI": "StopLoss",
"AssetInTHB":"StopLoss",
"AvgBuyPrice":"StopLoss",
"CurrentPrice":"StopLoss",
"Available":"StopLoss",
"Reserved":"StopLoss",
"Profit":"StopLoss",
"ProfitGoal":"StopLoss",
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
joblogDb[APIKEYBITKUB].insert_one(logSave)
botActivateDb.update_one({'Instance': APIKEYBITKUB},
{'$set': {'Activate': False}
}
,upsert=True
)
else:
ablaaa = {}
aOpenOrder= {}
aOrderHistory = {}
aDataFrame = {}
aUrl={}
alastBuyPrices = {}
##################################### ซื้อติดเป๋า
aData = aData['result']
print('***************** BEGIN *******************')
for trd in tradeLists_mongo:
aAvailable = aData[trd]['available']
aReserved = aData[trd]['reserved']
valueNow = aAvailable + aReserved
if(valueNow == 0):
_pair = 'THB_'+trd
_rat = bitkub.get_last_price(_pair)
aOpenOrder[trd] = bitkub.getSymOpenOrder(_pair)
aOpenOrderResult = aOpenOrder[trd]['result']
if(len(aOpenOrderResult)>=1):
for resultOrder in aOpenOrderResult:
_sym=trd
_id=resultOrder['id']
_sd =resultOrder['side']
_hash=resultOrder['hash']
_rate=resultOrder['rate']
_amount=resultOrder['amount']
if(_sd == 'BUY'):
bitkub.cancelOpenOrder(_sym, _id, _sd,_hash,_rate,_amount,lineOrderToken)
cancleDbDataSave = {
"hash": _hash,
"key": str(uuid4()),
"Asset": _sym,
"idOrder": _id,
"Side":_sd,
"Rate":_rate,
"Amount":_amount,
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
cancleDb[APIKEYBITKUB].insert_one(cancleDbDataSave)
print('เงินพอซื้อ Init Market buy: ', trd)
try:
aAmt = tradeOptions_mongo[trd]
except KeyError:
aAmt = tradeOptions_mongo['DEFAULT']
_firstInitial = aAmt['firstInitial']
buyResponse = bitkub.buyMarket(_pair, _firstInitial, 0,lineOrderToken)
try:
buyResponse = buyResponse['result']
buyDataSave = {
"hash": str(buyResponse['hash']),
"key": str(uuid4()),
"Asset": trd,
"Signal": "NO INIT COIN",
"AssetInTHB":"NO INIT COIN",
"PreviousAvgBuyPrice":"NO INIT COIN",
"BuyPrice":_rat['last'],
"Available":"NO INIT COIN",
"Reserved":"NO INIT COIN",
"AmountToBuy":buyResponse['amt'],
"Type":buyResponse['typ'],
"Fee":buyResponse['fee'],
"CreditFee":buyResponse['cre'],
"AmountToReceive":buyResponse['rec'],
"timestamp":buyResponse['ts'],
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
buyDb[APIKEYBITKUB].insert_one(buyDataSave)
except KeyError:
err = bitkub.errorCode[buyResponse['error']]
bitkub.sendLine('ซื้อ FirstInitial ไม่ได้ Error : ' + str(err),token=lineOrderToken)
##################################### ซื้อติดเป๋า
# print(table)
# for ba in bal:
for ba in bal:
if(ba['symbol']=='THB' or ba['symbol']=='DON' or ba['symbol']=='LUNA2' or ba['symbol']=='TRX' ):
if(ba['symbol']=='THB'):
cash = ba['available']
pass
else:
# lastBuyPrices = {}
symbol = ba['symbol']
_pair = 'THB_'+symbol
_rat = bitkub.get_last_price(_pair)
_ratBTC = bitkub.get_last_price('THB_BTC')
aOrderHistory[_pair] = bitkub.get_order_history(_pair)
# lastBuyPrice = 0
# for abc in aOrderHistory[_pair]:
# if(abc['side']=='buy'):
# lastBuyPrice=float(abc['rate'])
# break
# lastBuyPrice = bitkub.getLastBuyAverage(symbol) #OLD
# lastBuyPrice = bitkub.costBasisAveragePrice(symbol,timestamp=1655446223) # Time 17-06-2565 13.10 น
lastBuyPrice = bitkub.costBasisAveragePrice(symbol,timestamp=1656670957) # Saturday, June 25, 2022 12:30:00 PM GMT+07:00
# try:
# lastBuyPrice = bitkub.costBasisAveragePrice(symbol,timestamp=1655446223)
if(math.isnan(lastBuyPrice)):
lastBuyPrice = bitkub.getLastBuyAverage(symbol)
# print(symbol , " : lastBuyPrice ",lastBuyPrice)
# except:
# lastBuyPrice = 0
alastBuyPrices[symbol] = lastBuyPrice
lastPrice = _rat
Available = ba['available']
# print(symbol,':', float(Available))
Reserved = ba['reserved']
try:
balance_value = Available *_rat['last']
except TypeError:
continue
amountToSell = float((balance_value-2) / _rat['last'])
amountToSell = round(amountToSell,8)
signal = []
_timeframe='5'
try:
aAmt = tradeOptions_mongo[symbol]
_timeframe = aAmt['timeframe']
stopLossWhenLossInTHB = aAmt['stopLossWhenLossInTHB']
except KeyError:
aAmt = tradeOptions_mongo['DEFAULT']
_timeframe = aAmt['timeframe']
stopLossWhenLossInTHB = aAmt['stopLossWhenLossInTHB']
# print('จำนวนเงินใน ', symbol , balance_value , 'บาท')
# timeframe = ช่วงเวลาของกราฟที่จะดึงข้อมูล 1, 5, 15, 60, 240, 1D
# MyDataFrame = bitkub.get_candle(symbol, timeframe=_timeframe)
MyDataFrame ,aUrl[symbol] = bitkub.get_candle(symbol, timeframe=_timeframe)
aDataFrame[symbol] = MyDataFrame
BTCDataFrame ,aUrl['BTC'] = bitkub.get_candle('BTC', timeframe='60')
BTCDataFrame1D ,aUrl['BTC'] = bitkub.get_candle('BTC', timeframe='1D')
# 'key': str(uuid4()),
# "asset": symbol,
# label_0 : macd_value,
# label_1 : macd_hist,
# label_2 : value_label,
# label_3 : signal_label,
# 'signal':signal,
# 'key': str(uuid4()),
# "asset": symbol,
# "macd_value":{label_0 : macd_value},
# "macd_hist":{label_1 : macd_hist},
# "value_label":{label_2 : value_label},
# "signal_label":{label_3 : signal_label},
# 'signal':signal,
# label_0 = f'MACD({fast}, {slow}, {signal}) value'
# label_1 = f'MACD({fast}, {slow}, {signal}) hist'
# label_2 = f'MACD({fast}, {slow}, {signal}) value signal'
# label_3 = f'MACD({fast}, {slow}, {signal}) hist signal'
try:
a = bitkub.STOCHRSIsignal(MyDataFrame,symbol)
BTCRSI = bitkub.STOCHRSIsignal(BTCDataFrame,'BTC')
BTCRSI1D = bitkub.STOCHRSIsignal(BTCDataFrame1D,'BTC')
aa = stochrsi_db[tb_name].insert_one(a)
aa = stochrsi_db[tb_name].insert_one(BTCRSI)
except:
continue
try:
b = bitkub.MACDsignal(MyDataFrame,symbol)
bb = macd_db[tb_name].insert_one(b)
except:
continue
textBTC = 'BTC' + '\n Timeframe : 1H \n```' + '\n STOCH RSI : ' + str(BTCRSI['STOCHRSIk']) + '\n ราคา : ' + str(_ratBTC['last']) + '฿ \n ส่งซิก : ' + BTCRSI['SignalDesc'] + '``` \n'
textBTC1D = 'BTC' + '\n Timeframe : 1D \n```' + '\n STOCH RSI : ' + str(BTCRSI1D['STOCHRSIk']) + '\n ราคา : ' + str(_ratBTC['last']) + '฿ \n ส่งซิก : ' + BTCRSI1D['SignalDesc'] + '``` \n'
text = symbol + '\n Timeframe : '+ _timeframe +'m \n```' + '\n STOCH RSI : ' + str(a['STOCHRSIk']) + '\n ราคา : ' + str(_rat['last']) + '฿ \n ส่งซิก : ' + a['SignalDesc'] + '```'
textMACD = f"\n``` MACD Value : {b['macd_value']['MACD(12, 26, 9) value']} \n MACD HIST Value: {b['macd_hist']['MACD(12, 26, 9) hist']} \n MACD Value Signal: {b['value_label']['MACD(12, 26, 9) value signal']} \n MACD Hist Signal : {b['signal_label']['MACD(12, 26, 9) hist signal']} \n MACD Signal : {b['signal']} ```"
print('\nDoing : ', symbol.strip() , ' RSI Signal : ' , a['signal'] , ' RSI : ' , a['STOCHRSIk'])
# amountToSell = (balance_value-2) / _rat['last']
# blaaa[symbol] = amountToSell
_STOCHRSIk = a['STOCHRSIk']
_BTC_STOCHRSIk = BTCRSI['STOCHRSIk']
_signal = a['signal']
if(a['signal'] != 'Hold'):
bitkub.sendLine(str(textBTC1D) + str(textBTC) + text + str(textMACD) , token = 'LINENOTIFYTOKEN')
print(str(textBTC) +str(text) + str(textMACD))
if symbol in tradeLists_mongo:
print('กำลังทำงานในเหรียญ : ' , symbol)
buyResponse= {}
_firstInitial = aAmt['firstInitial']
aProfitTotake = aAmt['profitTotake']
_tradeStyle = aAmt['tradeStyle']
condition = {'cash':cash,'buymai':(balance_value-aAmt['Buy']),'amt/2':(aAmt['Buy']/2),'buy':aAmt['Buy'],'rat':_rat,'sell':amountToSell}
ablaaa[symbol] = {'Available':Available,'amountToSell':amountToSell,'Reserved':Reserved,'_rat':_rat,'balance_value':balance_value,'Action':condition}
aOpenOrder[symbol] = bitkub.getSymOpenOrder(_pair)
aOpenOrderResult = aOpenOrder[symbol]['result']
# ซื้ออออออออ
if (a['signal'] == 'Buy' and _BTC_STOCHRSIk < buyBtcRSI):
print('กำลังทำงานในเหรียญ : ' , symbol , ' ด้วยการซื้อ')
buyMai = balance_value
maxBuyAmt = (aAmt['MaxAmt'])
if(cash >= aAmt['Buy'] and balance_value <= maxBuyAmt):
if(len(aOpenOrderResult)>=1):
for resultOrder in aOpenOrderResult:
_sym=symbol
_id=resultOrder['id']
_sd =resultOrder['side']
_hash=resultOrder['hash']
_rate=resultOrder['rate']
_amount=resultOrder['amount']
if(_sd == 'BUY'):
print('กำลังทำงานในเหรียญ : ' , symbol , ' ยกเลิกออเดอร์เก่า')
bitkub.cancelOpenOrder(_sym, _id, _sd,_hash,_rate,_amount,lineOrderToken)
cancleDbDataSave = {
"hash": _hash,
"key": str(uuid4()),
"Asset": _sym,
"idOrder": _id,
"Side":_sd,
"Rate":_rate,
"Amount":_amount,
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
cancleDb[APIKEYBITKUB].insert_one(cancleDbDataSave)
print('กำลังทำงานในเหรียญ : ' , symbol , ' เงินพอซื้อ')
if(balance_value <= maxBuyAmt):
amtChecked = maxBuyAmt - balance_value
amtToBuy = aAmt['Buy']
if(amtChecked>=amtToBuy):
buyResponse = bitkub.buy(_pair, amtToBuy , _rat['last'],lineOrderToken)
buyResponse = buyResponse['result']
buyDataSave = {
"hash": str(buyResponse['hash']),
"key": str(uuid4()),
"Asset": symbol,
"Signal": _signal,
"AssetInTHB":balance_value,
"PreviousAvgBuyPrice":lastBuyPrice,
"BuyPrice":_rat['last'],
"Available":Available,
"Reserved":Reserved,
"AmountToBuy":aAmt['Buy'],
"Type":buyResponse['typ'],
"Fee":buyResponse['fee'],
"CreditFee":buyResponse['cre'],
"AmountToReceive":buyResponse['rec'],
"timestamp":buyResponse['ts'],
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
buyDb[APIKEYBITKUB].insert_one(buyDataSave)
print('กำลังทำงานในเหรียญ : ' , symbol , ' สั่งซื้อสำเร็จ')
else:
if(amtChecked>=10):
buyResponse = bitkub.buy(_pair, amtChecked , _rat['last'],lineOrderToken)
buyResponse = buyResponse['result']
buyDataSave = {
"hash": str(buyResponse['hash']),
"key": str(uuid4()),
"Asset": symbol,
"Signal": _signal,
"AssetInTHB":balance_value,
"PreviousAvgBuyPrice":lastBuyPrice,
"BuyPrice":_rat['last'],
"Available":Available,
"Reserved":Reserved,
"AmountToBuy":aAmt['Buy'],
"Type":buyResponse['typ'],
"Fee":buyResponse['fee'],
"CreditFee":buyResponse['cre'],
"AmountToReceive":buyResponse['rec'],
"timestamp":buyResponse['ts'],
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
buyDb[APIKEYBITKUB].insert_one(buyDataSave)
print('กำลังทำงานในเหรียญ : ' , symbol , ' สั่งซื้อสำเร็จ ด้วยเศษเงินที่เหลือ :' , amtChecked)
else:
print('กำลังทำงานในเหรียญ : ' , symbol , ' จำนวนสั่งซื้อ น้อยไป ไม่ถึง 10: ',_pair , ' Amount : ' ,amtChecked)
print('กำลังทำงานในเหรียญ : ' , symbol , ' สั่งซื้อแล้ว')
else:
print('กำลังทำงานในเหรียญ : ' , symbol , ' มีแล้วรอขาย')
else:
diff = maxBuyAmt - balance_value
if( balance_value > maxBuyAmt):
print('กำลังทำงานในเหรียญ : ' , symbol ,'มีเหรียญเยอะกว่าค่าสูงสุดอยู่แล้ว ไม่ซื้อจ๊ะ : ' , symbol)
elif(diff > aAmt['Buy']):
print('กำลังทำงานในเหรียญ : ' , symbol ,'มีเหรียญเยอะกว่าค่าสูงสุดอยู่แล้ว ไม่ซื้อจ๊ะ Diff > amtBuy : ' , symbol , ' diff:',diff,' amtBuy:',aAmt['Buy'])
else:
if(len(aOpenOrderResult)>=1):
for resultOrder in aOpenOrderResult:
_sym=symbol
_id=resultOrder['id']
_sd =resultOrder['side']
_hash=resultOrder['hash']
_rate=resultOrder['rate']
_amount=resultOrder['amount']
if(_sd == 'BUY'):
bitkub.cancelOpenOrder(_sym, _id, _sd,_hash,_rate,_amount,lineOrderToken)
cancleDbDataSave = {
"hash": _hash,
"key": str(uuid4()),
"Asset": _sym,
"idOrder": _id,
"Side":_sd,
"Rate":_rate,
"Amount":_amount,
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
cancleDb[APIKEYBITKUB].insert_one(cancleDbDataSave)
if(cash>10):
buyResponse = bitkub.buy(_pair, cash , _rat['last'],lineOrderToken)
buyResponse = buyResponse['result']
buyDataSave = {
"hash": str(buyResponse['hash']),
"key": str(uuid4()),
"Asset": symbol,
"Signal": _signal,
"AssetInTHB":balance_value,
"PreviousAvgBuyPrice":lastBuyPrice,
"BuyPrice":_rat['last'],
"Available":Available,
"Reserved":Reserved,
"AmountToBuy":aAmt['Buy'],
"Type":buyResponse['typ'],
"Fee":buyResponse['fee'],
"CreditFee":buyResponse['cre'],
"AmountToReceive":buyResponse['rec'],
"timestamp":buyResponse['ts'],
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
buyDb[APIKEYBITKUB].insert_one(buyDataSave)
else:
allX = {'Cash':cash,'aAmt[Buy]':aAmt['Buy'] ,'balance_value':balance_value,'maxBuyAmt':maxBuyAmt}
print('กำลังทำงานในเหรียญ : ' , symbol ,'เงินน้อยไปซื้อไม่ได้ : ' , symbol ,' : ', allX)
bitkub.sendLine(f"เงินคุณไม่พอซื้อ {symbol} โปรดเติมกระสุน \n เงินคุณมี {cash} \n บอทจะซื้อ {aAmt['Buy']}", token=lineOrderToken)
# ขายยยยยยยยยยยยยย
elif (a['signal'] == 'Sell'):
print('กำลังทำงานในเหรียญ : ' , symbol ,' ขาย')
profitMai = balance_value - (Available*lastBuyPrice)
# TRADE STYLE
if(_tradeStyle == 'fixProfit'):
print('กำลังทำงานในเหรียญ : ' , symbol ,' ขาย แบบ fixProfit')
# FIX RATE
if(profitMai>=float(aProfitTotake)):
if(Available>=amountToSell and balance_value >= 10):
if(len(aOpenOrderResult)>=1):
for resultOrder in aOpenOrderResult:
_sym=symbol
_id=resultOrder['id']
_sd =resultOrder['side']
_hash=resultOrder['hash']
_rate=resultOrder['rate']
_amount=resultOrder['amount']
if(_sd == 'SELL'):
bitkub.cancelOpenOrder(_sym, _id, _sd,_hash,_rate,_amount,lineOrderToken)
print('ยกเลิกออเดอร์ตั้งขายก่อนหน้า : ',symbol)
cancleDbDataSave = {
"hash": _hash,
"key": str(uuid4()),
"Asset": _sym,
"idOrder": _id,
"Side":_sd,
"Rate":_rate,
"Amount":_amount,
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
cancleDb[APIKEYBITKUB].insert_one(cancleDbDataSave)
bitkub.sell(_pair, amountToSell, _rat['last'],lineOrderToken)
print('กำลังทำงานในเหรียญ : ' , symbol ,' ขาย แบบ fixProfit ตั้งขาย : ', _pair , ' Amt:', amountToSell,' Price:', _rat['last'] )
bitkub.sendLine('ขายแบบ Fix Rate : '+symbol + 'STOCH RSI : ' + _STOCHRSIk + ' Sell : '+ amountToSell + '%'+ ' Price : ' +_rat['last'] + ' LastBuyPrice : ' + lastBuyPrice + ' Profit : '+profitMai , token=lineOrderToken)
else:
print('กำลังทำงานในเหรียญ : ' , symbol ,' ต้องซื้อก่อนจะขาย ' )
# IGNORE PROFIT Sell if RSI too High Don't Care Profit
if(aProfitTotake=='Ignore'):
if(Available>=amountToSell and balance_value >= 10):
if(len(aOpenOrderResult)>=1):
for resultOrder in aOpenOrderResult:
_sym=symbol
_id=resultOrder['id']
_sd =resultOrder['side']
_hash=resultOrder['hash']
_rate=resultOrder['rate']
_amount=resultOrder['amount']
if(_sd == 'SELL'):
bitkub.cancelOpenOrder(_sym, _id, _sd,_hash,_rate,_amount,lineOrderToken)
print('กำลังทำงานในเหรียญ : ' , symbol ,' ยกเลิกออเดอร์ตั้งขายก่อนหน้า งานขาย ' )
cancleDbDataSave = {
"hash": _hash,
"key": str(uuid4()),
"Asset": _sym,
"idOrder": _id,
"Side":_sd,
"Rate":_rate,
"Amount":_amount,
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
cancleDb[APIKEYBITKUB].insert_one(cancleDbDataSave)
bitkub.sell(_pair, amountToSell, _rat['last'],lineOrderToken)
print('ตั้งขาย : ', _pair , ' Amt:', amountToSell,' Price:', _rat['last'] )
bitkub.sendLine('ขายแบบไม่สนกำไร อิง RSI เป็นหลัก : '+symbol + 'STOCH RSI : ' + _STOCHRSIk + ' Sell : '+ amountToSell + '%'+ ' Price : ' +_rat['last'] + ' LastBuyPrice : ' + lastBuyPrice + ' Profit : '+profitMai , token=lineOrderToken)
else:
print('ต้องซื้อก่อนจะขายออก แบบไม่สนใจกำไร : ',symbol)
if(_tradeStyle == 'stepProfit'):
print('กำลังทำงานในเหรียญ : ' , symbol ,' งานขายแบบ stepProfit ' )
try:
AtradeStep = tradeStyleSteps_mongo[symbol]
except KeyError:
AtradeStep = tradeStyleSteps_mongo['DEFAULT']
for _range in AtradeStep:
_min = AtradeStep[_range]['Min']
_max = AtradeStep[_range]['Max']
_PercentToSell = AtradeStep[_range]['PercentToSell']
# print('_PercentToSell:',_PercentToSell)
amountToSell = (balance_value*_PercentToSell) / 100
# print('amountToSell : (balance_value*_PercentToSell) / 100 : ' ,amountToSell)
amountToSell = round(amountToSell,15)
# print('amountToSell : round(amountToSell,10) : ' ,amountToSell)
amountToSell = amountToSell / _rat['last']
# print('amountToSell : amountToSell / _rat["last"] : ' , ('%f' % amountToSell).rstrip('0').rstrip('.'))
cashRecieve = amountToSell * _rat['last']
a = ('%f' % amountToSell).rstrip('0').rstrip('.')
# print(a)
profitMai = (float(_rat['last'])*float(a)) - (float(a)*float(lastBuyPrice))
aFee = (cashRecieve*bitkubFee)
aProfitWithFee = profitMai - (aFee*2)
if(Available>=float(a) and balance_value >= 10 and cashRecieve >= 10 and float(a) >= 0.0001):
# # DEBUG
# if(symbol =='BTC'):
# abtc_STOCHRSIk = _STOCHRSIk
# abtcbalance_value = balance_value
# abtcAvailable = Available
# abtclastBuyPrice = lastBuyPrice
# abtcNowPrice = _rat['last']
# abtcProfit = balance_value - (Available*lastBuyPrice)
# aBtc_min = AtradeStep[_range]['Min']
# aBtc_max = AtradeStep[_range]['Max']
# aBtc_PercentToSell = AtradeStep[_range]['PercentToSell']
# aBtcamountToSell = (balance_value*_PercentToSell) / 100
# aBtcamountToSell = amountToSell / _rat['last']
# aBtccashRecieve = amountToSell * _rat['last']
# aBtca = ('%f' % amountToSell).rstrip('0').rstrip('.')
# # END
if(_STOCHRSIk >= _min and _STOCHRSIk <= _max):
print('********')
print('Preparing to sell : ',symbol)
print('StochRSI : ' , _STOCHRSIk)
print('balance_value : ' , balance_value)
print('lastBuyPrice : ' , lastBuyPrice)
print('CurrentPrice : ' , _rat['last'])
print('Available : ' , Available)
print('Amount To Sell : ' , float(a))
print('cashRecieve : ' , cashRecieve)
print('aProfitWithFee : ' , aProfitWithFee)
print('Profit without Fee : ' , profitMai)
print('aProfitTotake : ' , aProfitTotake)
print('_min : ' , _min)
print('_max : ' , _max)
print('_PercentToSell : ' , _PercentToSell)
print('_PercentToSell : ' , float(a))
print('Profit : ',aProfitWithFee , ' \n Fee : ' , aFee , '\n Profit - Fee Buy,Sell : ' , aProfitWithFee , '\n ******** ')
# profitMai = (_rat['last']*a) - (a*lastBuyPrice)
# profitMai = balance_value - (Available*lastBuyPrice)
if(aProfitWithFee >= float(aProfitTotake)):
if(len(aOpenOrderResult)>=1):
for resultOrder in aOpenOrderResult:
_sym=symbol
_id=resultOrder['id']
_sd =resultOrder['side']
_hash=resultOrder['hash']
_rate=resultOrder['rate']
_amount=resultOrder['amount']
if(_sd == 'SELL'):
bitkub.cancelOpenOrder(_sym, _id, _sd,_hash,_rate,_amount,lineOrderToken)
remove = profitDb[APIKEYBITKUB].delete_one({"hash":_hash})
cancleDbDataSave = {
"hash": _hash,
"key": str(uuid4()),
"Asset": _sym,
"idOrder": _id,
"Side":_sd,
"Rate":_rate,
"Amount":_amount,
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
cancleDb[APIKEYBITKUB].insert_one(cancleDbDataSave)
print('ยกเลิกออเดอร์ตั้งขายก่อนหน้า : ',symbol)
# bitkub.sell(_pair, a, _rat['last'],lineOrderToken)
_textSellDescription = '\nขายแบบ STEP ขั้น RSI : '+ str(symbol) + '\nSTOCH RSI : ' + str(_STOCHRSIk) + '\nSell : '+ str(_PercentToSell) + '%' + '\nจำนวน : ' + str(a) + '\nราคาปัจจุบัน : ' + str(_rat['last']) + '\nราคาซื้อล่าสุด : ' + str(lastBuyPrice) + '\nกำไร : '+ str(profitMai)+'฿'
sellResponse = bitkub.sell(_pair, a, _rat['last'],lineOrderToken,_textSellDescription)
sellResponse = sellResponse['result']
profitDataSave = {
"hash": str(sellResponse['hash']),
"key": str(uuid4()),
"Asset": symbol,
"Signal": _signal,
"StochRSI": _STOCHRSIk,
"AssetInTHB":balance_value,
"AvgBuyPrice":lastBuyPrice,
"SellPrice":_rat['last'],
"Available":Available,
"Amount":a,
"PercentToSell" : _PercentToSell,
"Reserved":Reserved,
"Profit":profitMai,
"ProfitGoal":aProfitTotake,
"Description":_textSellDescription,
"AmountToBuy":sellResponse['amt'],
"Type":sellResponse['typ'],
"Fee":sellResponse['fee'],
"CreditFee":sellResponse['cre'],
"AmountToReceive":sellResponse['rec'],
"timestamp":sellResponse['ts'],
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
# {
# "error": 0,
# "result": {
# "id": 1, // order id
# "hash": "fwQ6dnQWQPs4cbatF5Am2xCDP1J", // order hash
# "typ": "limit", // order type
# "amt": 1000, // spending amount
# "rat": 15000, // rate
# "fee": 2.5, // fee
# "cre": 2.5, // fee credit used
# "rec": 0.06666666, // amount to receive
# "ts": 1533834547 // timestamp
# }
# }
profitDb[APIKEYBITKUB].insert_one(profitDataSave)
# print('ขายแบบ STEP ขั้น RSI : ',symbol , ' RSI : ' , _STOCHRSIk , ' Sell : ', _PercentToSell , '%', ' Price : ' ,_rat['last'] , ' LastBuyPrice : ' , lastBuyPrice , ' Profit : ',profitMai)
print('ขายแบบ STEP ขั้น RSI : '+ str(symbol) + 'STOCH RSI : ' + str(_STOCHRSIk) + ' Sell : '+ str(_PercentToSell) + '%' + ' จำนวน : ' + str(a) + ' ราคาปัจจุบัน : ' + str(_rat['last']) + ' ซื้อล่าสุดราคา : ' + str(lastBuyPrice) + ' กำไร : '+ str(profitMai) )
else:
print('ขาดทุน ตาม Percent RSI ที่จะขาย : ' , aProfitWithFee)
print('กำลังทำงาน ตรวจสอบ StopLoss:' , symbol , ' ขายทอดตลาด StopLoss')
# self,_pair,_amt,_rat,_token ,_txtOptional=''
_PercentToSell = 99
amountToSell = (balance_value*_PercentToSell) / 100
amountToSell = round(amountToSell,15)
amountToSell = amountToSell / _rat['last']
cashRecieve = amountToSell * _rat['last']
a = ('%f' % amountToSell).rstrip('0').rstrip('.')
profitMai = (float(_rat['last'])*float(a)) - (float(a)*float(lastBuyPrice))
aFee = (cashRecieve*bitkubFee)
aProfitWithFee = profitMai - (aFee*2)
if(stopLossWhenLossInTHB>aProfitWithFee):
print('Sell Market When : StopLoss > Profit' , str(stopLossWhenLossInTHB) ,'>',str(aProfitWithFee))
print('Amount To Sell : ',str(a))
print('Cur Price : ',str( _rat['last']))
print('Last Buy Price : ',str( lastBuyPrice ))
sellResponse = bitkub.sellMarket(_pair,a, _rat['last'],lineOrderToken,'ขายทิ้ง Stop Loss ที่ขาดทุน :' + str(aProfitWithFee))
sellResponse = json.loads(sellResponse.text)
sellResponse = sellResponse['result']
botStopLossDbSave = {
"hash": str(sellResponse['hash']),
"key": str(uuid4()),
"Asset": symbol,
"Signal": _signal,
"StochRSI": _STOCHRSIk,
"AssetInTHB":balance_value,
"AvgBuyPrice":lastBuyPrice,
"SellPrice":_rat['last'],
"Available":Available,
"Amount":a,
"PercentToSell" : _PercentToSell,
"Reserved":Reserved,
"Profit":profitMai,
"ProfitGoal":aProfitTotake,
"Description":'ขายทิ้ง Stop Loss ที่ขาดทุน :' + str(aProfitWithFee),
"AmountToBuy":sellResponse['amt'],
"Type":sellResponse['typ'],
"Fee":sellResponse['fee'],
"CreditFee":sellResponse['cre'],
"AmountToReceive":sellResponse['rec'],
"timestamp":sellResponse['ts'],
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
botStopLossDb[APIKEYBITKUB].insert_one(botStopLossDbSave)
# bitkub.sendLine('ขายแบบ STEP ขั้น RSI : '+ str(symbol) + ' STOCH RSI : ' + str(_STOCHRSIk) + ' Sell : '+ str(_PercentToSell) + '%' + ' จำนวน : ' + str(a) + ' ราคาปัจจุบัน : ' + str(_rat['last']) + ' ซื้อล่าสุดราคา : ' + str(lastBuyPrice) + ' กำไร : '+ str(profitMai) ,token=lineOrderToken)
logSave = {
"CASH": cash,
"Asset": symbol,
"Signal": _signal,
"StochRSI": _STOCHRSIk,
"AssetInTHB":balance_value,
"AvgBuyPrice":lastBuyPrice,
"CurrentPrice":_rat['last'],
"Available":Available,
"Reserved":Reserved,
"Profit":profitMai,
"ProfitGoal":aProfitTotake,
"LastUpdate": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
}
joblogDb[APIKEYBITKUB].insert_one(logSave)
botActivateDb.update_one({'Instance': APIKEYBITKUB},
{'$set': {'Activate': True}
}
,upsert=True
)
print('***************** END *******************')
# else:
# pass
# print('Trade Option Not config TradeStyle')
# text = '```' + symbol + ' : ' + a['SignalDesc'] + '```'
# print('Doing : ', symbol , 'RSI Signal : ' , a['signal'] , '| MACD Signal : ',b['signal'])
# if(a['signal'] != 'Hold'):
# bitkub.sendLine(text,token = 'LINENOTIFYTOKEN')
# for s in tradeLists:
# symbol = s
# signal = []
# _pair = 'THB_'+symbol
# _amt = tradeAmt[symbol]
# if(s=='THB' or s=='DON'):
# pass
# else:
# MyDataFrame = bitkub.get_candle(symbol, timeframe='1')
# a = bitkub.STOCHRSIsignal(MyDataFrame,symbol)
# aa = stochrsi_db[tb_name].insert_one(a)
# # b = bitkub.MACDsignal(MyDataFrame,symbol)
# # bb = macd_db[tb_name].insert_one(b)
# _rat = bitkub.get_last_price(_pair)
# text = symbol + '\n ```' + '\n RSI : ' + str(a['STOCHRSIk']) + '\n ราคา : ' + str(_rat['last']) + '฿ \n ส่งซิก : *' + a['SignalDesc'] + '*```'
# print('Doing : ', symbol , 'RSI Signal : ' , a['signal'] , ' RSI : ' , a['STOCHRSIk'])
# if(a['signal'] != 'Hold'):
# bitkub.sendLine(text,token = 'LINENOTIFYTOKEN')
# if (a['signal'] == 'Buy'):
# print('ซื้อ ',_pair , )
# _rat = bitkub.get_last_price(_pair)
# bitkub.buy(_pair, _amt['Buy'], _rat['last'],'LINENOTIFYTOKEN')
# elif (a['signal'] == 'Sell'):
# MaxAmt
# _rat = bitkub.get_last_price(_pair)
# bitkub.sell(_pair, _amt['Sell'], _rat['last'],'LINENOTIFYTOKEN')
# df = pd.DataFrame()
# a = type(MyDataFrame)
# for i in obj:
# df[f'symbol_{i}'] = pd.Series(i, name = 'close').cumsum()