-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbotclass.py
1582 lines (1497 loc) · 65.2 KB
/
botclass.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 datetime import datetime
from enum import Enum
from dataclasses import dataclass
import numpy as np
import requests
import mariadb
import errorclass as error
import error_helper
@dataclass
class TickerData():
opens: np.ndarray
highs: np.ndarray
lows: np.ndarray
closes: np.ndarray
volumes: np.ndarray
dates: np.ndarray
@dataclass
class StrategyResponse():
signal: bool
stopPrice: float
targetPrice: float
targetRatio: float
strategy: int
class BinanceExchangeInfo:
def __init__(self,
dbCursor=None,
symbol=None,
baseAsset=None,
quoteAsset=None,
baseAssetName=None,
exchangeId=1,
status=0,
updateDate=datetime.now().strftime("%Y-%m-%d"),
updateTime=datetime.now().strftime("%H:%M:%S")
):
self.dbCursor = dbCursor
self.symbol = symbol # ETHBTC
self.baseAsset = baseAsset # ETH
self.quoteAsset = quoteAsset # BTC
self.baseAssetName = baseAssetName # ethereum
self.exchangeId = exchangeId # 1 (Binance)
self.status = status
self.updateDate = updateDate
self.updateTime = updateTime
def getData(self, url=None):
dbCursor = self.dbCursor
try:
response = requests.get(url)
response.raise_for_status()
records = response.json()
return records['symbols']
# return records['result']['data']
except requests.exceptions.HTTPError as errh:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errh.response.status_code
log.errorMessage = errh.response.text
log.moduleName = type(self).__name__
log.explanation = "Http Error: " + errh.response.url
log.addData()
except requests.exceptions.ConnectionError as errc:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errc.response.status_code
log.errorMessage = errc.response.text
log.moduleName = type(self).__name__
log.explanation = "Error Connecting: " + errc.response.url
log.addData()
except requests.exceptions.Timeout as errt:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errt.response.status_code
log.errorMessage = errt.response.text
log.moduleName = type(self).__name__
log.explanation = "Timeout Error: " + errt.response.url
log.addData()
except requests.exceptions.RequestException as err:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = err.response.status_code
log.errorMessage = err.response.text
log.moduleName = type(self).__name__
log.explanation = err.response.url
log.addData()
def addData(self):
try:
self.dbCursor.execute(
"INSERT INTO coin (symbol, base_asset, quote_asset, base_asset_name, "
" exchange_id, status, update_date, update_time) "
"VALUES (?, ?, ?, ?, ? ,?, ?, ?)",
(self.symbol, self.baseAsset, self.quoteAsset, self.baseAssetName,
self.exchangeId, self.status, self.updateDate, self.updateTime))
except mariadb.Error as e:
# print(f"Error: {e.errno} {e.errmsg}")
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "INSERT INTO coin"
log.addData()
def readAllSymbol(self):
try:
self.dbCursor.execute("SELECT JSON_OBJECT('symbol', symbol) FROM coin WHERE status=1")
rows = self.dbCursor.fetchall()
return rows
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "SELECT all coin"
log.addData()
def readAllCoinAsset(self, exchangeId):
try:
self.dbCursor.execute(
"SELECT JSON_OBJECT('symbol', symbol, 'base', base_asset, 'quote', quote_asset) "
"FROM symbol WHERE STATUS=? AND exchange_id=?",
(0, exchangeId)
)
rows = self.dbCursor.fetchall()
return rows
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "SELECT all coin"
log.addData()
class BinanceSymbol:
def __init__(self,
symbol=None,
exchange_id=None,
base_asset=None,
base_asset_precision=None,
quote_asset=None,
quote_precision=None,
quote_asset_precision=None,
symbol_status=None,
order_types=None,
iceberg_allowed=None,
oco_allowed=None,
quote_order_qty_market_allowed=None,
allow_trailing_stop=None,
cancel_replace_allowed=None,
is_spot_trading_allowed=None,
is_margin_trading_allowed=None,
permissions=None,
min_price=None,
max_price=None,
tick_size=None,
min_lot=None,
max_lot=None,
step_size=None,
min_notional=None,
status=None,
market_group=None,
update_time=None,
):
self.symbol = symbol
self.exchange_id = exchange_id
self.base_asset = base_asset
self.base_asset_precision = base_asset_precision
self.quote_asset = quote_asset
self.quote_precision = quote_precision
self.quote_asset_precision = quote_asset_precision
self.symbol_status = symbol_status
self.order_types = order_types
self.iceberg_allowed = iceberg_allowed
self.oco_allowed = oco_allowed
self.quote_order_qty_market_allowed = quote_order_qty_market_allowed
self.allow_trailing_stop = allow_trailing_stop
self.cancel_replace_allowed = cancel_replace_allowed
self.is_spot_trading_allowed = is_spot_trading_allowed
self.is_margin_trading_allowed = is_margin_trading_allowed
self.permissions = permissions
self.min_price = min_price
self.max_price = max_price
self.tick_size = tick_size
self.min_lot = min_lot
self.max_lot = max_lot
self.step_size = step_size
self.min_notional = min_notional
self.status = status
self.market_group = market_group
self.update_time = update_time
@staticmethod
def getData(url=None):
try:
response = requests.get(url)
response.raise_for_status()
records = response.json()
return records['symbols']
except requests.exceptions.RequestException as err:
helper = error_helper.ErrorHelper()
helper.status_code = err.response.status_code
helper.code = err.errno
helper.msg = err.response.reason
helper.module = 'Symbol getData'
helper.url = err.response.url
helper.addData()
def addData(self, dbCursor=None):
self.update_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
dbCursor.execute(
"INSERT INTO symbol (symbol, exchange_id, base_asset, base_asset_precision, quote_asset, "
"quote_precision, quote_asset_precision, symbol_status, order_types, iceberg_allowed, oco_allowed, "
"quote_order_qty_market_allowed, allow_trailing_stop, cancel_replace_allowed, "
"is_spot_trading_allowed, is_margin_trading_allowed, permissions, min_price, max_price, tick_size, "
"min_lot, max_lot, step_size, min_notional, status, market_group, update_time) "
"VALUES (?, ?, ?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(self.symbol, self.exchange_id, self.base_asset, self.base_asset_precision, self.quote_asset,
self.quote_precision, self.quote_asset_precision, self.symbol_status, self.order_types,
self.iceberg_allowed, self.oco_allowed, self.quote_order_qty_market_allowed, self.allow_trailing_stop,
self.cancel_replace_allowed, self.is_spot_trading_allowed,self.is_margin_trading_allowed,
self.permissions, self.min_price, self.max_price, self.tick_size, self.min_lot, self.max_lot,
self.step_size, self.min_notional, self.status, self.market_group, self.update_time))
except mariadb.Error as e:
# print(f"Error: {e.errno} {e.errmsg}")
helper = error_helper.ErrorHelper()
helper.code = e.errno
helper.msg = e.errmeg
helper.module = 'Symbol addData'
helper.explanation = "INSERT INTO SYMBOL"
helper.addData()
@staticmethod
def readAll(dbCursor=None, exchangeId=None, quoteAsset=None):
try:
dbCursor.execute(
"SELECT JSON_OBJECT('symbol', symbol, 'base', base_asset, 'quote', quote_asset, "
"'min_price', min_price, 'max_price', max_price, 'tick_size', tick_size, 'min_lot', min_lot, "
"'max_lot', max_lot, 'step_size', step_size, 'min_notional', min_notional ) "
"FROM symbol WHERE exchange_id=? AND quote_asset=? AND STATUS=? AND symbol_status=? "
" AND permissions LIKE ? ",
(exchangeId, quoteAsset, 0, 'TRADING', '%SPOT%')
)
rows = dbCursor.fetchall()
return rows
except mariadb.Error as e:
helper = error_helper.ErrorHelper()
helper.code = e.errno
helper.msg = e.errmeg
helper.module = 'Symbol readAll'
helper.explanation = "SELECT SYMBOL"
helper.addData()
@staticmethod
def readAllByGroup(dbCursor=None, exchangeId=None, quoteAsset=None, marketGroup=None):
try:
dbCursor.execute(
"SELECT JSON_OBJECT('symbol', symbol, 'base', base_asset, 'quote', quote_asset, "
"'min_price', min_price, 'max_price', max_price, 'tick_size', tick_size, 'min_lot', min_lot, "
"'max_lot', max_lot, 'step_size', step_size, 'min_notional', min_notional ) "
"FROM symbol WHERE exchange_id=? AND quote_asset=? AND STATUS=? AND symbol_status=? "
" AND permissions LIKE ? AND market_group = ? ",
(exchangeId, quoteAsset, 0, 'TRADING', '%SPOT%', marketGroup)
)
rows = dbCursor.fetchall()
return rows
except mariadb.Error as e:
helper = error_helper.ErrorHelper()
helper.code = e.errno
helper.msg = e.errmeg
helper.module = 'Symbol readAll'
helper.explanation = "SELECT SYMBOL"
helper.addData()
@staticmethod
def readOne(dbCursor=None, exchangeId=None, symbol=None):
try:
dbCursor.execute(
"SELECT JSON_OBJECT('symbol', symbol, 'base', base_asset, 'quote', quote_asset, "
"'min_price', min_price, 'max_price', max_price, 'tick_size', tick_size, 'min_lot', min_lot, "
"'max_lot', max_lot, 'step_size', step_size, 'min_notional', min_notional ) "
"FROM symbol WHERE exchange_id=? AND symbol=? AND STATUS=? AND symbol_status=? "
" AND permissions LIKE ? ",
(exchangeId, symbol, 0, 'TRADING', '%SPOT%')
)
row = dbCursor.fetchone()
return row
except mariadb.Error as e:
helper = error_helper.ErrorHelper()
helper.code = e.errno
helper.msg = e.errmeg
helper.module = 'Symbol readOne'
helper.explanation = "SELECT SYMBOL"
helper.addData()
@staticmethod
def readExist(dbCursor=None, exchangeId=None, symbol=None):
try:
dbCursor.execute(
"SELECT JSON_OBJECT('symbol', symbol, 'status', status, 'market_group', market_group ) "
"FROM symbol WHERE exchange_id=? AND symbol=? ",
(exchangeId, symbol)
)
row = dbCursor.fetchone()
return row
except mariadb.Error as e:
helper = error_helper.ErrorHelper()
helper.code = e.errno
helper.msg = e.errmeg
helper.module = 'Symbol readExist'
helper.explanation = "SELECT SYMBOL"
helper.addData()
@staticmethod
def delete(dbCursor=None, exchangeId=None, symbol=None):
try:
dbCursor.execute(
"DELETE FROM symbol WHERE exchange_id=? AND symbol=? ",
(exchangeId, symbol)
)
except mariadb.Error as e:
helper = error_helper.ErrorHelper()
helper.code = e.errno
helper.msg = e.errmeg
helper.module = 'Symbol delete'
helper.explanation = "DELETE SYMBOL"
helper.addData()
class TriangularPair:
def __init__(self,
dbCursor=None,
exchangeId=None,
aPairSymbol=None,
aPairBase=None,
aPairQuote=None,
bPairSymbol=None,
bPairBase=None,
bPairQuote=None,
cPairSymbol=None,
cPairBase=None,
cPairQuote=None,
status=None
):
self.dbCursor = dbCursor
self.exchangeId = exchangeId
self.aPairSymbol = aPairSymbol
self.aPairBase = aPairBase
self.aPairQuote = aPairQuote
self.bPairSymbol = bPairSymbol
self.bPairBase = bPairBase
self.bPairQuote = bPairQuote
self.cPairSymbol = cPairSymbol
self.cPairBase = cPairBase
self.cPairQuote = cPairQuote
self.status = status
def addTriangularPair(self):
try:
self.dbCursor.execute(
"INSERT INTO triangular_pair (exchange_id, pair_a_symbol, pair_a_base, pair_a_quote, "
"pair_b_symbol, pair_b_base, pair_b_quote, pair_c_symbol, pair_c_base, pair_c_quote, status) "
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(self.exchangeId, self.aPairSymbol, self.aPairBase, self.aPairQuote, self.bPairSymbol,
self.bPairBase, self.bPairQuote, self.cPairSymbol, self.cPairBase, self.cPairQuote, self.status))
except mariadb.Error as e:
# print(f"Error: {e.errno} {e.errmsg}")
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "INSERT INTO triangular_pair"
log.addData()
def readAllPair(self, exchangeId=None, refSymbol=None):
try:
self.dbCursor.execute(
"SELECT JSON_OBJECT('pair_a_symbol', pair_a_symbol, 'pair_b_symbol', pair_b_symbol, "
"'pair_c_symbol', pair_c_symbol) "
"FROM triangular_pair WHERE exchange_id=? and pair_a_quote=? and status=0 ",
(exchangeId, refSymbol)
)
rows = self.dbCursor.fetchall()
return rows
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "SELECT all triangular_pair"
log.addData()
class BinanceSymbolPriceTicker:
def __init__(self,
dbCursor=None,
priceId=None,
priceTime=None,
symbol=None,
price=None,
sourceExchange="binance",
status=None,
updateDate=None,
updateTime=None
):
self.dbCursor = dbCursor
self.priceId = priceId
self.priceTime = priceTime
self.symbol = symbol
self.price = price
self.sourceExchange = sourceExchange
self.status = status
self.updateDate = updateDate
self.updateTime = updateTime
def getData(self, url=None):
dbCursor = self.dbCursor
prm = {'symbol': self.symbol}
try:
response = requests.get(url, params=prm)
response.raise_for_status()
records = response.json()
return records
# return records['result']['data']
except requests.exceptions.HTTPError as errh:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errh.response.status_code
log.errorMessage = errh.response.text
log.moduleName = type(self).__name__
log.explanation = "Http Error: " + errh.response.url
log.addData()
except requests.exceptions.ConnectionError as errc:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errc.response.status_code
log.errorMessage = errc.response.text
log.moduleName = type(self).__name__
log.explanation = "Error Connecting: " + errc.response.url
log.addData()
except requests.exceptions.Timeout as errt:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errt.response.status_code
log.errorMessage = errt.response.text
log.moduleName = type(self).__name__
log.explanation = "Timeout Error: " + errt.response.url
log.addData()
except requests.exceptions.RequestException as err:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = err.response.status_code
log.errorMessage = err.response.text
log.moduleName = type(self).__name__
log.explanation = err.response.url
log.addData()
def addData(self):
self.priceTime = datetime.now()
self.updateDate = datetime.now().strftime("%Y-%m-%d")
self.updateTime = datetime.now().strftime("%H:%M:%S")
self.status = 1
try:
self.dbCursor.execute(
"INSERT INTO current_price ( price_time, symbol, price, source_exchange, "
" status, update_date, update_time) "
"VALUES (?, ?, ?, ? ,?, ?, ?)",
(self.priceTime, self.symbol, self.price, self.sourceExchange,
self.status, self.updateDate, self.updateTime))
except mariadb.Error as e:
# print(f"Error: {e.errno} {e.errmsg}")
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "INSERT INTO current_price"
log.addData()
class BinanceBookTicker:
def __init__(self,
dbCursor=None,
symbol=None,
symbols=None,
bidPrice=None,
bidQty=None,
askPrice=None,
askQty=None
):
self.dbCursor = dbCursor
self.symbol = symbol
self.symbols = symbols
self.bidPrice = bidPrice
self.bidQty = bidQty
self.askPrice = askPrice
self.askQty = askQty
def getData(self, url=None):
dbCursor = self.dbCursor
prm = url
if self.symbols is not None:
prm = prm + '?symbols=['
itemLen = len(self.symbols)
for ix in range(itemLen):
prm = prm + '"' + self.symbols[ix] + '"'
if ix < itemLen - 1:
prm = prm + ','
prm = prm + ']'
try:
# response = requests.get(url, params=prm)
response = requests.get(url=prm)
response.raise_for_status()
records = response.json()
return records
# return records['result']['data']
except requests.exceptions.HTTPError as errh:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errh.response.status_code
log.errorMessage = errh.response.reason
log.moduleName = type(self).__name__
log.explanation = "Http Error: " + errh.response.url
log.addData()
except requests.exceptions.ConnectionError as errc:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errc.response.status_code
log.errorMessage = errc.response.text
log.moduleName = type(self).__name__
log.explanation = "Error Connecting: " + errc.response.url
log.addData()
except requests.exceptions.Timeout as errt:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errt.response.status_code
log.errorMessage = errt.response.text
log.moduleName = type(self).__name__
log.explanation = "Timeout Error: " + errt.response.url
log.addData()
except requests.exceptions.RequestException as err:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = err.response.status_code
log.errorMessage = err.response.text
log.moduleName = type(self).__name__
log.explanation = err.response.url
log.addData()
def getDataWithSession(self, session=None, url=None):
dbCursor = self.dbCursor
prm = url
if self.symbols is not None:
prm = prm + '?symbols=['
itemLen = len(self.symbols)
for ix in range(itemLen):
prm = prm + '"' + self.symbols[ix] + '"'
if ix < itemLen - 1:
prm = prm + ','
prm = prm + ']'
try:
# response = requests.get(url, params=prm)
response = session.get(url=prm)
response.raise_for_status()
records = response.json()
return records
# return records['result']['data']
except requests.exceptions.HTTPError as errh:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errh.response.status_code
log.errorMessage = errh.response.reason
log.moduleName = type(self).__name__
log.explanation = "Http Error: " + errh.response.url
log.addData()
except requests.exceptions.ConnectionError as errc:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errc.response.status_code
log.errorMessage = errc.response.text
log.moduleName = type(self).__name__
log.explanation = "Error Connecting: " + errc.response.url
log.addData()
except requests.exceptions.Timeout as errt:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errt.response.status_code
log.errorMessage = errt.response.text
log.moduleName = type(self).__name__
log.explanation = "Timeout Error: " + errt.response.url
log.addData()
except requests.exceptions.RequestException as err:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = err.response.status_code
log.errorMessage = err.response.text
log.moduleName = type(self).__name__
log.explanation = err.response.url
log.addData()
class BinanceCandlePrice:
def __init__(self,
dbCursor=None,
start_time=None,
close_time=None,
symbol=None,
candle_interval=None,
first_trade_id=None,
last_trade_id=None,
open_price=None,
close_price=None,
high_price=None,
low_price=None,
base_asset_volume=None,
number_of_trades=None,
quote_asset_volume=None,
taker_buy_base_asset_volume=None,
taker_buy_quote_asset_volume=None,
ignore_info=None,
source_exchange="binance",
update_time=None
):
self.dbCursor = dbCursor
self.start_time = start_time
self.close_time = close_time
self.symbol = symbol
self.candle_interval = candle_interval
self.first_trade_id = first_trade_id
self.last_trade_id = last_trade_id
self.open_price = open_price
self.close_price = close_price
self.high_price = high_price
self.low_price = low_price
self.base_asset_volume = base_asset_volume
self.number_of_trades = number_of_trades
self.quote_asset_volume = quote_asset_volume
self.taker_buy_base_asset_volume = taker_buy_base_asset_volume
self.taker_buy_quote_asset_volume = taker_buy_quote_asset_volume
self.ignore_info = ignore_info
self.source_exchange = source_exchange
self.update_time = update_time
def addData(self):
self.update_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
try:
self.dbCursor.execute(
"INSERT INTO candle_price (start_time, close_time, symbol, candle_interval, first_trade_id, "
" last_trade_id, open_price, close_price, high_price, low_price, base_asset_volume, number_of_trades,"
" quote_asset_volume, taker_buy_base_asset_volume, taker_buy_quote_asset_volume, "
" ignore_info, source_exchange, update_time) "
"VALUES (?, ?, ?, ? ,?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
(self.start_time, self.close_time, self.symbol, self.candle_interval, self.first_trade_id,
self.last_trade_id, self.open_price, self.close_price, self.high_price, self.low_price,
self.base_asset_volume, self.number_of_trades, self.quote_asset_volume,
self.taker_buy_base_asset_volume, self.taker_buy_quote_asset_volume, self.ignore_info,
self.source_exchange, self.update_time))
except mariadb.Error as e:
# print(f"Error: {e.errno} {e.errmsg}")
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "INSERT INTO candle_price"
log.addData()
def getData(self, url=None, symbol=None, candleInterval=None, startTime=None, endTime=None, limit=None):
dbCursor = self.dbCursor
prm = {}
if (startTime is None) and (endTime is None) and (limit is not None):
prm = {'symbol': symbol,
'interval': candleInterval,
# 'startTime': startTime,
# 'endTime': endTime,
'limit': limit
}
if (startTime is not None) and (endTime is None) and (limit is not None):
prm = {'symbol': symbol,
'interval': candleInterval,
'startTime': startTime,
'limit': limit
}
if (startTime is not None) and (endTime is None) and (limit is None):
prm = {'symbol': symbol,
'interval': candleInterval,
'startTime': startTime
}
if (startTime is not None) and (endTime is not None) and (limit is None):
prm = {'symbol': symbol,
'interval': candleInterval,
'startTime': startTime,
'endTime': endTime
}
if (startTime is not None) and (endTime is not None) and (limit is not None):
prm = {'symbol': symbol,
'interval': candleInterval,
'startTime': startTime,
'endTime': endTime,
'limit': limit
}
try:
response = requests.get(url, params=prm)
response.raise_for_status()
records = response.json()
return records
# return records['result']['data']
except requests.exceptions.HTTPError as errh:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = errh.response.status_code
log.errorMessage = errh.response.text
log.moduleName = type(self).__name__
log.explanation = "Http Error: " + errh.response.url
log.addData()
except requests.exceptions.ConnectionError as errc:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = errc.response.status_code
log.errorMessage = errc.response.text
log.moduleName = type(self).__name__
log.explanation = "Error Connecting: " + errc.response.url
log.addData()
except requests.exceptions.Timeout as errt:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = errt.response.status_code
log.errorMessage = errt.response.text
log.moduleName = type(self).__name__
log.explanation = "Timeout Error: " + errt.response.url
log.addData()
except requests.exceptions.RequestException as err:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = err.response.status_code
log.errorMessage = err.response.text + symbol
log.moduleName = type(self).__name__
log.explanation = err.response.url
log.addData()
def getDataWithSession(self, session=None, url=None, symbol=None, candleInterval=None, startTime=None, endTime=None, limit=None):
dbCursor = self.dbCursor
prm = {}
if (startTime is None) and (endTime is None) and (limit is not None):
prm = {'symbol': symbol,
'interval': candleInterval,
# 'startTime': startTime,
# 'endTime': endTime,
'limit': limit
}
if (startTime is not None) and (endTime is None) and (limit is not None):
prm = {'symbol': symbol,
'interval': candleInterval,
'startTime': startTime,
'limit': limit
}
if (startTime is not None) and (endTime is None) and (limit is None):
prm = {'symbol': symbol,
'interval': candleInterval,
'startTime': startTime
}
if (startTime is not None) and (endTime is not None) and (limit is None):
prm = {'symbol': symbol,
'interval': candleInterval,
'startTime': startTime,
'endTime': endTime
}
if (startTime is not None) and (endTime is not None) and (limit is not None):
prm = {'symbol': symbol,
'interval': candleInterval,
'startTime': startTime,
'endTime': endTime,
'limit': limit
}
try:
response = session.get(url, params=prm)
response.raise_for_status()
records = response.json()
return records
# return records['result']['data']
except requests.exceptions.HTTPError as errh:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = errh.response.status_code
log.errorMessage = errh.response.text
log.moduleName = type(self).__name__
log.explanation = "Http Error: " + errh.response.url
log.addData()
except requests.exceptions.ConnectionError as errc:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = errc.response.status_code
log.errorMessage = errc.response.text
log.moduleName = type(self).__name__
log.explanation = "Error Connecting: " + errc.response.url
log.addData()
except requests.exceptions.Timeout as errt:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = errt.response.status_code
log.errorMessage = errt.response.text
log.moduleName = type(self).__name__
log.explanation = "Timeout Error: " + errt.response.url
log.addData()
except requests.exceptions.RequestException as err:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = err.response.status_code
log.errorMessage = err.response.text + symbol
log.moduleName = type(self).__name__
log.explanation = err.response.url
log.addData()
def fetchWithLimit(self, symbol=None, candleInterval=None, startTime=None, limit=None):
try:
self.dbCursor.execute(
"SELECT * FROM "
"(SELECT JSON_OBJECT('start_time', start_time, 'close_time', close_time, 'symbol', symbol, "
"'open_price', open_price, 'close_price', close_price, 'high_price', high_price, "
"'low_price', low_price,"
"'base_asset_volume', base_asset_volume, 'number_of_trades', number_of_trades) "
"FROM candle_price "
"WHERE symbol=? AND candle_interval=? AND start_time<=? "
"ORDER BY start_time LIMIT ?) tbl "
" ORDER BY tbl.start_time asc",
(symbol, candleInterval, startTime, limit)
)
rows = self.dbCursor.fetchall()
return rows
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "fetchWithLimit candle_price"
log.addData()
def fetchWithLimitDf(self, symbol=None, candleInterval=None, startTime=None, limit=None):
try:
self.dbCursor.execute(
" SELECT * FROM "
" (SELECT start_time, close_time, symbol, open_price, close_price, high_price, "
" low_price, base_asset_volume, number_of_trades "
"FROM candle_price "
"WHERE symbol=? AND candle_interval=? AND start_time<=? "
"ORDER BY start_time desc LIMIT ?) tbl"
" ORDER BY tbl.start_time asc",
(symbol, candleInterval, startTime, limit)
)
rows = self.dbCursor.fetchall()
return rows
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "fetchWithLimitDf candle_price"
log.addData()
def fetchMinDate(self, symbol=None, candleInterval=None):
try:
self.dbCursor.execute(
"SELECT min(start_time) FROM candle_price WHERE symbol=? AND candle_interval=?",
(symbol, candleInterval,)
)
result = self.dbCursor.fetchone()
return result[0]
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "fetchMinDate candle_price"
log.addData()
def fetchMaxCloseTime(self, symbol=None, candleInterval=None):
try:
self.dbCursor.execute(
"SELECT max(close_time) FROM candle_price WHERE symbol=? AND candle_interval=?",
(symbol, candleInterval,)
)
result = self.dbCursor.fetchone()
return result[0]
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "fetchMaxCloseTime candle_price"
log.addData()
def fetchCount(self, symbol=None, candleInterval=None):
try:
self.dbCursor.execute(
"SELECT count(*) FROM candle_price WHERE symbol=? AND candle_interval=?",
(symbol, candleInterval,)
)
result = self.dbCursor.fetchone()
return result[0]
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "fetchCount candle_price"
log.addData()
def fetchStartRow(self, symbol=None, candleInterval=None, startTime=None, limit=None):
try:
self.dbCursor.execute(
"SELECT JSON_OBJECT('start_time', start_time, 'close_time', close_time, 'symbol', symbol, "
"'open_price', open_price, 'close_price', close_price, 'high_price', high_price, "
"'low_price', low_price,"
"'base_asset_volume', base_asset_volume, 'number_of_trades', number_of_trades) "
"FROM candle_price "
"WHERE symbol=? AND candle_interval=? AND start_time>=? "
"ORDER BY start_time LIMIT ?, 1 ",
(symbol, candleInterval, startTime, limit - 1)
)
result = self.dbCursor.fetchone()
return result
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "fetchStartRow candle_price"
log.addData()
def fetchAll(self, symbol=None, candleInterval=None, startTime=None):
try:
self.dbCursor.execute(
"SELECT JSON_OBJECT('start_time', start_time, 'close_time', close_time, 'symbol', symbol, "
"'open_price', open_price, 'close_price', close_price, 'high_price', high_price, "
"'low_price', low_price,"
"'base_asset_volume', base_asset_volume, 'number_of_trades', number_of_trades) "
"FROM candle_price "
"WHERE symbol=? AND candle_interval=? AND start_time>=? "
"ORDER BY start_time ",
(symbol, candleInterval, startTime)
)
rows = self.dbCursor.fetchall()
return rows
except mariadb.Error as e:
log = error.ErrorLog()
log.dbCursor = self.dbCursor
log.errorNo = e.errno
log.errorMessage = e.errmsg
log.moduleName = type(self).__name__
log.explanation = "fetchAll candle_price"
log.addData()
class BinanceOrderBook:
def getData(self, dbCursor=None, url=None, symbol=None, limit=None):
prm = {}
if limit is not None:
prm = {'symbol': symbol, 'limit': limit}
if limit is None:
prm = {'symbol': symbol}
try:
response = requests.get(url, params=prm)
response.raise_for_status()
records = response.json()
return records
# return records['symbols']
except requests.exceptions.HTTPError as errh:
log = error.ErrorLog()
log.dbCursor = dbCursor
log.errorNo = errh.response.status_code
log.errorMessage = errh.response.text
log.moduleName = type(self).__name__
log.explanation = "Http Error: " + errh.response.url