-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtradingDefs.py
1446 lines (1144 loc) · 56.4 KB
/
tradingDefs.py
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
import json
import socket
import logging
import time
import ssl
from threading import Thread
import os
from datetime import datetime
from datetime import timedelta
from pprint import pprint
import math
import requests
import eventlet
from copy import deepcopy
from collections import Counter
os.chdir(os.path.dirname(__file__))
# set to true on debug environment only
DEBUG = True
# default connection properites
DEFAULT_XAPI_ADDRESS = 'xapi.xtb.com'
DEFAULT_XAPI_PORT = 5124
DEFUALT_XAPI_STREAMING_PORT = 5125
# API inter-command timeout (in ms)
API_SEND_TIMEOUT = 500
# max connection tries
API_MAX_CONN_TRIES = 4
# logger properties
logger = logging.getLogger("jsonSocket")
FORMAT = '[%(asctime)-15s][%(funcName)s:%(lineno)d] %(message)s'
logging.basicConfig(format=FORMAT, level=logging.DEBUG,
filename='error_logs.log')
if DEBUG:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.CRITICAL)
def reverse_dict(dictionary):
reversed_keys = reversed(list(dictionary.keys()))
return {key: dictionary[key]
for key in reversed_keys
}
def truncate(number, digits) -> float:
stepper = 10.0 ** digits
return math.trunc(stepper * number) / stepper
class TransactionSide(object):
BUY = 0
SELL = 1
BUY_LIMIT = 2
SELL_LIMIT = 3
BUY_STOP = 4
SELL_STOP = 5
class TransactionType(object):
ORDER_OPEN = 0
ORDER_CLOSE = 2
ORDER_MODIFY = 3
ORDER_DELETE = 4
class JsonSocket(object):
def __init__(self, address, port, encrypt=False):
self._ssl = encrypt
if self._ssl != True:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket = ssl.wrap_socket(sock)
self.conn = self.socket
self._timeout = None
self._address = address
self._port = port
self._decoder = json.JSONDecoder()
self._receivedData = ''
def connect(self):
for _ in range(API_MAX_CONN_TRIES):
try:
self.socket.connect((self.address, self.port))
self.socket.settimeout(6)
except socket.error as msg:
logger.error("SockThread Error: %s" % msg)
time.sleep(1)
continue
# logger.info("Socket connected")
return True
return False
def _sendObj(self, obj):
msg = json.dumps(obj)
self._waitingSend(msg)
def _waitingSend(self, msg):
if self.socket:
sent = 0
msg = msg.encode('utf-8')
while sent < len(msg):
sent += self.conn.send(msg[sent:])
# logger.info('Sent: ' + str(msg))
time.sleep(API_SEND_TIMEOUT/1000)
def _read(self, bytesSize=4096):
if not self.socket:
raise RuntimeError("socket connection broken")
while True:
char = self.conn.recv(bytesSize).decode()
self._receivedData += char
try:
(resp, size) = self._decoder.raw_decode(self._receivedData)
if size == len(self._receivedData):
self._receivedData = ''
break
elif size < len(self._receivedData):
self._receivedData = self._receivedData[size:].strip()
break
except ValueError as e:
continue
# logger.info('Received: ' + str(resp))
return resp
def _readObj(self):
msg = self._read()
return msg
def close(self):
# logger.debug("Closing socket")
self._closeSocket()
if self.socket is not self.conn:
# logger.debug("Closing connection socket")
self._closeConnection()
def _closeSocket(self):
self.socket.close()
def _closeConnection(self):
self.conn.close()
def _get_timeout(self):
return self._timeout
def _set_timeout(self, timeout):
self._timeout = timeout
self.socket.settimeout(timeout)
def _get_address(self):
return self._address
def _set_address(self, address):
pass
def _get_port(self):
return self._port
def _set_port(self, port):
pass
def _get_encrypt(self):
return self._ssl
def _set_encrypt(self, encrypt):
pass
timeout = property(_get_timeout, _set_timeout,
doc='Get/set the socket timeout')
address = property(_get_address, _set_address,
doc='read only property socket address')
port = property(_get_port, _set_port, doc='read only property socket port')
encrypt = property(_get_encrypt, _set_encrypt,
doc='read only property socket port')
class APIClient(JsonSocket):
def __init__(self, address=DEFAULT_XAPI_ADDRESS, port=DEFAULT_XAPI_PORT, encrypt=True):
super(APIClient, self).__init__(address, port, encrypt)
if(not self.connect()):
raise Exception("Cannot connect to " + address + ":" +
str(port) + " after " + str(API_MAX_CONN_TRIES) + " retries")
def execute(self, dictionary):
self._sendObj(dictionary)
return self._readObj()
def disconnect(self):
self.close()
def commandExecute(self, commandName, arguments=None):
return self.execute(baseCommand(commandName, arguments))
class APIStreamClient(JsonSocket):
def __init__(self, address=DEFAULT_XAPI_ADDRESS, port=DEFUALT_XAPI_STREAMING_PORT, encrypt=True, ssId=None,
tickFun=None, tradeFun=None, balanceFun=None, tradeStatusFun=None, profitFun=None, newsFun=None):
super(APIStreamClient, self).__init__(address, port, encrypt)
self._ssId = ssId
self._tickFun = tickFun
self._tradeFun = tradeFun
self._balanceFun = balanceFun
self._tradeStatusFun = tradeStatusFun
self._profitFun = profitFun
self._newsFun = newsFun
if(not self.connect()):
raise Exception("Cannot connect to streaming on " + address + ":" +
str(port) + " after " + str(API_MAX_CONN_TRIES) + " retries")
self._running = True
self._t = Thread(target=self._readStream, args=())
self._t.setDaemon(True)
self._t.start()
def _readStream(self):
while (self._running):
msg = self._readObj()
# logger.info("Stream received: " + str(msg))
if (msg["command"] == 'tickPrices'):
self._tickFun(msg)
elif (msg["command"] == 'trade'):
self._tradeFun(msg)
elif (msg["command"] == "balance"):
self._balanceFun(msg)
elif (msg["command"] == "tradeStatus"):
self._tradeStatusFun(msg)
elif (msg["command"] == "profit"):
self._profitFun(msg)
elif (msg["command"] == "news"):
self._newsFun(msg)
def disconnect(self):
self._running = False
self._t.join()
self.close()
def execute(self, dictionary):
self._sendObj(dictionary)
def subscribePrice(self, symbol):
self.execute(dict(command='getTickPrices',
symbol=symbol, streamSessionId=self._ssId))
def subscribePrices(self, symbols):
for symbolX in symbols:
self.subscribePrice(symbolX)
def subscribeTrades(self):
self.execute(dict(command='getTrades', streamSessionId=self._ssId))
def subscribeBalance(self):
self.execute(dict(command='getBalance', streamSessionId=self._ssId))
def subscribeTradeStatus(self):
self.execute(dict(command='getTradeStatus',
streamSessionId=self._ssId))
def subscribeProfits(self):
self.execute(dict(command='getProfits', streamSessionId=self._ssId))
def subscribeNews(self):
self.execute(dict(command='getNews', streamSessionId=self._ssId))
def unsubscribePrice(self, symbol):
self.execute(dict(command='stopTickPrices',
symbol=symbol, streamSessionId=self._ssId))
def unsubscribePrices(self, symbols):
for symbolX in symbols:
self.unsubscribePrice(symbolX)
def unsubscribeTrades(self):
self.execute(dict(command='stopTrades', streamSessionId=self._ssId))
def unsubscribeBalance(self):
self.execute(dict(command='stopBalance', streamSessionId=self._ssId))
def unsubscribeTradeStatus(self):
self.execute(dict(command='stopTradeStatus',
streamSessionId=self._ssId))
def unsubscribeProfits(self):
self.execute(dict(command='stopProfits', streamSessionId=self._ssId))
def unsubscribeNews(self):
self.execute(dict(command='stopNews', streamSessionId=self._ssId))
# Command templates
def baseCommand(commandName, arguments=None):
if arguments == None:
arguments = dict()
return dict([('command', commandName), ('arguments', arguments)])
def loginCommand(userId, password, appName=''):
return baseCommand('login', dict(userId=userId, password=password, appName=appName))
# example function for processing ticks from Streaming socket
def procTickExample(msg):
print("TICK: ", msg)
# example function for processing trades from Streaming socket
def procTradeExample(msg):
print("TRADE: ", msg)
# example function for processing trades from Streaming socket
def procBalanceExample(msg):
print("BALANCE: ", msg)
# example function for processing trades from Streaming socket
def procTradeStatusExample(msg):
print("TRADE STATUS: ", msg)
# example function for processing trades from Streaming socket
def procProfitExample(msg):
print("PROFIT: ", msg)
# example function for processing news from Streaming socket
def procNewsExample(msg):
print("NEWS: ", msg)
# ---------------------------------------------------------------------
def save_actual_calendar_json(client):
calendarFromApi = client.commandExecute('getCalendar')
argument = {
"symbol": "EURPLN"
}
fullCalendar = []
index = 0
for entryDict in calendarFromApi["returnData"]:
if entryDict["impact"] == "3" or entryDict["impact"] == "2":
fullCalendar.append(entryDict)
fullCalendar[index]["time"] = str(datetime.fromtimestamp(
entryDict["time"] / 1000))
index += 1
with open("fullCalendar.json", "w", encoding="UTF-8-sig") as fileJson:
json.dump(fullCalendar, fileJson, ensure_ascii=False, indent=4)
def get_important_calendar_events_dict(client, importantCountriesList):
calendarFromApi = client.commandExecute('getCalendar')
fullCalendar = []
index = 0
for entryDict in calendarFromApi["returnData"]:
if (entryDict["country"] in importantCountriesList) and (entryDict["impact"] == "3" or entryDict["impact"] == "2"):
fullCalendar.append(entryDict)
fullCalendar[index]["time"] = str(datetime.fromtimestamp(
entryDict["time"] / 1000))
index += 1
return fullCalendar
class Calendar:
def __init__(self, client, importantCurrencies):
self.importantCurrencies = importantCurrencies
self.fullOnlyImportantCalendar = Calendar.get_important_calendar_events_dict(
self, client)
onlyAnnouncementsTimes = [event["time"].split(" ")[1]
for event in self.fullOnlyImportantCalendar
]
self.onlyAnnouncementsTimesSorted = sorted(
list(set(onlyAnnouncementsTimes)), reverse=True)
self.currentTitlesDict = {event["title"]: ""
for event in self.fullOnlyImportantCalendar
}
def get_important_calendar_events_dict(self, client):
calendarFromApi = client.commandExecute('getCalendar')
with open("countriesCurrencies.json", "r", encoding="UTF-8-sig") as countriesCurrencies:
countriesCurrencies = json.load(countriesCurrencies)
importantCountriesList = [country
for country in countriesCurrencies
if countriesCurrencies[country] in self.importantCurrencies
]
# get today and tommorow timestamps
timeDiff = timedelta(hours=3)
startTime = (
datetime.now() - timeDiff).strftime("%Y-%m-%d %H:%M:%S")
# tymczasowo, żeby cokolwiek było w kalendarzu
# startTime = str(datetime.today().date()) + " 00:00:00"
dateDiff = timedelta(days=1)
endTime = str((datetime.now() + dateDiff).date()) + " 23:59:59"
self.startDateTimestamp = int(datetime.timestamp(
datetime.strptime(startTime, '%Y-%m-%d %H:%M:%S')))*1000
self.endDateTimestamp = int(datetime.timestamp(
datetime.strptime(endTime, '%Y-%m-%d %H:%M:%S')))*1000
# get only important events from today calendar
fullCalendar = []
index = 0
for entryDict in calendarFromApi["returnData"]:
if (entryDict["country"] in importantCountriesList) and \
(entryDict["time"] >= self.startDateTimestamp) and \
(entryDict["time"] < self.endDateTimestamp) and \
(entryDict["impact"] == "3" or entryDict["impact"] == "2"):
fullCalendar.append(entryDict)
fullCalendar[index]["time"] = str(datetime.fromtimestamp(
entryDict["time"] / 1000))
index += 1
if entryDict["forecast"] == "":
entryDict["forecast"] = entryDict["previous"]
return fullCalendar
def save_actual_calendar_json(self):
with open("fullCalendar2.json", "w", encoding="UTF-8-sig") as fileJson:
json.dump(self.fullOnlyImportantCalendar,
fileJson, ensure_ascii=False, indent=4)
class FileSupport:
@staticmethod
def read_file(name):
with open(name + ".json", "r", encoding="UTF-8-sig") as jsonFile:
return json.load(jsonFile)
@staticmethod
def save_file(name, dictionary, directory=""):
with open(directory + name + ".json", "w", encoding="UTF-8-sig") as jsonFile:
json.dump(dictionary, jsonFile, ensure_ascii=False, indent=4)
class BullsAndBears:
def __init__(self, calendarFromApi):
self.importantWithCurrentValue = [event
for event in calendarFromApi.fullOnlyImportantCalendar
if event["current"] != ""
]
titlesDictionaryDirections = FileSupport.read_file(
"titlesDictionaryDirections")
# check for new titles
newTitlesDict = {title: "Update Needed"
for title in calendarFromApi.currentTitlesDict
if title not in titlesDictionaryDirections
}
FileSupport.save_file("newTitles", newTitlesDict)
# merge new titles with older file, save json
updatedTitlesDirections = {
**titlesDictionaryDirections, **newTitlesDict}
FileSupport.save_file("titlesDictionaryDirections",
updatedTitlesDirections)
titlesDictionaryDirections = updatedTitlesDirections
countriesCurrencies = FileSupport.read_file("countriesCurrencies")
self.bullsCurrencies = [countriesCurrencies[eventWithCurrent["country"]]
for eventWithCurrent in self.importantWithCurrentValue
if (titlesDictionaryDirections[eventWithCurrent["title"]] == "Better Up" and
(float(eventWithCurrent["current"]) - BullsAndBears.change_to_zeros(self, eventWithCurrent["forecast"]) > 0)) or
(titlesDictionaryDirections[eventWithCurrent["title"]] == "Better Down" and
(float(eventWithCurrent["current"]) - BullsAndBears.change_to_zeros(self, eventWithCurrent["forecast"]) < 0)) or
BullsAndBears.check_minimum_value_bull(
self, eventWithCurrent["title"], eventWithCurrent["current"])
]
self.bearsCurrencies = [countriesCurrencies[eventWithCurrent["country"]]
for eventWithCurrent in self.importantWithCurrentValue
if (titlesDictionaryDirections[eventWithCurrent["title"]] == "Better Up" and
(float(eventWithCurrent["current"]) - BullsAndBears.change_to_zeros(self, eventWithCurrent["forecast"]) < 0)) or
(titlesDictionaryDirections[eventWithCurrent["title"]] == "Better Down" and
(float(eventWithCurrent["current"]) - BullsAndBears.change_to_zeros(self, eventWithCurrent["forecast"]) > 0)) or
BullsAndBears.check_minimum_value_bear(
self, eventWithCurrent["title"], eventWithCurrent["current"])
]
self.bearCurrenciesUnique = [currency
for currency in list(set(self.bearsCurrencies))
if currency not in list(set(self.bullsCurrencies))
]
self.bullCurrenciesUnique = [currency
for currency in list(set(self.bullsCurrencies))
if currency not in list(set(self.bearsCurrencies))
]
@staticmethod
def change_trades_order(semiTrades, fullTrades, withoutCurrent):
finalOrderTrades = {}
orderAfterSemi = {}
orderAfterFull = {}
if len(list(semiTrades.keys())) > 0:
for pair in reverse_dict(semiTrades):
if pair in withoutCurrent:
orderAfterSemi[pair] = withoutCurrent[pair]
if len(list(fullTrades.keys())) > 0:
for pair in reverse_dict(fullTrades):
if pair in withoutCurrent:
orderAfterFull[pair] = withoutCurrent[pair]
finalOrderTrades = {**orderAfterFull, **orderAfterSemi}
for pair in withoutCurrent:
if pair not in finalOrderTrades:
finalOrderTrades[pair] = withoutCurrent[pair]
return finalOrderTrades
def change_to_zeros(self, string):
if string == "":
return 0
else:
return float(string)
def check_minimum_value_bull(self, key, comparedValue):
with open("titlesDictionaryMinimums.json", "r", encoding="UTF-8-sig") as jsonFile:
titlesDictionaryMinimums = json.load(jsonFile)
try:
if float(titlesDictionaryMinimums[key]) < float(comparedValue):
return True
except:
return False
def check_minimum_value_bear(self, key, comparedValue):
with open("titlesDictionaryMinimums.json", "r", encoding="UTF-8-sig") as jsonFile:
titlesDictionaryMinimums = json.load(jsonFile)
try:
if float(titlesDictionaryMinimums[key]) > float(comparedValue):
return True
except:
return False
def get_possible_trades_both_lists(self, possibleCurrencyPairs):
allCombinations = []
listToMakeCombinations = self.bearCurrenciesUnique + \
self.bullCurrenciesUnique
for currency in listToMakeCombinations:
for currencyIndex in range(len(listToMakeCombinations)):
currentCombination = str(currency) + \
str(listToMakeCombinations[currencyIndex])
if currentCombination in possibleCurrencyPairs:
allCombinations.append(currentCombination)
possibleFullTrades = list(set(allCombinations))
# nadanie kierunku trejdom na podstawie kalendarza
return BullsAndBears.get_trade_directions_for_pairs(self, possibleFullTrades)
def get_semi_possible_trades(self, possibleCurrencyPairs, importantCurrencies):
allCombinations = []
listToMakeCombinations = self.bearCurrenciesUnique + \
self.bullCurrenciesUnique
for possibleCurrency in listToMakeCombinations:
for currency in importantCurrencies:
currentCombination = str(possibleCurrency) + str(currency)
if (currentCombination in possibleCurrencyPairs) and (possibleCurrency in currentCombination):
allCombinations.append(currentCombination)
alternativeCombination = str(currency) + str(possibleCurrency)
if (alternativeCombination in possibleCurrencyPairs) and (possibleCurrency in alternativeCombination):
allCombinations.append(alternativeCombination)
possibleSemiTrades = list(set(allCombinations))
# nadanie kierunku trejdom na podstawie kalendarza
return BullsAndBears.get_trade_directions_for_pairs(self, possibleSemiTrades)
@staticmethod
def get_possible_pairs_from_currencies_list(currenciesList, possibleCurrencyPairs, importantCurrencies):
allCombinations = []
listToMakeCombinations = currenciesList
for possibleCurrency in listToMakeCombinations:
for currency in importantCurrencies:
currentCombination = str(possibleCurrency) + str(currency)
if (currentCombination in possibleCurrencyPairs) and (possibleCurrency in currentCombination):
allCombinations.append(currentCombination)
alternativeCombination = str(currency) + str(possibleCurrency)
if (alternativeCombination in possibleCurrencyPairs) and (possibleCurrency in alternativeCombination):
allCombinations.append(alternativeCombination)
uniquePairs = []
for pair in allCombinations:
if pair not in uniquePairs:
uniquePairs.append(pair)
return uniquePairs
def get_unique_currency_pairs(self, pairsList):
if len(list(pairsList.keys())) > 1:
firstCurrenciesFromPairs = []
secondCurrenciesFromPairs = []
finalPairs = {}
for pair in pairsList:
firstCurrenciesFromPairs.append(pair[0:3])
secondCurrenciesFromPairs.append(pair[3:6])
allCurencies = firstCurrenciesFromPairs + secondCurrenciesFromPairs
matchesDict = dict(Counter(allCurencies))
if max(list(matchesDict.values())) < 2:
finalPairs[pair] = pairsList[pair]
else:
firstCurrenciesFromPairs.pop()
secondCurrenciesFromPairs.pop()
allCurencies = firstCurrenciesFromPairs + secondCurrenciesFromPairs
return finalPairs
else:
return pairsList
def get_trade_directions_for_pairs(self, pairsList):
if self.bullCurrenciesUnique == [] and \
self.bearCurrenciesUnique == []:
bothDict = {pair: "both"
for pair in pairsList
}
return bothDict
else:
# sprawdzenie listy bull
bullDict = {}
for pair in pairsList:
for bullCurrency in self.bullCurrenciesUnique:
if pair[3:6] in self.bullCurrenciesUnique and \
pair[0:3] in self.bullCurrenciesUnique:
pass
elif pair[3:6] == bullCurrency:
bullDict[pair] = "sell"
elif pair[0:3] == bullCurrency:
bullDict[pair] = "buy"
elif pair[3:6] not in self.bearCurrenciesUnique and \
pair[0:3] not in self.bearCurrenciesUnique and \
pair[3:6] not in self.bullCurrenciesUnique and \
pair[0:3] not in self.bullCurrenciesUnique:
bullDict[pair] = "both"
# sprawdzenie listy bear
bearDict = {}
for pair in pairsList:
for bearCurrency in self.bearCurrenciesUnique:
if pair[3:6] in self.bearCurrenciesUnique and \
pair[0:3] in self.bearCurrenciesUnique:
pass
elif pair[3:6] == bearCurrency:
bearDict[pair] = "buy"
elif pair[0:3] == bearCurrency:
bearDict[pair] = "sell"
elif pair[3:6] not in self.bearCurrenciesUnique and \
pair[0:3] not in self.bearCurrenciesUnique and \
pair[3:6] not in self.bullCurrenciesUnique and \
pair[0:3] not in self.bullCurrenciesUnique:
bearDict[pair] = "both"
return {**bullDict, **bearDict}
@staticmethod
def split_pairs_to_currencies(pairsList):
firstCurrenciesFromPairs = [pair[0:3]
for pair in pairsList
]
secondCurrenciesFromPairs = [pair[3:6]
for pair in pairsList
]
allCurrencies = list(firstCurrenciesFromPairs +
secondCurrenciesFromPairs)
uniqueCurrencies = []
for currency in allCurrencies:
if currency not in uniqueCurrencies:
uniqueCurrencies.append(currency)
return uniqueCurrencies
class Chart:
def __init__(self, client, pair, timeFrame, startTime=None):
timeFrames = {"day": 1440, "fourhour": 240,
"hour": 60, "halfhour": 30, "quater": 15}
chosenTimeFrame = timeFrames[timeFrame]
if startTime == None:
timeDiff = timedelta(days=19)
startTimeChart = str(
datetime.today().date() - timeDiff) + " 00:00:00"
else:
startTimeChart = startTime
endTimeChart = str(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
# daty start/koniec w formacie timestamp
startDateTimestampChart = int(datetime.timestamp(
datetime.strptime(startTimeChart, '%Y-%m-%d %H:%M:%S')))*1000
endDateTimestampChart = int(datetime.timestamp(
datetime.strptime(endTimeChart, '%Y-%m-%d %H:%M:%S')))*1000
chart_info = {
"start": startDateTimestampChart,
"end": endDateTimestampChart,
"period": chosenTimeFrame,
"symbol": pair,
"ticks": 0
}
argument = {
"info": chart_info
}
chartListDays = client.commandExecute(
"getChartRangeRequest", argument)["returnData"]["rateInfos"]
numberOfDigits = {"EURUSD": 5, "USDJPY": 3, "GBPUSD": 5, "AUDUSD": 5,
"USDCAD": 5, "EURJPY": 3, "EURGBP": 5, "GBPJPY": 3,
"AUDJPY": 3, "AUDCAD": 5, "CADJPY": 3}
for note in chartListDays:
note["high"] = (float(note["open"]) +
float(note["high"])) / 10 ** numberOfDigits[pair]
note["low"] = (float(note["open"]) +
float(note["low"])) / 10 ** numberOfDigits[pair]
note["close"] = (float(note["open"]) +
float(note["close"])) / 10 ** numberOfDigits[pair]
note["open"] = float(note["open"]) / 10 ** numberOfDigits[pair]
time.sleep(2)
self.chartReady = chartListDays
class Resistance:
def __init__(self, client, pair, timeFrame, startTime=None):
daysOfWeek = {0: "mon", 1: "tue", 2: "wed",
3: "thu", 4: "fri", 5: "sat", 6: "sun"}
chart = Chart(client, pair, timeFrame, startTime=startTime)
if startTime == None:
chartListDays = chart.chartReady
else:
chartListDays = chart.chartReady # [:-1]
for note in chartListDays:
note["ctm"] = daysOfWeek[datetime.fromtimestamp(
note["ctm"] / 1000).weekday()]
amountOfWeeks = 3
allCloses = []
currentCloses = []
mondayNo = 0
if startTime == None:
for note in list(reversed(chartListDays)):
currentCloses.append(note["close"])
if note["ctm"] == "sun":
mondayNo += 1
allCloses.append(max(currentCloses))
currentCloses = []
if mondayNo == amountOfWeeks:
break
else:
for note in list(reversed(chartListDays)):
currentCloses.append(note["close"])
allCloses = max(currentCloses)
self.allCloses = allCloses
class Support:
def __init__(self, client, pair, timeFrame, startTime=None):
daysOfWeek = {0: "mon", 1: "tue", 2: "wed",
3: "thu", 4: "fri", 5: "sat", 6: "sun"}
chart = Chart(client, pair, timeFrame, startTime=startTime)
if startTime == None:
chartListDays = chart.chartReady
else:
chartListDays = chart.chartReady # [:-1]
for note in chartListDays:
note["ctm"] = daysOfWeek[datetime.fromtimestamp(
note["ctm"] / 1000).weekday()]
amountOfWeeks = 3
allCloses = []
currentCloses = []
mondayNo = 0
if startTime == None:
for note in list(reversed(chartListDays)):
currentCloses.append(note["close"])
if note["ctm"] == "sun":
mondayNo += 1
allCloses.append(min(currentCloses))
currentCloses = []
if mondayNo == amountOfWeeks:
break
else:
for note in list(reversed(chartListDays)):
currentCloses.append(note["close"])
allCloses = min(currentCloses)
self.allCloses = allCloses
class SlowStoch:
def __init__(self, client, possibleTradesDict, timeFrame):
possibleTradesSlowStoch = {}
self.averageHighLowsPerPair = {}
for pair in possibleTradesDict:
chart = Chart(client, pair, timeFrame)
time.sleep(1)
chartListDays = chart.chartReady
# slow stoch
k = 25 # z ilu ma dni być liczony stoch
ps = 15 # zwalnianie stocha
currentK = 0
lowsSlow = []
highsSlow = []
closeSlow = []
pairsHighLows = []
for note in list(reversed(chartListDays)):
lowsSlow.append(note["low"])
highsSlow.append(note["high"])
closeSlow.append(note["close"])
pairsHighLows.append(note["high"] - note["low"])
currentK += 1
if currentK == k + ps - 1:
break
pairsHighLowsAverage = round(
sum(pairsHighLows) / len(pairsHighLows), 5)
self.averageHighLowsPerPair[pair] = pairsHighLowsAverage
stochUp = []
stochDown = []
index = 0
for index in range(ps):
stochUp.append(
100 * (closeSlow[index] - min(lowsSlow[index: index + k])))
stochDown.append(
max(highsSlow[index: index + k]) - min(lowsSlow[index: index + k]))
possibleTradesSlowStoch[pair] = round(
sum(stochUp) / sum(stochDown), 2)
self.possibleTradesSlowStoch = possibleTradesSlowStoch
@staticmethod
def get_possible_trades_from_stoch(possibleCurrencyPairs, fourHourSS, oneHourSS, halfHourSS, quaterSS):
possibleBuysStoch = {pair: "buy"
for pair in possibleCurrencyPairs
if quaterSS[pair] <= 20 and
fourHourSS[pair] < 50 and
(halfHourSS[pair] <= 20 or
oneHourSS[pair] <= 20)
}
possibleSellsdStoch = {pair: "sell"
for pair in possibleCurrencyPairs
if quaterSS[pair] >= 80 and
fourHourSS[pair] > 50 and
(halfHourSS[pair] >= 80 or
oneHourSS[pair] >= 80)
}
return {**possibleBuysStoch, **possibleSellsdStoch}
class MoneyManagement:
def __init__(self, client):
accountData = client.commandExecute("getMarginLevel")["returnData"]
self.balance = accountData["balance"]
self.margin = accountData["margin"]
self.equity = accountData["equity"]
self.marginFree = accountData["margin_free"]
self.marginLevel = accountData["margin_level"]
def count_volumes(self, resistanceDict, supportDict, possibleTradesWithAllOk):
pass
class CurrentTrades:
def __init__(self, client):
tradesDirections = {0: "buy", 1: "sell"}
arguments = {
"openedOnly": True
}
self.openedTradesFullInfo = client.commandExecute(
"getTrades", arguments)["returnData"]
self.openedTradesOnlyPairs = {trade["symbol"]: tradesDirections[trade["cmd"]]
for trade in self.openedTradesFullInfo
}
self.openedTradesOpeningPrices = {trade["symbol"]: trade["open_price"]
for trade in self.openedTradesFullInfo
}
self.openedTradesVolumes = {trade["symbol"]: trade["volume"]
for trade in self.openedTradesFullInfo
}
self.openedTradesOrdersNo = {trade["symbol"]: trade["order"]
for trade in self.openedTradesFullInfo
}
self.openedTradesStopLoss = {trade["symbol"]: trade["sl"]
for trade in self.openedTradesFullInfo
}
self.openedTradesTakeProfit = {trade["symbol"]: trade["tp"]
for trade in self.openedTradesFullInfo
}
self.openedTradesResults = {trade["symbol"]: trade["profit"]
for trade in self.openedTradesFullInfo
}
self.openedTradesOpenTimes = {trade["symbol"]: trade["open_time"]
for trade in self.openedTradesFullInfo
}
def check_current_trades_get_unique(self, possibleTradesDict):
currentTradesCurrencies = BullsAndBears.split_pairs_to_currencies(
list(self.openedTradesOnlyPairs.keys()))
toRemove = []
for pair in possibleTradesDict:
if pair[0:3] in currentTradesCurrencies or \
pair[3:6] in currentTradesCurrencies:
toRemove.append(pair)
possibleTradesDict = {pair: possibleTradesDict[pair]
for pair in possibleTradesDict
if pair not in toRemove
}
return possibleTradesDict
def close_trades(self, client, tradesToClose):
for pair in tradesToClose:
Trade(client, self.openedTradesOnlyPairs[pair], "close", pair,
self.openedTradesVolumes[pair], self.openedTradesOpeningPrices[pair],
order=self.openedTradesOrdersNo[pair])
class Trade:
def __init__(self, client, buyORsell, openORclose, pair,
volume, price=1, stopLoss=None, takeProfit=None,
order=None):
cmdField = {
"buy": 0,
"sell": 1,
"buylimit": 2,
"selllimit": 3,
"buystop": 4,