-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfunctions.py
3502 lines (3245 loc) · 127 KB
/
functions.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 re
import threading
import time
import tkinter as tk
from datetime import datetime, timedelta, timezone
from decimal import Decimal
from enum import Enum
from random import randint
from typing import Tuple, Union
from dotenv import dotenv_values
import display.bot_menu as bot_menu
import services as service
from api.api import WS
from api.setup import Markets
from api.variables import Variables
from botinit.variables import Variables as robo
from common.data import Bots, Instrument
from common.variables import Variables as var
from display.functions import info_display
from display.headers import Header
from display.messages import ErrorMessage, Message
from display.option_desk import options_desk
from display.variables import AutoScrollbar
from display.variables import OrderForm as form
from display.variables import (
RadioButtonFrame,
SubTreeviewTable,
TreeTable,
TreeviewTable,
)
from display.variables import Variables as disp
class SelectDatabase(str, Enum):
QWR = (
"select SYMBOL, TICKER, CATEGORY, EMI, POS, PNL, MARKET, TTIME from (select "
+ "EMI, SYMBOL, TICKER, CATEGORY, sum(QTY) POS, sum(SUMREAL) PNL, MARKET, "
+ "TTIME from {DATABASE_TABLE}"
+ " where SIDE <> 'Fund' group by EMI, SYMBOL, "
+ "MARKET) res where POS <> 0 order by SYMBOL desc;"
)
def __str__(self) -> str:
return self.value
class Function(WS, Variables):
sql_lock = threading.Lock()
def calculate(
self: Markets,
symbol: tuple,
price: float,
qty: float,
rate: float,
fund: int,
execFee: float = None,
) -> dict:
"""
Calculates trade or funding value and commission.
Parameters
----------
self: Markets
Market instance.
symbol: tuple
Instrument symbol in (symbol, market name) format, e.g.
("BTCUSD", "Bybit").
price: float
Price of the instrument.
qty: float
Quantity of the instrument, negative if sell.
rate: float
Comission or funding rate.
fund: int
1 - trade, 0 - funding is being calculated.
execFee: float (optional)
Some exchanges send the commission and funding already calculated
in the "execFee" field, so this value will be returned as
"commission" or "funding" value.
Returns
-------
dict
"sumreal" - trade value.
"commiss" - payed commission for trade, negative if maker rebate.
"funding: - funding value, negative if in favor of the trader.
"""
instrument = self.Instrument[symbol]
coef = instrument.valueOfOneContract * instrument.myMultiplier
if instrument.isInverse is True and "option" not in instrument.category:
sumreal = qty / price * fund
if execFee is not None:
commiss = execFee
funding = execFee
else:
commiss = abs(qty) / price * rate
funding = qty / price * rate
elif instrument.category in ["spot", "spot_linear"]:
sumreal = 0
if execFee is not None:
commiss = execFee
else:
commiss = abs(qty) * price * rate
funding = 0
else: # here the options are also calculated
sumreal = -qty * price * fund
if execFee is not None:
commiss = execFee
funding = execFee
else:
commiss = abs(qty) * price * rate
funding = qty * price * rate
return {
"sumreal": sumreal * coef,
"commiss": commiss * coef,
"funding": funding * coef,
}
def add_symbol(self: Markets, symb: str, ticker: str, category: str) -> None:
symbol = (symb, self.name)
if symbol not in self.Instrument.get_keys():
qwr = (
"select * from "
+ var.expired_table
+ " where SYMBOL ='"
+ symb
+ "' and MARKET = '"
+ self.name
+ "';"
)
data = service.select_database(qwr)
if not data:
WS.get_instrument(self, ticker=ticker, category=category)
service.add_symbol_database(
instrument=self.Instrument[symbol], table=var.expired_table
)
else:
data = data[0]
instrument = self.Instrument.add(symbol)
service.set_symbol(instrument=instrument, data=data)
def kline_data_filename(self: Markets, symbol: tuple, timefr: str) -> str:
return "data/" + symbol[0] + "_" + self.name + "_" + str(timefr) + ".txt"
def save_kline_data(self: Markets, row: dict, symbol: tuple, timefr: int) -> None:
filename = Function.kline_data_filename(self, symbol=symbol, timefr=timefr)
zero = (4 - len(str(row["time"]))) * "0"
data = (
str(row["date"])
+ ";"
+ str(zero)
+ str(row["time"])
+ ";"
+ str(row["open_bid"])
+ ";"
+ str(row["open_ask"])
+ ";"
+ str(row["hi"])
+ ";"
+ str(row["lo"])
+ ";"
+ str(round(self.Instrument[symbol].fundingRate, 6))
)
with open(filename, "a") as f:
f.write(data + "\n")
def noll(self: Markets, val: str, length: int) -> str:
r = ""
for _ in range(length - len(val)):
r = r + "0"
return r + val
def transaction(self: Markets, row: dict, info: str = "") -> None:
"""
Trades and funding processing
"""
def handle_trade_or_delivery(row, emi, refer, clientID):
results = self.Result[row["settlCurrency"]]
lastQty = row["lastQty"]
leavesQty = row["leavesQty"]
if row["side"] == "Sell":
lastQty = -row["lastQty"]
leavesQty = -row["leavesQty"]
calc = Function.calculate(
self,
symbol=row["symbol"],
price=row["lastPx"],
qty=lastQty,
rate=row["commission"],
fund=1,
execFee=row["execFee"],
)
if clientID == "Delivery":
calc["commiss"] = 0
instrument = self.Instrument[row["symbol"]]
instrument.volume += abs(lastQty)
instrument.sumreal += calc["sumreal"]
if emi in Bots.keys():
service.process_position(
bot=Bots[emi],
symbol=row["symbol"],
instrument=instrument,
user_id=Markets[instrument.market].user_id,
qty=lastQty,
calc=calc,
ttime=row["transactTime"],
)
results.commission += calc["commiss"]
results.sumreal += calc["sumreal"]
values = [
row["execID"],
emi,
refer,
row["settlCurrency"][0],
row["symbol"][0],
instrument.ticker,
row["category"],
self.name,
row["side"],
lastQty,
leavesQty,
row["price"],
0,
row["lastPx"],
calc["sumreal"],
calc["commiss"],
clientID,
row["transactTime"],
self.user_id,
]
service.insert_database(values=values, table=var.database_table)
message = {
"SYMBOL": row["symbol"],
"MARKET": row["market"],
"TTIME": row["transactTime"],
"SIDE": row["side"],
"TRADE_PRICE": row["lastPx"],
"QTY": abs(lastQty),
"EMI": emi,
"TICKER": instrument.ticker,
"CATEGORY": instrument.category,
}
if not info:
var.queue_info.put(
{
"trades_display": self,
"table": TreeTable.trades,
"message": message,
"emi": emi,
}
)
if emi in Bots.keys():
var.queue_info.put(
{
"trades_display": self,
"table": bot_menu.trade_treeTable[emi],
"message": message,
"emi": emi,
}
)
var.lock.acquire(True)
try:
Function.add_symbol(
self,
symb=row["symbol"][0],
ticker=row["ticker"],
category=row["category"],
)
instrument = self.Instrument[row["symbol"]]
if "price" not in row:
row["price"] = 0
# Trade
if row["execType"] == "Trade":
cl_id, emi = service.get_clOrdID(row=row)
refer = emi
if emi not in Bots.keys():
emi = ""
data = service.select_database( # read_database
"select EXECID from %s where EXECID='%s' and account=%s"
% (var.database_table, row["execID"], self.user_id),
)
if not data:
handle_trade_or_delivery(row, emi, refer, cl_id)
Function.orders_processing(self, row=row, info=info)
# Delivery
elif row["execType"] == "Delivery":
results = self.Result[row["settlCurrency"]]
pos = 0
if row["side"] == "Sell":
lastQty = -row["lastQty"]
elif row["side"] == "Buy":
lastQty = row["lastQty"]
else:
lastQty = 0
qwr = SelectDatabase.QWR.format(DATABASE_TABLE=var.database_table)
unclosed_positions = service.select_database(qwr)
for position in unclosed_positions:
symbol = (position["SYMBOL"], position["MARKET"])
if row["symbol"] == symbol and position["POS"] != 0:
pass
qty = position["POS"]
if qty > 0:
row["side"] = "Sell"
pos += qty
else:
row["side"] = "Buy"
pos += qty
row["lastQty"] = abs(qty)
handle_trade_or_delivery(row, position["EMI"], "", "Delivery")
diff = -(lastQty + pos)
if diff != 0:
qwr = (
"select sum(QTY) as sum from "
+ var.database_table
+ " where SYMBOL = '" # d emi
+ row["symbol"][0]
+ "' and MARKET = '"
+ self.name
+ "' and ACCOUNT = "
+ str(self.user_id)
+ " and side <> 'Fund'"
+ ";"
)
data = service.select_database(query=qwr)[0]
if data["sum"] != diff:
message = ErrorMessage.IMPOSSIBLE_DATABASE_POSITION.format(
SYMBOL=row["symbol"][0],
DELIVERY=diff,
MARKET=self.name,
POSITION=data["sum"],
)
_put_message(market=self.name, message=message, warning=True)
else:
emi = ""
if diff > 0:
row["side"] = "Sell"
else:
row["side"] = "Buy"
row["lastQty"] = abs(diff)
handle_trade_or_delivery(row, emi, "", "Delivery")
# Funding
elif row["execType"] == "Funding":
results = self.Result[row["settlCurrency"]]
message = {
"SYMBOL": row["symbol"],
"TTIME": row["transactTime"],
"PRICE": row["price"],
}
position = 0
instrument = self.Instrument[row["symbol"]]
calc = Function.calculate(
self,
symbol=row["symbol"],
price=row["lastPx"],
qty=row["lastQty"],
rate=row["commission"],
fund=0,
execFee=row["execFee"],
)
message["CATEGORY"] = row["category"]
message["MARKET"] = self.name
message["QTY"] = row["lastQty"]
message["COMMISS"] = calc["funding"]
message["TICKER"] = instrument.ticker
values = [
row["execID"],
"",
"",
row["settlCurrency"][0],
row["symbol"][0],
instrument.ticker,
row["category"],
self.name,
"Fund",
row["lastQty"],
0,
row["lastPx"],
0,
row["price"],
calc["sumreal"],
calc["funding"],
0,
row["transactTime"],
self.user_id,
]
service.insert_database(values=values, table=var.database_table)
results.funding += calc["funding"]
if not info:
var.queue_info.put({"funding_display": self, "message": message})
# New order
elif row["execType"] == "New":
cl_id, emi = service.get_clOrdID(row=row)
if cl_id == 0: # The order was placed outside Tmatic.
emi = service.set_emi(symbol=row["symbol"])
clOrdID = service.set_clOrdID()
service.fill_order(
emi=emi, clOrdID=clOrdID, category=row["category"], value=row
)
info = "Outside placement:"
else:
info = ""
Function.orders_processing(self, row=row, info=info)
# Canceled order
elif row["execType"] == "Canceled":
Function.orders_processing(self, row=row)
# Replaced order
elif row["execType"] == "Replaced":
Function.orders_processing(self, row=row)
finally:
var.lock.release()
def orders_processing(self: Markets, row: dict, info: str = "") -> None:
"""
Orders processing<--transaction()<--(trading_history() or get_exec())
This function is called from transaction(), which in turn is called
in two cases:
1) A new row from the websocket with the corresponding execType is
received:
<New> a new order has been successfully placed.
<Trade> the order has been executed, partially or completely.
<Canceled> the order has been cancelled.
<Replaced> the order has been moved to another price.
2) A row from trading history (info parameter is "History") is
received, and since trading history only informs about trades, there
is only one possible execType:
<Trade> the order has been executed, partially or completely.
All orders in var.orders are assigned clOrdID, therefore the task is
to find the required order and process it according to the execType.
However, the current row does not necessarily contain clOrdID, so the
possible scenarios are as follows:
1) The order was sent via Tmatic.
Websocket
clOrdID is always present if the row was received from the websocket
stream.
Trading history
clOrdID is always present for Bitmex and Bybit exchanges. Deribit
exchange sends clOrdID only for trades for the last 5 days. In case
of restoring the trading history for an earlier period, then the row
without clOrdID.
2) Order was not sent via Tmatic.
clOrdID is missing. The application searches for order in var.orders
by orderID. Failure does not always mean an error in case of
restoring trading history.
Parameters
----------
self: Markets
Market instance.
row: dict
Information received via web socket stream or downloaded trade
history.
info: str
Possibly "History" in case of trading history or other additional
information.
"""
def order_not_found(clOrdID: str) -> None:
message = (
"execType "
+ row["execType"]
+ " - order with clOrdID "
+ clOrdID
+ " not found."
)
_put_message(market=self.name, message=message, warning="warning")
cl_id, emi = service.get_clOrdID(row=row)
if cl_id != 0:
clOrdID = row["clOrdID"]
if emi == "":
emi = service.set_emi(symbol=row["symbol"])
else: # Retrieved from /execution or /execution/tradeHistory. The order
# was made outside Tmatic.
for emi, values in var.orders.items():
for clOrdID, value in values.items():
if value["orderID"] == row["orderID"]:
# emi and clOrdID were defined in var.orders
break
else:
continue
break
else:
"""There is no order with this orderID in the var.orders. The
order was not sent via Tmatic. Possibly retrieved from
Trading history"""
clOrdID = "Empty!"
emi = "Not_found!"
if "orderID" not in row:
"""Bitmex: orderID is missing when text='Closed to conform to lot
size'. The last time this happened was on 31.05.2021."""
row["orderID"] = row["text"]
price = row["price"]
info_q = ""
info_p = ""
order_message = ""
if row["execType"] == "Canceled":
order_message = "Order canceled " + row["symbol"][0]
info_p = price
info_q = row["orderQty"] - row["cumQty"]
if emi in var.orders and clOrdID in var.orders[emi]:
var.queue_order.put(
{"action": "delete", "clOrdID": clOrdID, "market": self.name}
)
del var.orders[emi][clOrdID]
else:
order_not_found(clOrdID=clOrdID)
else:
if row["execType"] == "New":
order_message = "New order " + row["symbol"][0]
if "clOrdID" in row and row["clOrdID"]:
service.fill_order(
emi=emi, clOrdID=clOrdID, category=row["category"], value=row
)
info_p = price
info_q = row["orderQty"]
elif row["execType"] == "Trade":
order_message = "Transaction " + row["symbol"][0]
info_p = row["lastPx"]
info_q = row["lastQty"]
if emi in var.orders and clOrdID in var.orders[emi]:
precision = self.Instrument[row["symbol"]].precision
var.orders[emi][clOrdID]["leavesQty"] -= row["lastQty"]
var.orders[emi][clOrdID]["leavesQty"] = round(
var.orders[emi][clOrdID]["leavesQty"], precision
)
if var.orders[emi][clOrdID]["leavesQty"] == 0:
del var.orders[emi][clOrdID]
if emi in Bots.keys():
if Bots[emi].multitrade:
if Bots[emi].state != "Disconnected":
t = threading.Thread(
target=service.call_bot_function,
args=(
robo.run_bot[emi],
emi,
),
)
t.start()
var.queue_order.put(
{"action": "delete", "clOrdID": clOrdID, "market": self.name}
)
else:
if info != "History":
order_not_found(clOrdID=clOrdID)
elif row["execType"] == "Replaced":
order_message = "Order replaced " + row["symbol"][0]
if emi in var.orders and clOrdID in var.orders[emi]:
var.orders[emi][clOrdID]["orderID"] = row["orderID"]
info_p = price
"""
"""
"""
Deribit does not have a leavesQty field, so in case of replace this
field is ignored. The ability to change the volume is not provided
by Tmatic. In case of Deribit the leavesQty field can be: 1) set
when a new order is received (execType = "New"), 2) the leavesQty
value can be reduced by the amount of the trade volume (execType =
"Trade").
"""
if not row["leavesQty"]:
info_q = var.orders[emi][clOrdID]["leavesQty"]
else:
info_q = row["leavesQty"]
var.orders[emi][clOrdID]["leavesQty"] = row["leavesQty"]
"""
"""
"""
"""
var.queue_order.put(
{"action": "delete", "clOrdID": clOrdID, "market": self.name}
)
else:
order_not_found(clOrdID=clOrdID)
if emi in var.orders and clOrdID in var.orders[emi]:
var.orders[emi][clOrdID]["price"] = price
var.orders[emi][clOrdID]["transactTime"] = row["transactTime"]
"""try:
t = clOrdID.split(".")
int(t[0])
emi = service.set_emi(symbol=t[1:3])
except ValueError:
emi = clOrdID"""
if info_q:
info_q = service.volume(self.Instrument[row["symbol"]], qty=info_q)
info_p = Function.format_price(self, number=info_p, symbol=row["symbol"])
if info != "History":
message = (
order_message
+ ", emi="
+ emi
+ ", side="
+ row["side"]
+ ", price="
+ str(info_p)
+ ", qty="
+ info_q
+ ", clOrdID="
+ clOrdID
)
var.queue_info.put(
{
"market": self.name,
"message": message,
"time": datetime.now(tz=timezone.utc),
"warning": None,
"emi": emi,
}
)
if info:
info += " - "
var.logger.info(
self.name
+ " - "
+ info
+ order_message
+ " - "
+ "side=%s, orderID=%s, clOrdID=%s, price=%s, qty=%s",
row["side"],
row["orderID"],
clOrdID,
str(info_p),
info_q,
)
if emi in var.orders and clOrdID in var.orders[emi]:
var.queue_order.put({"action": "put", "order": var.orders[emi][clOrdID]})
var.orders[emi].move_to_end(clOrdID)
disp.bot_orders_processing = True
def trades_display(
self: Markets, val: dict, table: TreeviewTable, init=False
) -> Union[None, list]:
"""
Update trades widget
"""
Function.add_symbol(
self,
symb=val["SYMBOL"][0],
ticker=val["TICKER"],
category=val["CATEGORY"],
)
tm = str(val["TTIME"])[2:]
tm = tm.replace("-", "")
tm = tm.replace("T", " ")[:15]
emi = val["EMI"]
if emi == "":
emi = var.DASH3
row = [
tm,
val["SYMBOL"][0],
val["CATEGORY"],
val["MARKET"],
val["SIDE"],
Function.format_price(
self,
number=float(val["TRADE_PRICE"]),
symbol=val["SYMBOL"],
),
service.volume(self.Instrument[val["SYMBOL"]], qty=val["QTY"]),
]
if table.name == "trades":
row.append(emi)
if init:
return row
table.insert(values=row, market=self.name, configure=val["SIDE"])
if "No trades" in table.children:
table.delete(iid="No trades")
def funding_display(self: Markets, val: dict, init=False) -> Union[None, list]:
"""
Update funding widget
"""
Function.add_symbol(
self,
symb=val["SYMBOL"][0],
ticker=val["TICKER"],
category=val["CATEGORY"],
)
tm = str(val["TTIME"])[2:]
tm = tm.replace("-", "")
tm = tm.replace("T", " ")[:15]
row = [
tm,
val["SYMBOL"][0],
val["CATEGORY"],
val["MARKET"],
Function.format_price(
self,
number=float(val["PRICE"]),
symbol=val["SYMBOL"],
),
"{:.7f}".format(-val["COMMISS"]),
service.volume(self.Instrument[val["SYMBOL"]], qty=val["QTY"]),
]
if init:
return row
configure = "Buy" if val["COMMISS"] <= 0 else "Sell"
TreeTable.funding.insert(values=row, market=self.name, configure=configure)
def orders_display(self: Markets, val: dict) -> None:
"""
Update Orders widget
"""
symb = val["emi"].split(".")[0]
if symb == val["symbol"][0]:
emi = var.DASH3
else:
emi = val["emi"]
tm = str(val["transactTime"])[2:]
tm = tm.replace("-", "")
tm = tm.replace("T", " ")[:15]
row = [
tm,
val["symbol"][0],
val["category"],
val["market"],
val["side"],
Function.format_price(
self,
number=val["price"],
symbol=val["symbol"],
),
service.volume(self.Instrument[val["symbol"]], qty=val["leavesQty"]),
emi,
]
clOrdID = val["clOrdID"]
if clOrdID in TreeTable.orders.children:
TreeTable.orders.delete(iid=clOrdID)
TreeTable.orders.insert(
values=row, market=self.name, iid=val["clOrdID"], configure=val["side"]
)
def format_price(self: Markets, number: Union[float, str], symbol: tuple) -> str:
try:
number = float(number)
except Exception:
return number
# if not isinstance(number, str):
precision = self.Instrument[symbol].price_precision
number = "{:.{precision}f}".format(number, precision=precision)
if precision:
dot = number.find(".")
if dot == -1:
number = number + "."
n = len(number) - 1 - number.find(".")
for _ in range(precision - n):
number = number + "0"
return number
def kline_update_market(self: Markets, utcnow: datetime) -> None:
"""
Processing timeframes.
"""
for symbol, kline in self.klines.items():
for timefr, values in kline.items():
timefr_minutes = var.timeframe_human_format[timefr]
if utcnow > values["time"] + timedelta(minutes=timefr_minutes):
instrument = self.Instrument[symbol]
bot_list = list()
for bot_name in values["robots"]:
bot = Bots[bot_name]
if bot.timefr == timefr:
if not bot.error_message:
if bot.state != "Disconnected":
bot_list.append(bot_name)
service.call_bot_function(
function=robo.update_bot[bot_name],
bot_name=bot_name,
)
run_bots(bot_list=bot_list)
Function.save_kline_data(
self,
row=values["data"][-1],
symbol=symbol,
timefr=timefr,
)
next_minute = int(utcnow.minute / timefr_minutes) * timefr_minutes
dt_now = utcnow.replace(minute=next_minute, second=0, microsecond=0)
try:
ask = instrument.asks[0][0]
except IndexError:
message = ErrorMessage.EMPTY_ORDERBOOK_DATA_KLINE.format(
SIDE="ask",
SYMBOL=symbol,
PRICE=values["data"][-1]["open_ask"],
)
_put_message(
market=instrument.market, message=message, warning=True
)
ask = values["data"][-1]["open_ask"]
try:
bid = instrument.bids[0][0]
except IndexError:
message = ErrorMessage.EMPTY_ORDERBOOK_DATA_KLINE.format(
SIDE="bid",
SYMBOL=symbol,
PRICE=values["data"][-1]["open_bid"],
)
_put_message(
market=instrument.market, message=message, warning=True
)
bid = values["data"][-1]["open_bid"]
values["data"].append(
{
"date": (utcnow.year - 2000) * 10000
+ utcnow.month * 100
+ utcnow.day,
"time": utcnow.hour * 100 + utcnow.minute,
"open_bid": bid,
"open_ask": ask,
"hi": ask,
"lo": bid,
"funding": instrument.fundingRate,
"datetime": dt_now,
}
)
values["time"] = dt_now
def refresh_on_screen(self: Markets, utc: datetime) -> None:
"""
Refresh information on screen
"""
# adaptive_screen(self)
if utc.hour != var.refresh_hour:
service.select_database("select count(*) cou from robots")
var.refresh_hour = utc.hour
var.logger.info("Emboldening SQLite")
current_time = time.gmtime()
if current_time.tm_sec != disp.last_gmtime_sec:
# We are here once a second
asctime = time.asctime(current_time)
disp.label_time["text"] = (
"CPU: "
+ str(service.Variables.cpu_usage)
+ "% MEM: "
+ str(service.Variables.memory_usage)
+ "MB | "
+ str(asctime[0 : len(asctime) - 4])
)
disp.last_gmtime_sec = current_time.tm_sec
Function.refresh_tables(self)
def display_instruments(self: Markets, indx=0):
tree = TreeTable.instrument
# d tm = datetime.now()
for market in var.market_list:
ws = Markets[market]
if market == var.current_market:
for symbol in ws.symbol_list:
instrument = ws.Instrument[symbol]
compare = [
symbol[0],
instrument.category,
instrument.currentQty,
instrument.avgEntryPrice,
instrument.unrealisedPnl,
instrument.marginCallPrice,
instrument.volume24h,
instrument.expire,
]
iid = f"{symbol[1]}!{symbol[0]}"
if iid in tree.children_hierarchical[market]:
if compare != tree.cache[iid]:
tree.cache[iid] = compare.copy()
tree.update_hierarchical(
parent=market,
iid=iid,
values=Function.format_instrument_line(
ws,
compare=compare,
instrument=instrument,
symbol=symbol,
),
)
else:
tree.insert_hierarchical(
parent=market,
iid=iid,
values=Function.format_instrument_line(
ws,
compare=compare,
instrument=instrument,
symbol=symbol,
),
indx=indx,
image=disp.image_cancel,
)
if var.rollup_symbol:
if var.rollup_symbol != "cancel":
TreeTable.instrument.on_rollup(iid=var.rollup_symbol, setup="child")
TreeTable.instrument.set_selection(var.rollup_symbol)
var.rollup_symbol = ""
# d print("___instrument", datetime.now() - tm)
def display_account(self: Markets):
tree = TreeTable.account
# d tm = datetime.now()
for market in var.market_list:
ws = Markets[market]
for settlCurrency in ws.Account.keys():
account = ws.Account[settlCurrency]
compare = [
settlCurrency[0],
account.walletBalance,
account.unrealisedPnl,
account.marginBalance,
account.orderMargin,
account.positionMagrin,
account.availableMargin,
]
iid = market + settlCurrency[0]
if iid in tree.children_hierarchical[market]:
if iid not in tree.cache:
tree.cache[iid] = []
if compare != tree.cache[iid]:
tree.cache[iid] = compare.copy()
tree.update_hierarchical(
parent=market, iid=iid, values=form_result_line(compare)
)
else:
tree.insert_hierarchical(
parent=market, iid=iid, values=form_result_line(compare)
)
# d print("___account", datetime.now() - tm)
def display_results(self: Markets):
tree = TreeTable.results
# d tm = datetime.now()
for market in var.market_list:
ws = Markets[market]
results = dict()
for symbol in ws.symbol_list:
instrument = ws.Instrument[symbol]
if "spot" not in instrument.category:
if instrument.ticker != "option!":
if instrument.currentQty != 0:
value = Function.close_value(
ws, symbol=symbol, pos=instrument.currentQty
)
currency = instrument.settlCurrency
if currency in results:
results[currency] += value
else:
results[currency] = value
for currency in ws.Result.keys():
result = ws.Result[currency]
result.result = 0
if currency in results:
result.result += results[currency]
compare = [
currency[0],
result.sumreal + result.result,
-result.commission,
-result.funding,
result.sumreal + result.result - result.commission - result.funding,
]
iid = market + currency[0]
Function.update_result_line(
self,
iid=iid,
compare=compare,
market=market,
tree=tree,
)
# d print("___result", datetime.now() - tm)
def display_positions(self: Markets):
tree = TreeTable.position
# d tm = datetime.now()
pos_by_market = {market: [] for market in var.market_list}
for name in Bots.keys():
bot = Bots[name]
for symbol in bot.bot_positions.keys():
pos_by_market[symbol[1]].append(bot.bot_positions[symbol])