-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
8395 lines (7258 loc) · 542 KB
/
app.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
from flask import Flask, render_template, request, jsonify, redirect
from flask import session as s_mgt
import psycopg2 # on ubuntu, sudo apt-get install libpq-dev, sudo pip install psycopg2/sudo pip install psycopg2-binary
from binance.client import Client
from datetime import datetime
from decimal import Decimal
import json
import math
import ast
import requests
from psycopg2 import sql
import time
import threading
import decimal
import pybit.spot
import pybit.usdt_perpetual
import pytz
app = Flask(__name__)
app.secret_key = "Notofomo'sdash"
api_key = ""
api_secret = ""
dash_user_name = "pick_a_username"
dash_password = "pick_a_password"
colors = [
"#F7464A", "#46BFBD", "#FDB45C", "#FEDCBA",
"#ABCDEF", "#DDDDDD", "#ABCABC", "#4169E1",
"#C71585", "#FF4500", "#FEDCBA", "#46BFBD"]
#establishing the connection
conn = psycopg2.connect(
database="gpu", user='postgres', password='postgres', host='127.0.0.1', port= '5432')
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Executing an MYSQL function using the execute() method
cursor.execute("select version()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)
cursor.execute("ALTER DATABASE gpu SET timezone TO 'Europe/Berlin';")
conn.commit()
client = Client(api_key, api_secret)
try:
cursor.execute("select api_key from binance_keys")
r_2 = cursor.fetchall()
binance_api_key = r_2[0][0]
except:
binance_api_key = "Enter Api Key"
cursor.execute("insert into binance_keys(api_key) values (%s)",
[binance_api_key])
conn.commit()
print("Records inserted")
try:
cursor.execute("select api_secret from binance_keys")
r_2 = cursor.fetchall()
binance_api_secret = r_2[0][0]
except:
binance_api_secret = "Enter Api Secret"
cursor.execute("insert into binance_keys(api_secret) values (%s)",
[binance_api_secret])
conn.commit()
print("Records inserted")
try:
cursor.execute("select api_key from bybit_keys")
r_2 = cursor.fetchall()
bybit_api_key = r_2[0][0]
except:
bybit_api_key = "Enter Api Key"
cursor.execute("insert into bybit_keys(api_key) values (%s)",
[bybit_api_key])
conn.commit()
print("Records inserted")
try:
cursor.execute("select api_secret from bybit_keys")
r_2 = cursor.fetchall()
bybit_api_secret = r_2[0][0]
except:
bybit_api_secret = "Enter Api Secret"
cursor.execute("insert into bybit_keys(api_secret) values (%s)",
[bybit_api_secret])
conn.commit()
print("Records inserted")
@app.route('/')
def welcome():
return render_template('welcome.html')
@app.route('/profile',methods=["POST","GET"])
def get_profile():
if "password" in s_mgt:
entered_pw = s_mgt["password"]
if request.method == "GET":
try:
cursor.execute("select api_key from binance_keys")
r_2 = cursor.fetchall()
binance_api_key = r_2[0][0]
except:
binance_api_key = "Enter Api Key"
try:
cursor.execute("select api_secret from binance_keys")
r_2 = cursor.fetchall()
binance_api_secret = r_2[0][0]
except:
binance_api_secret = "Enter Api Secret"
try:
cursor.execute("select api_key from bybit_keys")
r_2 = cursor.fetchall()
bybit_api_key = r_2[0][0]
except:
bybit_api_key = "Enter Api Key"
try:
cursor.execute("select api_secret from bybit_keys")
r_2 = cursor.fetchall()
bybit_api_secret = r_2[0][0]
except:
bybit_api_secret = "Enter Api Secret"
return render_template('profile.html',bi_key=binance_api_key,bi_secret=binance_api_secret,by_key=bybit_api_key,by_secret=bybit_api_secret)
if request.method == "POST":
binance_api_key = request.form["binance_key"]
binance_api_secret = request.form["binance_secret"]
bybit_api_key = request.form["bybit_key"]
bybit_api_secret = request.form["bybit_secret"]
cursor.execute("update binance_keys set api_key = %s, api_secret = %s",[binance_api_key, binance_api_secret])
conn.commit()
print("Records inserted")
print("Done")
cursor.execute("update bybit_keys set api_key = %s, api_secret = %s", [bybit_api_key, bybit_api_secret])
conn.commit()
print("Records inserted")
print("Done")
return render_template('profile.html',bi_key=binance_api_key,bi_secret=binance_api_secret,by_key=bybit_api_key,by_secret=bybit_api_secret)
else:
return redirect("/")
correct_un = ""
correct_pw = ""
entered_ex = "Select Exchange"
entered_tt = "Select Trade Type"
entered_bc = "Select Base Coin"
@app.route('/copy_msg',methods=["POST"])
def get_json():
if "password" in s_mgt:
entered_pw = s_mgt["password"]
try:
exchange1 = '{"exchange"'
exchange2 = entered_ex
trade_type1 = "trade_type"
trade_type2 = entered_tt
base_coin1 = "base_coin"
base_coin2 = entered_bc
coin_pair = request.form["coin_pair"]
coin_pair1 = "coin_pair"
coin_pair2 = coin_pair
entry_type = request.form["entry_type"]
entry_type1 = "entry_type"
entry_type2 = entry_type
exit_type = request.form["exit_type"]
exit_type1 = "exit_type"
exit_type2 = exit_type
margin_mode = request.form["margin_mode"]
margin_mode1 = "margin_mode"
margin_mode2 = margin_mode
amt_type = request.form["amt_type"]
amt_type1 = "qty_type"
amt_type2 = amt_type
enter_amt = request.form["enter_amt"]
enter_amt1 = "qty"
enter_amt2 = enter_amt
long_lev = request.form["long_lev"]
long_lev1 = "long_leverage"
long_lev2 = long_lev
short_lev = request.form["short_lev"]
short_lev1 = "short_leverage"
short_lev2 = short_lev
long_sl = request.form["long_sl"]
long_sl1 = "long_stop_loss_percent"
long_sl2 = long_sl
long_tp = request.form["long_tp"]
long_tp1 = "long_take_profit_percent"
long_tp2 = long_tp
short_sl = request.form["short_sl"]
short_sl1 = "short_stop_loss_percent"
short_sl2 = short_sl
short_tp = request.form["short_tp"]
short_tp1 = "short_take_profit_percent"
short_tp2 = short_tp
multi_tp = request.form["multi_tp"]
multi_tp1 = "enable_multi_tp"
multi_tp2 = multi_tp
tp1_pos_size = request.form["tp1_pos_size"]
tp1_pos_size1 = "tp_1_pos_size"
tp1_pos_size2 = tp1_pos_size
tp2_pos_size = request.form["tp2_pos_size"]
tp2_pos_size1 = "tp_2_pos_size"
tp2_pos_size2 = tp2_pos_size
tp3_pos_size = request.form["tp3_pos_size"]
tp3_pos_size1 = "tp_3_pos_size"
tp3_pos_size2 = tp3_pos_size
tp1_percent = request.form["tp1_percent"]
tp1_percent1 = "tp1_percent"
tp1_percent2 = tp1_percent
tp2_percent = request.form["tp2_percent"]
tp2_percent1 = "tp2_percent"
tp2_percent2 = tp2_percent
tp3_percent = request.form["tp3_percent"]
tp3_percent1 = "tp3_percent"
tp3_percent2 = tp3_percent
stop_bot = request.form["stop_bot"]
stop_bot1 = "stop_bot_below_balance"
stop_bot2 = stop_bot
time_out = request.form["time_out"]
time_out1 = "order_time_out"
time_out2 = time_out
enterlong1 = "position_type"
enterlong2 = '"Enter_long"}'
entershort1 = "position_type"
entershort2 = '"Enter_short"}'
exitlong1 = "position_type"
exitlong2 = '"Exit_long"}'
exitshort1 = "position_type"
exitshort2 = '"Exit_short"}'
return render_template('copy_msg.html',exchange1=exchange1,exchange2=exchange2,trade_type1=trade_type1,trade_type2=trade_type2,base_coin1=base_coin1,base_coin2=base_coin2,coin_pair1=coin_pair1,coin_pair2=coin_pair2,entry_type1=entry_type1,entry_type2=entry_type2,exit_type1=exit_type1,exit_type2=exit_type2,margin_mode1=margin_mode1,margin_mode2=margin_mode2,amt_type1=amt_type1,amt_type2=amt_type2,enter_amt1=enter_amt1,enter_amt2=enter_amt2,long_lev1=long_lev1,long_lev2=long_lev2,short_lev1=short_lev1,short_lev2=short_lev2,long_sl1=long_sl1,long_sl2=long_sl2,long_tp1=long_tp1,long_tp2=long_tp2,short_sl1=short_sl1,short_sl2=short_sl2,short_tp1=short_tp1,short_tp2=short_tp2,multi_tp1=multi_tp1,multi_tp2=multi_tp2,tp1_pos_size1=tp1_pos_size1,tp1_pos_size2=tp1_pos_size2,tp2_pos_size1=tp2_pos_size1,tp2_pos_size2=tp2_pos_size2,tp3_pos_size1=tp3_pos_size1,tp3_pos_size2=tp3_pos_size2,tp1_percent1=tp1_percent1,tp1_percent2=tp1_percent2,tp2_percent1=tp2_percent1,tp2_percent2=tp2_percent2,tp3_percent1=tp3_percent1,tp3_percent2=tp3_percent2,stop_bot1=stop_bot1,stop_bot2=stop_bot2,time_out1=time_out1,time_out2=time_out2,enterlong1=enterlong1,enterlong2=enterlong2,entershort1=entershort1,entershort2=entershort2,exitlong1=exitlong1,exitlong2=exitlong2,exitshort1=exitshort1,exitshort2=exitshort2)
except:
return render_template('missing_fields.html')
else:
return redirect("/")
@app.route('/json_generator',methods=["POST", "GET"])
def gen_json():
global correct_pw
global correct_un
global entered_ex
global entered_tt
global entered_bc
list_of_coin_pairs = []
dup_removed_list = []
base_url = "https://api.bybit.com"
session = pybit.spot.HTTP(base_url, api_key, api_secret)
f_session = pybit.usdt_perpetual.HTTP(base_url, api_key, api_secret)
try:
entered_ex = request.form["exchange"]
except:
pass
try:
entered_tt = request.form["trade_type"]
except:
pass
try:
entered_bc = request.form["base_coin"]
except:
pass
if entered_tt != "Select Trade Type" and entered_ex != "Select Exchange" and entered_bc != "Select Base Coin":
if entered_ex == "Binance":
if entered_tt == "Spot":
spot_e_i = client.get_exchange_info()
spot_e_info = spot_e_i["symbols"]
for item in spot_e_info:
quote_asset = item["quoteAsset"]
if quote_asset == entered_bc:
cp = item["symbol"]
list_of_coin_pairs.append(cp)
if entered_tt == "Futures":
futures_e_i = client.futures_exchange_info()
futures_e_info = futures_e_i["symbols"]
for item in futures_e_info:
quote_asset = item["quoteAsset"]
if quote_asset == entered_bc:
cp = item["symbol"]
list_of_coin_pairs.append(cp)
if entered_ex == "Bybit":
if entered_tt == "Spot":
exchange_info = session.query_symbol()
for s in exchange_info['result']:
quote_asset = s['quoteCurrency']
if quote_asset == entered_bc:
cp = s["name"]
list_of_coin_pairs.append(cp)
if entered_tt == "Futures":
exchange_info = f_session.query_symbol()
for s in exchange_info['result']:
quote_asset = s['quote_currency']
if quote_asset == entered_bc:
cp = s["name"]
list_of_coin_pairs.append(cp)
dup_removed_list = list(dict.fromkeys(list_of_coin_pairs))
if request.method == "POST":
try:
entered_un = request.form["Username"]
entered_pw = request.form["Password"]
correct_un = entered_un
correct_pw = entered_pw
except:
pass
s_mgt["password"] = correct_pw
if correct_un == dash_user_name and correct_pw == dash_password:
if list_of_coin_pairs == []:
list_with_error = ["Required fields missing or incorrect to generate coin pairs"]
return render_template('json_gen.html', coin_list=list_with_error,exchange_name=entered_ex,trade_name=entered_tt,base_coin_name=entered_bc)
else:
return render_template('json_gen.html', coin_list=dup_removed_list,exchange_name=entered_ex,trade_name=entered_tt,base_coin_name=entered_bc)
else:
return render_template('welcome_incorrect_credentials.html')
if request.method == "GET":
if list_of_coin_pairs == []:
list_with_error = ["Required fields missing to generate coin pairs"]
return render_template('json_gen.html', coin_list=list_with_error,exchange_name=entered_ex,trade_name=entered_tt,base_coin_name=entered_bc)
else:
return render_template('json_gen.html',coin_list=dup_removed_list,exchange_name=entered_ex,trade_name=entered_tt,base_coin_name=entered_bc)
@app.route('/binance_spot',methods=["POST", "GET"])
def index():
if "password" in s_mgt:
entered_pw = s_mgt["password"]
# establishing the connection
conn = psycopg2.connect(
database="gpu", user='postgres', password='postgres', host='127.0.0.1', port='5432')
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
# Executing an MYSQL function using the execute() method
cursor.execute("select version()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ", data)
cursor.execute("ALTER DATABASE gpu SET timezone TO 'Europe/Berlin';")
conn.commit()
print(request)
global api_key
global api_secret
try:
cursor.execute("select api_key from binance_keys")
r_2 = cursor.fetchall()
if r_2[0][0] == "Enter Api Key":
api_key = ""
else:
api_key = r_2[0][0]
except:
api_key = ""
try:
cursor.execute("select api_secret from binance_keys")
r_2 = cursor.fetchall()
if r_2[0][0] == "Enter Api Secret":
api_secret = ""
else:
api_secret = r_2[0][0]
except:
api_secret = ""
if api_key and api_secret != "":
try:
client = Client(api_key, api_secret)
except:
return render_template('invalid_key.html')
try:
open_orders = client.get_open_orders()
sql = ''' DELETE FROM open_orders '''
cursor.execute(sql)
conn.commit()
for order in open_orders:
create_time = order["time"]
SPOT_OR_CREATE_DATE = datetime.fromtimestamp((create_time / 1000)).strftime("%Y-%m-%d")
# SPOT_OR_CREATE_TIME = datetime.fromtimestamp((create_time / 1000)).strftime("%I:%M:%S")
SPOT_SYM = order["symbol"]
SPOT_OR_ID = order["orderId"]
p = order["price"]
num = Decimal(p)
SPOT_PRICE = num.normalize()
q = order["origQty"]
q_num = Decimal(q)
SPOT_QUANTITY = q_num.normalize()
SPOT_OR_ACTION = order["side"]
SPOT_OR_TYPE = order["type"]
prices = client.get_all_tickers()
for ticker in prices:
if ticker["symbol"] == SPOT_SYM:
SPOT_SYM_CURRENT_PRICE = float(ticker["price"])
break
try:
cursor.execute("select entry_price from s_id_list where order_id = %s", [SPOT_OR_ID])
result = cursor.fetchall()
ENTRY_PRICE_OF_BUY_ORDER = float(result[0][0])
# p_o_l = ((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER)/ENTRY_PRICE_OF_BUY_ORDER)
# p_o_l_r = round(p_o_l,6)
#
# PROFIT_OR_LOSS_FROM_ENTRY = ("{:.3%}".format(p_o_l_r))
p_n_l = round((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER),3)
p_o_l = ((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER) / ENTRY_PRICE_OF_BUY_ORDER) * 100
PROFIT_OR_LOSS_FROM_ENTRY = str((round(p_o_l, 3))) + "%"
print(PROFIT_OR_LOSS_FROM_ENTRY)
cursor.execute(
"insert into open_orders(created_date, symbol, order_id, price, quantity, order_action, order_type, entry_price, current_price, pnl,pnl_per) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s)",
[SPOT_OR_CREATE_DATE, SPOT_SYM, SPOT_OR_ID, SPOT_PRICE, SPOT_QUANTITY, SPOT_OR_ACTION,
SPOT_OR_TYPE, ENTRY_PRICE_OF_BUY_ORDER, SPOT_SYM_CURRENT_PRICE, p_n_l,
PROFIT_OR_LOSS_FROM_ENTRY])
conn.commit()
except:
cursor.execute(
"insert into open_orders(created_date, symbol, order_id, price, quantity, order_action, order_type, current_price) values (%s, %s, %s, %s, %s, %s, %s, %s)",
[SPOT_OR_CREATE_DATE, SPOT_SYM, SPOT_OR_ID, SPOT_PRICE, SPOT_QUANTITY, SPOT_OR_ACTION,
SPOT_OR_TYPE, SPOT_SYM_CURRENT_PRICE])
conn.commit()
except:
pass
cursor.execute("SELECT to_char(created_date, 'DD-mon-YYYY HH12:MIPM'),order_id,symbol,price,quantity,order_action,order_type,entry_price,current_price,pnl,pnl_per FROM open_orders;")
rowResults=cursor.fetchall()
list_length = len(rowResults)
exchange_info = client.get_exchange_info()
list_of_coin_pairs = []
for s in exchange_info['symbols']:
baseAsset = s['baseAsset']
list_of_coin_pairs.append((baseAsset + "USD"))
dup_removed_list = list(dict.fromkeys(list_of_coin_pairs))
cursor.execute("SELECT to_char(occured_time, 'DD-mon-YYYY HH12:MIPM'),symbol,order_action,entry_order_type,exit_order_type,quantity,error_description FROM error_log;")
error_rowResults = cursor.fetchall()
error_list_length = len(error_rowResults)
cursor.execute("SELECT to_char(date_time, 'DD-mon-YYYY HH12:MIPM'),order_id,symbol,order_action,order_type,executed_price,executed_qty,execution,pnl,percentage FROM trade_log;")
trade_rowResults = cursor.fetchall()
trade_list_length = len(trade_rowResults)
try:
deposits = client.get_deposit_history()
total_deposited_amt = float(0)
for deposit in deposits:
deposited_coin_name = deposit["coin"]
deposited_amount = float(deposit["amount"])
if deposited_coin_name == "USDT":
total_deposited_amt += deposited_amount
else:
current_price_USDT = client.get_symbol_ticker(symbol=deposited_coin_name + "USDT")["price"]
total_deposited_amt += deposited_amount * float(current_price_USDT)
deposits_display = f"Deposited Amt (USD): {round((total_deposited_amt), 2)}"
except:
return render_template('invalid_key.html')
try:
margin_info = client.get_margin_account()["userAssets"]
margin_balance = float(0)
for margin_asset in margin_info:
value = float(margin_asset["free"]) + float(margin_asset["locked"])
margin_balance += value
print(f"Margin balance = {margin_balance}")
futures_info = client.futures_account_balance()
futures_usd = 0.0
for futures_asset in futures_info:
name = futures_asset["asset"]
balance = float(futures_asset["balance"])
if name == "USDT":
futures_usd += balance
else:
current_price_USDT = client.get_symbol_ticker(symbol=name + "USDT")["price"]
futures_usd += balance * float(current_price_USDT)
print(f"Futures balance = {futures_usd}")
sum_SPOT = 0.0
balances = client.get_account()
for _balance in balances["balances"]:
asset = _balance["asset"]
if float(_balance["free"]) != 0.0 or float(_balance["locked"]) != 0.0:
if asset == "USDT":
usdt_quantity = float(_balance["free"]) + float(_balance["locked"])
sum_SPOT += usdt_quantity
try:
btc_quantity = float(_balance["free"]) + float(_balance["locked"])
_price = client.get_symbol_ticker(symbol=asset + "USDT")
sum_SPOT += btc_quantity * float(_price["price"])
except:
pass
print(f"Spot balance = {sum_SPOT}")
total_asset_balance = sum_SPOT + futures_usd + margin_balance
asset_balance_display = f"Asset Balance (USD): {round((total_asset_balance), 2)}"
spot_balance_display = f"Asset Balance (USD): {round((sum_SPOT), 2)}"
except:
asset_balance_display = "Asset Balance (USD): NA"
spot_balance_display = "Asset Balance (USD): NA"
cursor.execute("select sum(pnl) as total from trade_log")
results = cursor.fetchall()
try:
overall_pnl = float(round((results[0][0]), 2))
pnl_display = f"Spot PnL (USD): {overall_pnl}"
except:
overall_pnl = "NA"
pnl_display = "Spot PnL (USD): NA"
labels = []
values = []
labels.clear()
values.clear()
try:
acc_info = client.get_account()
prices = client.get_all_tickers()
for asset in acc_info["balances"]:
if float(asset["free"]) != 0.0 or float(asset["locked"]) != 0.0:
pair_name = asset["asset"]
total_bal = float(asset["free"]) + float(asset["locked"])
for price in prices:
sym_for_price = price["symbol"]
if pair_name + "USDT" == sym_for_price:
usdt_price = float(price["price"])
value_in_usdt = (total_bal * usdt_price)
break
if pair_name == "USDT" and total_bal > 2:
labels.append(pair_name)
values.append(round(total_bal, 2))
if value_in_usdt > 2:
labels.append(pair_name)
values.append(round(value_in_usdt, 2))
except:
pass
try:
coin_pair_name = request.form["coins"]
href_modified = f"https://www.tradingview.com/symbols/{coin_pair_name}/?exchange=BITSTAMP"
except:
coin_pair_name = "BTCUSD"
href_modified = f"https://www.tradingview.com/symbols/{coin_pair_name}/?exchange=BITSTAMP"
return render_template('index.html',recentRecords=rowResults,list_length=list_length,coin_list=dup_removed_list,coin_pair_name=coin_pair_name,modified_link=href_modified,labels=labels,values=values,colors=colors,error_recentRecords=error_rowResults,error_list_length=error_list_length,trade_recentRecords=trade_rowResults,trade_list_length=trade_list_length,deposits=deposits_display,assets=asset_balance_display,pnl=pnl_display,spot=spot_balance_display)
else:
return render_template('error.html')
else:
return redirect("/")
@app.route('/bybit_spot',methods=["POST", "GET"])
def get_bybit_spot():
if "password" in s_mgt:
entered_pw = s_mgt["password"]
# establishing the connection
conn = psycopg2.connect(database="gpu", user='postgres', password='postgres', host='127.0.0.1', port='5432')
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
# Executing an MYSQL function using the execute() method
cursor.execute("select version()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ", data)
cursor.execute("ALTER DATABASE gpu SET timezone TO 'Europe/Berlin';")
conn.commit()
print(request)
global api_key
global api_secret
try:
cursor.execute("select api_key from bybit_keys")
r_2 = cursor.fetchall()
if r_2[0][0] == "Enter Api Key":
api_key = ""
else:
api_key = r_2[0][0]
except:
api_key = ""
try:
cursor.execute("select api_secret from bybit_keys")
r_2 = cursor.fetchall()
if r_2[0][0] == "Enter Api Secret":
api_secret = ""
else:
api_secret = r_2[0][0]
except:
api_secret = ""
if api_key and api_secret != "":
try:
base_url = "https://api.bybit.com"
session = pybit.spot.HTTP(base_url, api_key, api_secret)
except:
return render_template('invalid_key.html')
try:
open_orders = session.query_active_order()
sql = ''' DELETE FROM bybit_open_orders '''
cursor.execute(sql)
conn.commit()
for order in open_orders["result"]["list"]:
create_time = order["createTime"]
SPOT_OR_CREATE_DATE = datetime.fromtimestamp((create_time / 1000)).strftime("%Y-%m-%d")
# SPOT_OR_CREATE_TIME = datetime.fromtimestamp((create_time / 1000)).strftime("%I:%M:%S")
SPOT_SYM = order["symbol"]
SPOT_OR_ID = order["orderId"]
SPOT_PRICE = order["orderPrice"]
SPOT_QUANTITY = order["orderQty"]
SPOT_OR_ACTION = order["side"]
SPOT_OR_TYPE = order["orderType"]
symbol_data = (session.latest_information_for_symbol(symbol=SPOT_SYM))
SPOT_SYM_CURRENT_PRICE = float(symbol_data['result']['lastPrice'])
try:
cursor.execute("select entry_price from s_id_list where order_id = %s", [SPOT_OR_ID])
result = cursor.fetchall()
ENTRY_PRICE_OF_BUY_ORDER = float(result[0][0])
# p_o_l = ((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER)/ENTRY_PRICE_OF_BUY_ORDER)
# p_o_l_r = round(p_o_l,6)
#
# PROFIT_OR_LOSS_FROM_ENTRY = ("{:.3%}".format(p_o_l_r))
p_n_l = round((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER),3)
p_o_l = ((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER) / ENTRY_PRICE_OF_BUY_ORDER) * 100
PROFIT_OR_LOSS_FROM_ENTRY = str((round(p_o_l, 3))) + "%"
print(PROFIT_OR_LOSS_FROM_ENTRY)
cursor.execute(
"insert into bybit_open_orders(created_date, symbol, order_id, price, quantity, order_action, order_type, entry_price, current_price, pnl,pnl_per) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s)",
[SPOT_OR_CREATE_DATE, SPOT_SYM, SPOT_OR_ID, SPOT_PRICE, SPOT_QUANTITY, SPOT_OR_ACTION,
SPOT_OR_TYPE, ENTRY_PRICE_OF_BUY_ORDER, SPOT_SYM_CURRENT_PRICE, p_n_l,
PROFIT_OR_LOSS_FROM_ENTRY])
conn.commit()
except:
cursor.execute(
"insert into bybit_open_orders(created_date, symbol, order_id, price, quantity, order_action, order_type, current_price) values (%s, %s, %s, %s, %s, %s, %s, %s)",
[SPOT_OR_CREATE_DATE, SPOT_SYM, SPOT_OR_ID, SPOT_PRICE, SPOT_QUANTITY, SPOT_OR_ACTION,
SPOT_OR_TYPE, SPOT_SYM_CURRENT_PRICE])
conn.commit()
open_orders_2 = session.query_active_order(orderCategory=1)
for order in open_orders_2["result"]["list"]:
create_time = order["createTime"]
SPOT_OR_CREATE_DATE = datetime.fromtimestamp((create_time / 1000)).strftime("%Y-%m-%d")
# SPOT_OR_CREATE_TIME = datetime.fromtimestamp((create_time / 1000)).strftime("%I:%M:%S")
SPOT_SYM = order["symbol"]
SPOT_OR_ID = order["orderId"]
SPOT_PRICE = order["triggerPrice"]
SPOT_QUANTITY = order["orderQty"]
SPOT_OR_ACTION = order["side"]
SPOT_OR_TYPE = order["orderType"]
symbol_data = (session.latest_information_for_symbol(symbol=SPOT_SYM))
SPOT_SYM_CURRENT_PRICE = float(symbol_data['result']['lastPrice'])
try:
cursor.execute("select entry_price from s_id_list where order_id = %s", [SPOT_OR_ID])
result = cursor.fetchall()
ENTRY_PRICE_OF_BUY_ORDER = float(result[0][0])
# p_o_l = ((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER)/ENTRY_PRICE_OF_BUY_ORDER)
# p_o_l_r = round(p_o_l,6)
#
# PROFIT_OR_LOSS_FROM_ENTRY = ("{:.3%}".format(p_o_l_r))
p_n_l = round((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER), 3)
p_o_l = ((SPOT_SYM_CURRENT_PRICE - ENTRY_PRICE_OF_BUY_ORDER) / ENTRY_PRICE_OF_BUY_ORDER) * 100
PROFIT_OR_LOSS_FROM_ENTRY = str((round(p_o_l, 3))) + "%"
print(PROFIT_OR_LOSS_FROM_ENTRY)
cursor.execute(
"insert into bybit_open_orders(created_date, symbol, order_id, price, quantity, order_action, order_type, entry_price, current_price, pnl,pnl_per) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s,%s)",
[SPOT_OR_CREATE_DATE, SPOT_SYM, SPOT_OR_ID, SPOT_PRICE, SPOT_QUANTITY, SPOT_OR_ACTION,
SPOT_OR_TYPE, ENTRY_PRICE_OF_BUY_ORDER, SPOT_SYM_CURRENT_PRICE, p_n_l,
PROFIT_OR_LOSS_FROM_ENTRY])
conn.commit()
except:
cursor.execute(
"insert into bybit_open_orders(created_date, symbol, order_id, price, quantity, order_action, order_type, current_price) values (%s, %s, %s, %s, %s, %s, %s, %s)",
[SPOT_OR_CREATE_DATE, SPOT_SYM, SPOT_OR_ID, SPOT_PRICE, SPOT_QUANTITY, SPOT_OR_ACTION,
SPOT_OR_TYPE, SPOT_SYM_CURRENT_PRICE])
conn.commit()
except:
pass
try:
cursor.execute("SELECT to_char(created_date, 'DD-mon-YYYY HH12:MIPM'),order_id,symbol,price,quantity,order_action,order_type,entry_price,current_price,pnl,pnl_per FROM bybit_open_orders;")
rowResults=cursor.fetchall()
list_length = len(rowResults)
except:
rowResults = []
list_length = 0
exchange_info = session.query_symbol()
list_of_coin_pairs = []
for s in exchange_info['result']:
baseAsset = s['baseCurrency']
list_of_coin_pairs.append((baseAsset + "USD"))
dup_removed_list = list(dict.fromkeys(list_of_coin_pairs))
try:
cursor.execute("SELECT to_char(occured_time, 'DD-mon-YYYY HH12:MIPM'),symbol,order_action,entry_order_type,exit_order_type,quantity,error_description FROM bybit_error_log;")
error_rowResults = cursor.fetchall()
error_list_length = len(error_rowResults)
except:
error_rowResults = []
error_list_length = 0
try:
cursor.execute("SELECT to_char(date_time, 'DD-mon-YYYY HH12:MIPM'),symbol,order_id,order_action,order_type,executed_price,executed_qty,execution,pnl,percentage FROM bybit_trade_log;")
trade_rowResults = cursor.fetchall()
trade_list_length = len(trade_rowResults)
except:
trade_rowResults = []
trade_list_length = 0
try:
spot_balance = session.get_wallet_balance()
spot_total_asset_balance = 0
for bals in spot_balance["result"]["balances"]:
if bals["coin"] == "USDT":
USD_BAL = float(bals["total"])
spot_total_asset_balance += USD_BAL
else:
other_coin = bals["coin"]
other_coin_bal = float(bals["total"])
sym_for_bal = other_coin+"USDT"
symbol_data = (session.latest_information_for_symbol(symbol=sym_for_bal))
usdt_price_of_other_coin = float(symbol_data['result']['lastPrice'])
OTHER_COIN_BALANCE = other_coin_bal * usdt_price_of_other_coin
spot_total_asset_balance += OTHER_COIN_BALANCE
f_session = pybit.usdt_perpetual.HTTP(base_url, api_key, api_secret)
futures_balance = f_session.get_wallet_balance()
futures_total_asset_balance = 0
for bals in futures_balance["result"]:
if bals == "USDT":
USD_BAL = float(futures_balance["result"][bals]["equity"])
futures_total_asset_balance += USD_BAL
else:
other_coin = bals
other_coin_bal = float(futures_balance["result"][bals]["equity"])
sym_for_bal = other_coin + "USDT"
print(sym_for_bal)
try:
symbol_data = (f_session.latest_information_for_symbol(symbol=sym_for_bal))
usdt_price_of_other_coin = float(symbol_data['result'][0]['last_price'])
OTHER_COIN_BALANCE = other_coin_bal * usdt_price_of_other_coin
futures_total_asset_balance += OTHER_COIN_BALANCE
except:
pass
total_asset_balance = spot_total_asset_balance + futures_total_asset_balance
asset_balance_display = f"Asset Balance (USD): {round((total_asset_balance), 2)}"
spot_balance_display = f"Asset Balance (USD): {round((spot_total_asset_balance), 2)}"
except:
asset_balance_display = "Asset Balance (USD): NA"
spot_balance_display = "Asset Balance (USD): NA"
try:
cursor.execute("select sum(pnl) as total from bybit_trade_log")
results = cursor.fetchall()
overall_pnl = float(round((results[0][0]), 2))
pnl_display = f"Spot PnL (USD): {overall_pnl}"
except:
overall_pnl = "NA"
pnl_display = "Spot PnL (USD): NA"
labels = []
values = []
labels.clear()
values.clear()
try:
spot_balance = session.get_wallet_balance()
for bals in spot_balance["result"]["balances"]:
pair_name = bals["coin"]
labels.append(pair_name)
if pair_name == "USDT":
USD_BAL = round(float(bals["total"]), 2)
values.append(USD_BAL)
else:
other_coin = bals["coin"]
other_coin_bal = float(bals["total"])
sym_for_bal = other_coin + "USDT"
symbol_data = (session.latest_information_for_symbol(symbol=sym_for_bal))
usdt_price_of_other_coin = float(symbol_data['result']['lastPrice'])
OTHER_COIN_BALANCE = round((other_coin_bal * usdt_price_of_other_coin), 2)
values.append(OTHER_COIN_BALANCE)
except:
pass
try:
coin_pair_name = request.form["coins"]
href_modified = f"https://www.tradingview.com/symbols/{coin_pair_name}/?exchange=BITSTAMP"
except:
coin_pair_name = "BTCUSD"
href_modified = f"https://www.tradingview.com/symbols/{coin_pair_name}/?exchange=BITSTAMP"
return render_template('bybit_index.html',recentRecords=rowResults,list_length=list_length,coin_list=dup_removed_list,coin_pair_name=coin_pair_name,modified_link=href_modified,labels=labels,values=values,colors=colors,error_recentRecords=error_rowResults,error_list_length=error_list_length,trade_recentRecords=trade_rowResults,trade_list_length=trade_list_length,assets=asset_balance_display,pnl=pnl_display,spot=spot_balance_display)
else:
return render_template('error.html')
else:
return redirect("/")
@app.route('/binance_futures',methods=["POST", "GET"])
def get_futures():
if "password" in s_mgt:
entered_pw = s_mgt["password"]
# establishing the connection
conn = psycopg2.connect(
database="gpu", user='postgres', password='postgres', host='127.0.0.1', port='5432')
# Creating a cursor object using the cursor() method
cursor = conn.cursor()
# Executing an MYSQL function using the execute() method
cursor.execute("select version()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ", data)
cursor.execute("ALTER DATABASE gpu SET timezone TO 'Europe/Berlin';")
conn.commit()
print(request)
global api_key
global api_secret
try:
cursor.execute("select api_key from binance_keys")
r_2 = cursor.fetchall()
api_key = r_2[0][0]
except:
api_key = ""
try:
cursor.execute("select api_secret from binance_keys")
r_2 = cursor.fetchall()
api_secret = r_2[0][0]
except:
api_secret = ""
if api_key and api_secret != "":
try:
client = Client(api_key, api_secret)
except:
return render_template('invalid_key.html')
try:
open_orders = client.futures_get_open_orders()
sql = ''' DELETE FROM f_o_orders '''
cursor.execute(sql)
conn.commit()
for order in open_orders:
create_time = order["time"]
create_date = datetime.fromtimestamp((create_time / 1000)).strftime("%Y-%m-%d")
# SPOT_OR_CREATE_TIME = datetime.fromtimestamp((create_time / 1000)).strftime("%I:%M:%S")
sym = order["symbol"]
id = order["orderId"]
p = order["stopPrice"]
num = Decimal(p)
price = num.normalize()
action= order["side"]
type = order["type"]
prices = client.get_all_tickers()
for ticker in prices:
if ticker["symbol"] == sym:
sym_current_price = float(ticker["price"])
break
try:
cursor.execute("select entry_price from f_id_list where order_id = %s", [id])
result = cursor.fetchall()
ENTRY_PRICE_OF_INITIAL_ORDER = float(result[0][0])
cursor.execute("select qty from f_id_list where order_id = %s", [id])
result = cursor.fetchall()
QTY_OF_OPEN_ORDER = float(result[0][0])
p_n_l = round((sym_current_price - ENTRY_PRICE_OF_INITIAL_ORDER),3)
p_o_l = ((sym_current_price - ENTRY_PRICE_OF_INITIAL_ORDER) / ENTRY_PRICE_OF_INITIAL_ORDER) * 100
PROFIT_OR_LOSS_FROM_ENTRY = str((round(p_o_l, 3))) + "%"
cursor.execute("insert into f_o_orders(created_date, symbol, order_id, price, quantity, order_action, order_type, entry_price, current_price, pnl, pnl_per) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",[create_date, sym, id, price, QTY_OF_OPEN_ORDER, action,type, ENTRY_PRICE_OF_INITIAL_ORDER, sym_current_price, p_n_l, PROFIT_OR_LOSS_FROM_ENTRY])
conn.commit()
except:
cursor.execute(
"insert into f_o_orders(created_date, symbol, order_id, price, order_action, order_type, current_price) values (%s, %s, %s, %s, %s, %s, %s)",
[create_date, sym, id, price, action, type, sym_current_price])
conn.commit()
except:
pass
try:
open_positions = client.futures_position_information()
sql = ''' DELETE FROM f_o_positions '''
cursor.execute(sql)
conn.commit()
for order in open_positions:
sym = order["symbol"]
create_time = order["updateTime"]
create_date = datetime.fromtimestamp((create_time / 1000)).strftime("%Y-%m-%d")
# SPOT_OR_CREATE_TIME = datetime.fromtimestamp((create_time / 1000)).strftime("%I:%M:%S")
pos_entry_price = float(order["entryPrice"])
liquidation_price = float(order["liquidationPrice"])
pos_current_price = float(order["markPrice"])
margin_type = order["marginType"]
leverage = int(order["leverage"])
if float(order["positionAmt"]) < 0:
pos_qty = (float(order["positionAmt"]))*-1
pos_side = "SELL"
else:
pos_qty = float(order["positionAmt"])
pos_side = "BUY"
PROFIT_OR_LOSS_FROM_ENTRY = round((float(order["unRealizedProfit"])),6)
if float(order["positionAmt"]) != 0:
cursor.execute(