-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstable_api.py
More file actions
1754 lines (1497 loc) · 67.8 KB
/
Copy pathstable_api.py
File metadata and controls
1754 lines (1497 loc) · 67.8 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
# python
from iqoptionapi.api import IQOptionAPI
import iqoptionapi.constants as OP_code
import iqoptionapi.country_id as Country
import threading
import time
import logging
import operator
import iqoptionapi.global_value as global_value
from collections import defaultdict
from collections import deque
from iqoptionapi.expiration import get_expiration_time, get_remaning_time
from datetime import datetime, timedelta
import json
def nested_dict(n, type):
if n == 1:
return defaultdict(type)
else:
return defaultdict(lambda: nested_dict(n-1, type))
class IQ_Option:
__version__ = "8.9"
def __init__(self, email, password,http_proxy_host=None,http_proxy_port=None,http_proxy_auth=None,set_ssid=None,auto_logout=True):
self.size = [1, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800,
3600, 7200, 14400, 28800, 43200, 86400, 604800, 2592000]
self.email = email
self.password = password
self.suspend = 0.1
self.thread = None
self.subscribe_candle = []
self.subscribe_candle_all_size = []
self.subscribe_mood = []
# for digit
self.get_digital_spot_profit_after_sale_data = nested_dict(2, int)
self.get_realtime_strike_list_temp_data = {}
self.get_realtime_strike_list_temp_expiration = 0
self.SESSION_HEADER={"User-Agent":r"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36"}
self.SESSION_COOKIE={}
self.http_proxy_host=http_proxy_host
self.http_proxy_port=http_proxy_host
self.http_proxy_auth=http_proxy_host
self.set_ssid=set_ssid
self.auto_logout=auto_logout
self._2FA_TOKEN=None
#
# --start
#self.connect()
# this auto function delay too long
# --------------------------------------------------------------------------
def logout(self):
self.api.logout()
def set_call_back_for_client(self,function):
global_value.client_callback[self.api.object_id]=function
def get_server_timestamp(self):
return self.api.timesync.server_timestamp
def re_subscribe_stream(self):
try:
for ac in self.subscribe_candle:
sp = ac.split(",")
self.start_candles_one_stream(sp[0], sp[1])
except:
pass
# -----------------
try:
for ac in self.subscribe_candle_all_size:
self.start_candles_all_size_stream(ac)
except:
pass
# -------------reconnect subscribe_mood
try:
for ac in self.subscribe_mood:
self.start_mood_stream(ac)
except:
pass
def set_session(self,header,cookie):
self.SESSION_HEADER=header
self.SESSION_COOKIE=cookie
def get_ssid(self):
return global_value.SSID[self.api.object_id]
def setting_2FA_TOKEN(self,code):
self._2FA_TOKEN=code
def TWO_FA(self, token,method=None,code=None):
r=self.api.TWO_FA(token,method,code)
return json.loads(r.text)
def close(self):
try:
self.api.close()
if self.auto_logout:
self.api.logout()
except:
pass
def connect(self):
try:
self.api.close()
except:
pass
#logging.error('**warning** self.api.close() fail')
#id-iqoption.com some country only can using this url
#Iqoption.com
try:
self.set_ssid=global_value.SSID[self.api.object_id]
except:
pass
self.api = IQOptionAPI(
"iqoption.com", self.email, self.password,http_proxy_host=self.http_proxy_host,http_proxy_port=self.http_proxy_port,http_proxy_auth=self.http_proxy_auth,set_ssid=self.set_ssid,auto_logout=self.auto_logout,_2FA_TOKEN=self._2FA_TOKEN)
check = None
self.api.set_session(headers=self.SESSION_HEADER,cookies=self.SESSION_COOKIE)
check,reason = self.api.connect()
if check == True:
# -------------reconnect subscribe_candle
self.re_subscribe_stream()
# ---------for async get name: "position-changed", microserviceName
while global_value.balance_id[self.api.object_id]==None:
pass
balances=self.get_balances()
#print(balances)
for i in balances["msg"]:
id=i["id"]
self.position_change_all("subscribeMessage",id)
rout=["internal-billing.balance-created","internal-billing.auth-balance-changed","internal-billing.balance-changed","internal-billing.marginal-changed","tournaments.user-registered-in-tournament","tournaments.user-tournament-position-changed"]
for name in rout:
self.api.subscribeMessage_routingFilters_None(name)
self.order_changed_all("subscribeMessage")
self.api.setOptions("", True)
"""
self.api.subscribe_position_changed(
"position-changed", "multi-option", 2)
self.api.subscribe_position_changed(
"trading-fx-option.position-changed", "fx-option", 3)
self.api.subscribe_position_changed(
"position-changed", "crypto", 4)
self.api.subscribe_position_changed(
"position-changed", "forex", 5)
self.api.subscribe_position_changed(
"digital-options.position-changed", "digital-option", 6)
self.api.subscribe_position_changed(
"position-changed", "cfd", 7)
"""
#self.get_balance_id()
return True,None
else:
return False,reason
# self.update_ACTIVES_OPCODE()
def check_connect(self):
# True/False
if global_value.check_websocket_if_connect[self.api.object_id] == 0:
return False
else:
return True
# wait for timestamp getting
# _________________________UPDATE ACTIVES OPCODE_____________________
def get_all_ACTIVES_OPCODE(self):
return OP_code.ACTIVES
def update_ACTIVES_OPCODE(self):
# update from binary option
self.get_ALL_Binary_ACTIVES_OPCODE()
self.get_All_Digital_ACTIVES_OPCODE()
#crypto /dorex/cfd
self.instruments_input_all_in_ACTIVES()
dicc = {}
for lis in sorted(OP_code.ACTIVES.items(), key=operator.itemgetter(1)):
dicc[lis[0]] = lis[1]
OP_code.ACTIVES = dicc
def get_name_by_activeId(self, activeId):
info = self.get_financial_information(activeId)
try:
return info["msg"]["data"]["active"]["name"]
except:
return None
def get_financial_information(self, activeId):
self.api.financial_information = None
self.api.get_financial_information(activeId)
while self.api.financial_information == None:
pass
return self.api.financial_information
def get_leader_board(self,country,from_position,to_position,near_traders_count,user_country_id=0,near_traders_country_count=0,top_country_count=0,top_count=0,top_type=2):
self.api.leaderboard_deals_client=None
country_id=Country.ID[country]
self.api.Get_Leader_Board(country_id,user_country_id,from_position,to_position,near_traders_country_count,near_traders_count,top_country_count,top_count,top_type)
while self.api.leaderboard_deals_client==None:
pass
return self.api.leaderboard_deals_client
def get_active_exposure(self,instrument_type,active,duration,currency="USD"):
#instrument_type=["digital-option","turbo-option","binary-option"]
request_id=global_value.get_req_id(self.api.object_id)
active_id=OP_code.ACTIVES[active]
self.api.get_active_exposure(instrument_type,active_id,duration,request_id,currency)
self.api.active_exposure[request_id]=None
while self.api.active_exposure[request_id]==None:
pass
_tmp=self.api.active_exposure[request_id]
del self.api.active_exposure[request_id]
ans = {}
try:
ans["call"]=_tmp["msg"]["call"]
ans["put"]=_tmp["msg"]["put"]
except:
pass
return ans
def get_instruments(self, type,polling=0):
# type="crypto"/"forex"/"cfd"
time.sleep(self.suspend)
self.api.instruments = None
while self.api.instruments == None:
try:
self.api.get_instruments(type)
start = time.time()
while self.api.instruments == None and time.time()-start < 10:
pass
except:
logging.error('**error** api.get_instruments need reconnect')
self.connect()
time.sleep(polling)
return self.api.instruments
def instruments_input_to_ACTIVES(self, type):
instruments = self.get_instruments(type)
for ins in instruments["instruments"]:
OP_code.ACTIVES[ins["id"]] = ins["active_id"]
def instruments_input_all_in_ACTIVES(self):
self.instruments_input_to_ACTIVES("crypto")
self.instruments_input_to_ACTIVES("forex")
self.instruments_input_to_ACTIVES("cfd")
def get_All_Digital_ACTIVES_OPCODE(self):
underlying_list_data=self.get_digital_underlying_list_data()
for list_data in underlying_list_data["underlying"]:
active_id=list_data["active_id"]
name=list_data["name"]
OP_code.ACTIVES[name]=active_id
def get_ALL_Binary_ACTIVES_OPCODE(self):
init_info = self.get_all_init()
for dirr in (["binary", "turbo"]):
for i in init_info["result"][dirr]["actives"]:
OP_code.ACTIVES[(init_info["result"][dirr]
["actives"][i]["name"]).split(".")[1]] = int(i)
# _________________________self.api.get_api_option_init_all() wss______________________
def get_all_init(self):
while True:
self.api.api_option_init_all_result = None
while True:
try:
self.api.get_api_option_init_all()
break
except:
logging.error('**error** get_all_init need reconnect')
self.connect()
time.sleep(5)
start = time.time()
while True:
if time.time()-start > 30:
logging.error('**warning** get_all_init late 30 sec')
break
try:
if self.api.api_option_init_all_result != None:
break
except:
pass
try:
if self.api.api_option_init_all_result["isSuccessful"] == True:
return self.api.api_option_init_all_result
except:
pass
def get_all_init_v2(self,polling=0):
self.api.api_option_init_all_result_v2 = None
self.api.get_api_option_init_all_v2()
start_t = time.time()
while self.api.api_option_init_all_result_v2 == None:
if time.time()-start_t >= 30:
logging.error('**warning** get_all_init_v2 late 30 sec')
return None
time.sleep(polling)
return self.api.api_option_init_all_result_v2
# return OP_code.ACTIVES
# ------- chek if binary/digit/cfd/stock... if open or not
def get_all_open_time(self,polling):
# for binary option turbo and binary
OPEN_TIME = nested_dict(3, dict)
binary_data = self.get_all_init_v2(polling)
binary_list = ["binary", "turbo"]
for option in binary_list:
for actives_id in binary_data[option]["actives"]:
active = binary_data[option]["actives"][actives_id]
name = str(active["name"]).split(".")[1]
if active["enabled"] == True:
if active["is_suspended"] == True:
OPEN_TIME[option][name]["open"] = False
else:
OPEN_TIME[option][name]["open"] = True
else:
OPEN_TIME[option][name]["open"] = active["enabled"]
# for digital
digital_data = self.get_digital_underlying_list_data(polling)["underlying"]
for digital in digital_data:
name = digital["underlying"]
schedule = digital["schedule"]
OPEN_TIME["digital"][name]["open"] = False
for schedule_time in schedule:
start = schedule_time["open"]
end = schedule_time["close"]
if start < time.time() < end:
OPEN_TIME["digital"][name]["open"] = True
# for OTHER
instrument_list = ["cfd", "forex", "crypto"]
for instruments_type in instrument_list:
ins_data = self.get_instruments(instruments_type,polling)["instruments"]
for detail in ins_data:
name = detail["name"]
schedule = detail["schedule"]
OPEN_TIME[instruments_type][name]["open"] = False
for schedule_time in schedule:
start = schedule_time["open"]
end = schedule_time["close"]
if start < time.time() < end:
OPEN_TIME[instruments_type][name]["open"] = True
return OPEN_TIME
# --------for binary option detail
def get_binary_option_detail(self):
detail = nested_dict(2, dict)
init_info = self.get_all_init()
for actives in init_info["result"]["turbo"]["actives"]:
name = init_info["result"]["turbo"]["actives"][actives]["name"]
name = name[name.index(".")+1:len(name)]
detail[name]["turbo"] = init_info["result"]["turbo"]["actives"][actives]
for actives in init_info["result"]["binary"]["actives"]:
name = init_info["result"]["binary"]["actives"][actives]["name"]
name = name[name.index(".")+1:len(name)]
detail[name]["binary"] = init_info["result"]["binary"]["actives"][actives]
return detail
def get_all_profit(self):
all_profit = nested_dict(2, dict)
init_info = self.get_all_init()
for actives in init_info["result"]["turbo"]["actives"]:
name = init_info["result"]["turbo"]["actives"][actives]["name"]
name = name[name.index(".")+1:len(name)]
if init_info["result"]["turbo"]["actives"][actives]["enabled"]==False:
all_profit[name]["turbo"]={}
continue
all_profit[name]["turbo"] = (
100.0-init_info["result"]["turbo"]["actives"][actives]["option"]["profit"]["commission"])/100.0
for actives in init_info["result"]["binary"]["actives"]:
name = init_info["result"]["binary"]["actives"][actives]["name"]
name = name[name.index(".")+1:len(name)]
if init_info["result"]["binary"]["actives"][actives]["enabled"]==False:
all_profit[name]["binary"]={}
continue
all_profit[name]["binary"] = (
100.0-init_info["result"]["binary"]["actives"][actives]["option"]["profit"]["commission"])/100.0
return all_profit
def get_all_profit_v2(self):
all_profit = nested_dict(2, dict)
init_info = self.get_all_init_v2()
for actives in init_info["turbo"]["actives"]:
name = init_info["turbo"]["actives"][actives]["name"]
name = name[name.index(".")+1:len(name)]
if init_info["turbo"]["actives"][actives]["enabled"]==False:
all_profit[name]["turbo"]={}
continue
all_profit[name]["turbo"] = (
100.0-init_info["turbo"]["actives"][actives]["option"]["profit"]["commission"])/100.0
for actives in init_info["binary"]["actives"]:
name = init_info["binary"]["actives"][actives]["name"]
name = name[name.index(".")+1:len(name)]
if init_info["binary"]["actives"][actives]["enabled"]==False:
all_profit[name]["binary"]={}
continue
all_profit[name]["binary"] = (
100.0-init_info["binary"]["actives"][actives]["option"]["profit"]["commission"])/100.0
return all_profit
# ----------------------------------------
# ______________________________________self.api.getprofile() https________________________________
def get_profile(self):
req_id=global_value.get_req_id(self.api.object_id)
self.api.get_profile_ws(req_id)
while self.api.profile.msg==None:
pass
return self.api.profile.msg
def get_profile_ansyc(self):
while self.api.profile.msg==None:
pass
return self.api.profile.msg
"""def get_profile(self):
while True:
try:
respon = self.api.getprofile().json()
time.sleep(self.suspend)
if respon["isSuccessful"] == True:
return respon
except:
logging.error('**error** get_profile try reconnect')
self.connect()"""
def get_currency(self):
balances_raw=self.get_balances()
for balance in balances_raw["msg"]:
if balance["id"]==global_value.balance_id[self.api.object_id]:
return balance["currency"]
def get_balance_id(self):
return global_value.balance_id[self.api.object_id]
""" def get_balance(self):
self.api.profile.balance = None
while True:
try:
respon = self.get_profile()
self.api.profile.balance = respon["result"]["balance"]
break
except:
logging.error('**error** get_balance()')
time.sleep(self.suspend)
return self.api.profile.balance"""
def get_balance(self):
self.api.get_balances()
balances_raw=self.get_balances()
for balance in balances_raw["msg"]:
if balance["id"]==global_value.balance_id[self.api.object_id]:
return balance["amount"]
def get_balance_v2(self):
#more hight performance, asnyc
current_balance_id=global_value.balance_id[self.api.object_id]
if current_balance_id in self.api.balance:
return self.api.balance[current_balance_id]
else:
self.api.balance[current_balance_id]=self.get_balance()
return self.api.balance[current_balance_id]
def _get_balances(self):
self.api.balances_raw=None
self.api.get_balances()
while self.api.balances_raw == None:
pass
return self.api.balances_raw
def get_balances(self):
self.api.get_balances()
if self.api.balances_raw!=None:
return self.api.balances_raw
else:
while self.api.balances_raw == None:
pass
time.sleep(self.suspend)
return self.api.balances_raw
def get_balance_mode(self):
# self.api.profile.balance_type=None
for balance in self.get_balances()["msg"]:
if balance["id"]==global_value.balance_id[self.api.object_id]:
if balance["type"]==1:
return "REAL"
elif balance["type"]==4:
return "PRACTICE"
def reset_practice_balance(self):
self.api.training_balance_reset_request = None
self.api.reset_training_balance()
while self.api.training_balance_reset_request == None:
pass
return self.api.training_balance_reset_request
def position_change_all(self,Main_Name,user_balance_id):
instrument_type=["cfd","forex","crypto","digital-option","turbo-option","binary-option"]
for ins in instrument_type:
self.api.portfolio(Main_Name=Main_Name,name="portfolio.position-changed",instrument_type=ins,user_balance_id=user_balance_id)
def order_changed_all(self,Main_Name):
instrument_type=["cfd","forex","crypto","digital-option","turbo-option","binary-option"]
for ins in instrument_type:
self.api.portfolio(Main_Name=Main_Name,name="portfolio.order-changed",instrument_type=ins)
def portfolio_get_positions(self,limit=1,offset=0,polling_time=1):
self.api.positions=None
instrument_type=["cfd","forex","crypto","digital-option","turbo-option","binary-option"]
self.api.portfolio(Main_Name="sendMessage",name="portfolio.get-positions",instrument_type=instrument_type,limit=limit,offset=offset)
while self.api.positions==None:
time.sleep(polling_time)
pass
return self.api.positions
def get_balance_id_by_mode(self,mode):
for balance in self.get_balances()["msg"]:
if balance["type"] == 1:
real_id = balance["id"]
if balance["type"] == 4:
practice_id = balance["id"]
if mode=="REAL":
return real_id
elif mode=="PRACTICE":
return practice_id
else:
return None
def change_balance(self, Balance_MODE):
def set_id(b_id):
#if global_value.balance_id[self.api.object_id]!=None:
# self.position_change_all("unsubscribeMessage",global_value.balance_id[self.api.object_id])
global_value.balance_id[self.api.object_id]=b_id
#self.position_change_all("subscribeMessage",b_id)
if global_value._tmp_raw_balance_id[self.api.object_id]=={}:
for balance in self.get_balances()["msg"]:
if balance["type"] == 1:
real_id = balance["id"]
global_value._tmp_raw_balance_id[self.api.object_id]["REAL"]=real_id
if balance["type"] == 4:
practice_id = balance["id"]
global_value._tmp_raw_balance_id[self.api.object_id]["PRACTICE"]=practice_id
real_id = global_value._tmp_raw_balance_id[self.api.object_id]["REAL"]
practice_id = global_value._tmp_raw_balance_id[self.api.object_id]["PRACTICE"]
if Balance_MODE == "REAL":
set_id(real_id)
elif Balance_MODE == "PRACTICE":
set_id(practice_id)
else:
logging.error("ERROR doesn't have this mode")
exit(1)
# ________________________________________________________________________
# _______________________ CANDLE _____________________________
# ________________________self.api.getcandles() wss________________________
def get_candles(self, ACTIVES, interval, count, endtime):
self.api.candles.candles_data = None
while True:
try:
self.api.getcandles(
OP_code.ACTIVES[ACTIVES], interval, count, endtime)
while self.check_connect and self.api.candles.candles_data == None:
pass
if self.api.candles.candles_data != None:
break
except:
logging.error('**error** get_candles need reconnect')
self.connect()
return self.api.candles.candles_data
#######################################################
# ______________________________________________________
# _____________________REAL TIME CANDLE_________________
# ______________________________________________________
#######################################################
def start_candles_stream(self, ACTIVE, size, maxdict):
if size == "all":
for s in self.size:
self.full_realtime_get_candle(ACTIVE, s, maxdict)
self.api.real_time_candles_maxdict_table[ACTIVE][s] = maxdict
self.start_candles_all_size_stream(ACTIVE)
elif size in self.size:
self.api.real_time_candles_maxdict_table[ACTIVE][size] = maxdict
self.full_realtime_get_candle(ACTIVE, size, maxdict)
self.start_candles_one_stream(ACTIVE, size)
else:
logging.error(
'**error** start_candles_stream please input right size')
def stop_candles_stream(self, ACTIVE, size):
if size == "all":
self.stop_candles_all_size_stream(ACTIVE)
elif size in self.size:
self.stop_candles_one_stream(ACTIVE, size)
else:
logging.error(
'**error** start_candles_stream please input right size')
def get_realtime_candles(self, ACTIVE, size):
if size == "all":
try:
return self.api.real_time_candles[ACTIVE]
except:
logging.error(
'**error** get_realtime_candles() size="all" can not get candle')
return False
elif size in self.size:
try:
return self.api.real_time_candles[ACTIVE][size]
except:
logging.error(
'**error** get_realtime_candles() size='+str(size)+' can not get candle')
return False
else:
logging.error(
'**error** get_realtime_candles() please input right "size"')
def get_all_realtime_candles(self):
return self.api.real_time_candles
################################################
# ---------REAL TIME CANDLE Subset Function---------
################################################
# ---------------------full dict get_candle-----------------------
def full_realtime_get_candle(self, ACTIVE, size, maxdict):
candles = self.get_candles(
ACTIVE, size, maxdict, self.api.timesync.server_timestamp)
for can in candles:
self.api.real_time_candles[str(
ACTIVE)][int(size)][can["from"]] = can
# ------------------------Subscribe ONE SIZE-----------------------
def start_candles_one_stream(self, ACTIVE, size):
if (str(ACTIVE+","+str(size)) in self.subscribe_candle) == False:
self.subscribe_candle.append((ACTIVE+","+str(size)))
start = time.time()
self.api.candle_generated_check[str(ACTIVE)][int(size)] = {}
while True:
if time.time()-start > 20:
logging.error(
'**error** start_candles_one_stream late for 20 sec')
return False
try:
if self.api.candle_generated_check[str(ACTIVE)][int(size)] == True:
return True
except:
pass
try:
self.api.subscribe(OP_code.ACTIVES[ACTIVE], size)
except:
logging.error('**error** start_candles_stream reconnect')
self.connect()
time.sleep(1)
def stop_candles_one_stream(self, ACTIVE, size):
if ((ACTIVE+","+str(size)) in self.subscribe_candle) == True:
self.subscribe_candle.remove(ACTIVE+","+str(size))
while True:
try:
if self.api.candle_generated_check[str(ACTIVE)][int(size)] == {}:
return True
except:
pass
self.api.candle_generated_check[str(ACTIVE)][int(size)] = {}
self.api.unsubscribe(OP_code.ACTIVES[ACTIVE], size)
time.sleep(self.suspend*10)
# ------------------------Subscribe ALL SIZE-----------------------
def start_candles_all_size_stream(self, ACTIVE):
self.api.candle_generated_all_size_check[str(ACTIVE)] = {}
if (str(ACTIVE) in self.subscribe_candle_all_size) == False:
self.subscribe_candle_all_size.append(str(ACTIVE))
start = time.time()
while True:
if time.time()-start > 20:
logging.error('**error** fail '+ACTIVE +
' start_candles_all_size_stream late for 10 sec')
return False
try:
if self.api.candle_generated_all_size_check[str(ACTIVE)] == True:
return True
except:
pass
try:
self.api.subscribe_all_size(OP_code.ACTIVES[ACTIVE])
except:
logging.error(
'**error** start_candles_all_size_stream reconnect')
self.connect()
time.sleep(1)
def stop_candles_all_size_stream(self, ACTIVE):
if (str(ACTIVE) in self.subscribe_candle_all_size) == True:
self.subscribe_candle_all_size.remove(str(ACTIVE))
while True:
try:
if self.api.candle_generated_all_size_check[str(ACTIVE)] == {}:
break
except:
pass
self.api.candle_generated_all_size_check[str(ACTIVE)] = {}
self.api.unsubscribe_all_size(OP_code.ACTIVES[ACTIVE])
time.sleep(self.suspend*10)
# ------------------------top_assets_updated---------------------------------------------
def subscribe_top_assets_updated(self, instrument_type):
self.api.Subscribe_Top_Assets_Updated(instrument_type)
def unsubscribe_top_assets_updated(self, instrument_type):
self.api.Unsubscribe_Top_Assets_Updated(instrument_type)
def get_top_assets_updated(self, instrument_type):
if instrument_type in self.api.top_assets_updated_data:
return self.api.top_assets_updated_data[instrument_type]
else:
return None
# ------------------------commission_________
#instrument_type: "binary-option"/"turbo-option"/"digital-option"/"crypto"/"forex"/"cfd"
def subscribe_commission_changed(self, instrument_type):
self.api.Subscribe_Commission_Changed(instrument_type)
def unsubscribe_commission_changed(self, instrument_type):
self.api.Unsubscribe_Commission_Changed(instrument_type)
def get_commission_change(self, instrument_type):
return self.api.subscribe_commission_changed_data[instrument_type]
# -----------------------------------------------
# -----------------traders_mood----------------------
def start_mood_stream(self, ACTIVES):
if ACTIVES in self.subscribe_mood == False:
self.subscribe_mood.append(ACTIVES)
while True:
self.api.subscribe_Traders_mood(OP_code.ACTIVES[ACTIVES])
try:
self.api.traders_mood[OP_code.ACTIVES[ACTIVES]]
break
except:
time.sleep(5)
def stop_mood_stream(self, ACTIVES):
if ACTIVES in self.subscribe_mood == True:
del self.subscribe_mood[ACTIVES]
self.api.unsubscribe_Traders_mood(OP_code.ACTIVES[ACTIVES])
def get_traders_mood(self, ACTIVES):
# return highter %
return self.api.traders_mood[OP_code.ACTIVES[ACTIVES]]
def get_all_traders_mood(self):
# return highter %
return self.api.traders_mood
##############################################################################################
def raw_check_win(self,external_id):
position_data=self.get_history_positions(external_id=external_id)
ans_data=None
for row in position_data["msg"]["positions"]:
if row["external_id"]==external_id:
ans_data=row
if ans_data!=None:
return round(ans_data["pnl_realized"], 2)
return None
def check_win(self, external_id,polling_time=0.5):
ok_id=None
check,data=self.get_order(external_id)
def get_position_id():
nonlocal ok_id,data,check
if ok_id!=None:
return ok_id
if check:
#for forex...
position_id=None
position_id=data["position_id"]
while position_id==None:
_,data=self.get_order(external_id)
position_id=data["position_id"]
if data["status"]=="canceled":
return "canceled"
time.sleep(polling_time)
ok_id=position_id
else:
ok_id=external_id
return ok_id
while True:
external_id=get_position_id()
if external_id=="canceled":
return None
PL=self.raw_check_win(external_id)
if PL !=None:
return PL
time.sleep(polling_time)
def check_win_v2(self, id_number, polling_time):
while True:
check, data = self.get_betinfo(id_number)
win=data["result"]["data"][str(id_number)]["win"]
if check and win!="":
try:
return data["result"]["data"][str(id_number)]["profit"]-data["result"]["data"][str(id_number)]["deposit"]
except:
pass
time.sleep(polling_time)
def check_win_v3(self, id_number,polling_time):
while True:
try:
if self.get_async_order(id_number)["option-closed"] !={}:
break
except:
pass
time.sleep(polling_time)
return self.get_async_order(id_number)["option-closed"]["msg"]["profit_amount"]-self.get_async_order(id_number)["option-closed"]["msg"]["amount"]
# -------------------get infomation only for binary option------------------------
def get_betinfo(self, id_number):
# INPUT:int
while True:
self.api.game_betinfo.isSuccessful = None
start = time.time()
try:
self.api.get_betinfo(id_number)
except:
logging.error(
'**error** def get_betinfo self.api.get_betinfo reconnect')
self.connect()
while self.api.game_betinfo.isSuccessful == None:
if time.time()-start > 10:
logging.error(
'**error** get_betinfo time out need reconnect')
self.connect()
self.api.get_betinfo(id_number)
time.sleep(self.suspend*10)
if self.api.game_betinfo.isSuccessful == True:
return self.api.game_betinfo.isSuccessful, self.api.game_betinfo.dict
else:
return self.api.game_betinfo.isSuccessful, None
time.sleep(self.suspend*10)
def get_optioninfo(self, limit):
self.api.api_game_getoptions_result = None
self.api.get_options(limit)
while self.api.api_game_getoptions_result == None:
pass
return self.api.api_game_getoptions_result
def get_optioninfo_v2(self, limit):
self.api.get_options_v2_data = None
self.api.get_options_v2(limit, "binary,turbo")
while self.api.get_options_v2_data == None:
pass
return self.api.get_options_v2_data
# __________________________BUY__________________________
# __________________FOR OPTION____________________________
#thread safe
def buy_multi(self, price, ACTIVES, ACTION, expirations,polling=0.1):
req_id=[]
buy_len = len(price)
for i in range(buy_len):
req_id.append(global_value.get_req_id(self.api.object_id))
if len(price) == len(ACTIVES) == len(ACTION) == len(expirations):
for idx in range(buy_len):
self.api.buyv3(
price[idx], OP_code.ACTIVES[ACTIVES[idx]], ACTION[idx], expirations[idx], req_id[idx])
while True:
check_ok=True
for i in range(buy_len):
if req_id[i] not in self.api.buy_multi_option:
check_ok=False
if check_ok==True:
break
time.sleep(polling)
buy_id = []
for i in range(buy_len):
order_data=self.api.buy_multi_option[req_id[i]]
if "message" in order_data.keys():
buy_id.append(None)
else:
buy_id.append(order_data["id"])
return buy_id
else:
logging.error('buy_multi error please input all same len')
def get_remaning(self, duration,time=None):
if time==None:
time=self.api.timesync.server_timestamp
for remaning in get_remaning_time(time):
if remaning[0] == duration:
return remaning[1]
logging.error('get_remaning(self,duration) ERROR duration')
return "ERROR duration"
def buy_by_raw_expirations(self, price, active, direction, option, expired):
#thread safe
req_id = global_value.get_req_id(self.api.object_id)
try:
self.api.buy_multi_option[req_id] = None
except:
pass
if isinstance(active,int):
self.api.buyv3_by_raw_expired(price, active, direction, option, expired, request_id=req_id)
else:
self.api.buyv3_by_raw_expired(price, OP_code.ACTIVES[active], direction, option, expired, request_id=req_id)
while self.api.buy_multi_option[req_id] == None:
try:
if "message" in self.api.buy_multi_option[req_id].keys():
logging.error(
'**warning** buy'+str(self.api.buy_multi_option[req_id]["message"]))
return False, self.api.buy_multi_option[req_id]["message"]
except:
pass
time.sleep(self.suspend)
_order=self.api.buy_multi_option[req_id]
del self.api.buy_multi_option[req_id]
return True, _order
#thread safe