openfund-core 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. openfund/core/__init__.py +0 -0
  2. openfund/core/binance_tools/__init__.py +16 -0
  3. openfund/core/binance_tools/binance_tools.py +39 -0
  4. openfund/core/binance_tools/continuous_klines.py +147 -0
  5. openfund/core/factory.py +37 -0
  6. openfund/core/libs/__init__.py +6 -0
  7. openfund/core/libs/email_tools.py +56 -0
  8. openfund/core/libs/enums.py +507 -0
  9. openfund/core/libs/file_tools.py +13 -0
  10. openfund/core/libs/log_tools.py +45 -0
  11. openfund/core/libs/prepare_env.py +28 -0
  12. openfund/core/libs/time.py +14 -0
  13. openfund/core/libs/time_tools.py +22 -0
  14. openfund/core/openfund_old/__init__.py +0 -0
  15. openfund/core/openfund_old/continuous_klines.py +153 -0
  16. openfund/core/openfund_old/depth.py +92 -0
  17. openfund/core/openfund_old/historical_trades.py +123 -0
  18. openfund/core/openfund_old/index_info.py +67 -0
  19. openfund/core/openfund_old/index_price_kline.py +118 -0
  20. openfund/core/openfund_old/klines.py +95 -0
  21. openfund/core/openfund_old/klines_qrr.py +103 -0
  22. openfund/core/openfund_old/mark_price.py +121 -0
  23. openfund/core/openfund_old/mark_price_klines.py +122 -0
  24. openfund/core/openfund_old/ticker_24hr_price_change.py +99 -0
  25. openfund/core/pyopenfund.py +32 -0
  26. openfund/core/sample/__init__.py +1 -0
  27. openfund/core/sample/sample.py +20 -0
  28. openfund/core/sycu_exam/__init__.py +1 -0
  29. openfund/core/sycu_exam/exam.py +19 -0
  30. openfund/core/sycu_exam/random_grade_cplus.py +440 -0
  31. openfund/core/sycu_exam/random_grade_web.py +404 -0
  32. openfund_core-0.0.2.dist-info/LICENSE +201 -0
  33. openfund_core-0.0.2.dist-info/METADATA +66 -0
  34. openfund_core-0.0.2.dist-info/RECORD +35 -0
  35. openfund_core-0.0.2.dist-info/WHEEL +4 -0
@@ -0,0 +1,153 @@
1
+ #!/usr/bin/env python
2
+ import csv
3
+ import logging
4
+ import time
5
+ import os
6
+ import sys
7
+
8
+
9
+ curPath = os.path.abspath(os.path.dirname(__file__))
10
+ rootPath = os.path.split(curPath)[0]
11
+ sys.path.append(rootPath)
12
+ from datetime import datetime
13
+
14
+ from binance.um_futures import UMFutures
15
+ from binance.um_futures import UMFutures
16
+ from binance.error import ClientError
17
+
18
+ from libs.time_tools import format_timestamp
19
+ from libs.file_tools import create_path
20
+ from libs.prepare_env import get_api_key, get_path
21
+ from libs import enums
22
+
23
+ # 数据路径、日志路径
24
+ data_path, log_path = get_path()
25
+ # client
26
+ um_futures_client = UMFutures()
27
+ # 合同类型
28
+ contractTypes = [type.value for type in enums.ContractType]
29
+ # 币种类型
30
+ # POOL = enums.CUR_SYMBOL_POOL
31
+ POOL = [
32
+ "BTCUSDT_240329",
33
+ "BLURUSDT",
34
+ "DYDXUSDT",
35
+ "ETHBTC",
36
+ "ETHBUSD",
37
+ "ETHUSDT",
38
+ "ETHUSDT_231229",
39
+ "ETHUSDT_240329",
40
+ "GMTBUSD",
41
+ "GMTUSDT",
42
+ "LTCBUSD",
43
+ "LTCUSDT",
44
+ "MATICBUSD",
45
+ "MATICUSDT",
46
+ "SOLBUSD",
47
+ "SOLUSDT",
48
+ ]
49
+ interval = enums.KLINE_INTERVAL_5MINUTE
50
+ limit = 1500
51
+ errorLimit = 100
52
+ sleepSec = 10
53
+
54
+ # 历史截止数据开关
55
+ hisSwitch = 0
56
+ # hisSwitch 打开的情况下,抓取数据截止时间
57
+ hisDateTime = 1653974399999
58
+
59
+ for symbol in POOL:
60
+ fileName = "{}/continuous_klines_{}_{}.log".format(
61
+ log_path, symbol, format_timestamp(datetime.now().timestamp() * 1000)
62
+ )
63
+ # print(fileName)
64
+ logging.basicConfig(
65
+ format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
66
+ datefmt="%Y-%m-%d %H:%M:%S",
67
+ level=logging.INFO,
68
+ filename=fileName,
69
+ )
70
+ logging.info("{} symbol 开始 ++++++++++++++++++++++++++++ ".format(symbol))
71
+ total = 0
72
+ for contractType in contractTypes:
73
+ latestRecords = 1
74
+ records = 0 # 累计记录数
75
+ queryTimes = 0 # 执行次数
76
+ nextEndTime = 0
77
+ errorCount = 0
78
+ params = {"limit": limit}
79
+ while latestRecords != 0: # 循环读取,直到记录为空
80
+ queryTimes = queryTimes + 1
81
+ if nextEndTime != 0:
82
+ params = {"limit": limit, "endTime": nextEndTime}
83
+
84
+ logging.info(
85
+ "1、{}-{} 第{}次开始执行...".format(symbol, contractType, queryTimes)
86
+ )
87
+ listData = []
88
+ try:
89
+ listData = um_futures_client.continuous_klines(
90
+ symbol, contractType, interval, **params
91
+ )
92
+ except KeyError as err:
93
+ print("KeyError:", err)
94
+ logging.error(err)
95
+ break
96
+ except ClientError as error:
97
+ logging.error(
98
+ "Found error. status: {}, error code: {}, error message: {}".format(
99
+ error.status_code, error.error_code, error.error_message
100
+ )
101
+ )
102
+ if error.error_code == -4144 and error.status_code == 400:
103
+ break
104
+ except Exception as e:
105
+ print("Error:", e)
106
+ logging.error(e)
107
+ errorCount = errorCount + 1
108
+ if errorCount > errorLimit:
109
+ break
110
+ else:
111
+ time.sleep(sleepSec)
112
+ continue
113
+
114
+ latestRecords = len(listData)
115
+ records = latestRecords + records
116
+ logging.info("2、{}条写入文件...".format(latestRecords))
117
+
118
+ path = "{}/continuous_klines/{}/{}/".format(data_path, symbol, contractType)
119
+ create_path(path) # 不存在路径进行呢创建
120
+
121
+ with open(
122
+ "{}continuous_klines_{}_{}_{}.csv".format(
123
+ path, symbol, contractType, interval
124
+ ),
125
+ "a",
126
+ newline="",
127
+ ) as file:
128
+ writer = csv.writer(file)
129
+ # 时间戳倒序,插入文件尾部
130
+ writer.writerows(sorted(listData, key=lambda x: x[0], reverse=True))
131
+
132
+ # 拿到最后一条记录后,获取close时间戳,变为下一次截止时间戳
133
+ if latestRecords > 0:
134
+ nextEndTime = (
135
+ listData[0][0] - 1
136
+ ) # -1 不和close时间戳相同,避免重新拉取重复数据
137
+ errorCount = 0
138
+ logging.info(
139
+ "3、下次结束时间 {} {}".format(
140
+ format_timestamp(nextEndTime), nextEndTime
141
+ )
142
+ )
143
+
144
+ if nextEndTime <= hisDateTime and hisSwitch == 1:
145
+ break
146
+ else:
147
+ logging.info("4、结束...")
148
+
149
+ total = total + records
150
+ logging.info("5、{} 抓取数据 {} 条记录...".format(symbol, records))
151
+
152
+ logging.info("6、{} 抓取数据 {} 条记录...".format(symbol, total))
153
+ logging.info("{} symbol --------------------------------- ".format(symbol))
@@ -0,0 +1,92 @@
1
+ #!/usr/bin/env python
2
+ import csv
3
+ import time
4
+ import os
5
+ import sys
6
+ import json
7
+ import schedule
8
+
9
+ curPath = os.path.abspath(os.path.dirname(__file__))
10
+ rootPath = os.path.split(curPath)[0]
11
+ sys.path.append(rootPath)
12
+
13
+
14
+ from datetime import datetime
15
+ from binance.um_futures import UMFutures
16
+ from binance.error import ClientError
17
+ from libs.time_tools import format_timestamp, format_date
18
+ from libs.file_tools import create_path
19
+ from libs.prepare_env import get_api_key, get_path
20
+ from libs import enums
21
+ from libs.log_tools import Logger
22
+
23
+ data_path, log_path = get_path()
24
+
25
+ um_futures_client = UMFutures()
26
+
27
+ POOL = enums.NEW_SYMBOL_POLL
28
+ interval = enums.KLINE_INTERVAL_5MINUTE
29
+ # 历史截止数据开关
30
+ hisSwitch = 0
31
+ # hisSwitch 打开的情况下,抓取数据截止时间
32
+ hisDateTime = 1653974399999
33
+ # 发现异常后累计失败次数上限,超过后退出。
34
+ errorLimit = 100
35
+ # 异常后暂停秒数
36
+ sleepSec = 10
37
+ # 下次执行周期 5min
38
+ nextTimeMin = 5
39
+
40
+ app = "depth"
41
+ logger = Logger(app).get_log()
42
+
43
+
44
+ # logging.basicConfig(
45
+ # format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
46
+ # datefmt="%Y-%m-%d %H:%M:%S",
47
+ # level=logging.INFO,
48
+ # filename="{}/{}_{}.log".format(
49
+ # log_path, app, format_timestamp(datetime.now().timestamp() * 1000)
50
+ # ),
51
+ # )
52
+ def job():
53
+ logger.info("{} app 开始 ++++++++++++++++++++++++++++ ".format(app))
54
+ latestRecords = 1
55
+ params = {"limit": 1000}
56
+ for symbol in POOL:
57
+ queryTimes = queryTimes + 1
58
+ logger.info("1、{}第{}次开始执行...".format(symbol, queryTimes))
59
+ listData = []
60
+ try:
61
+ listData = um_futures_client.depth(symbol, **params)
62
+ except Exception as e:
63
+ logger.error(e)
64
+ time.sleep(sleepSec)
65
+ continue
66
+
67
+ latestRecords = len(listData)
68
+ records = latestRecords + records
69
+ logger.info("2、{}条写入文件...".format(latestRecords))
70
+
71
+ path = "{}/{}/".format(data_path, app)
72
+ create_path(path) # 不存在路径进行呢创建
73
+
74
+ with open(
75
+ "{}{}_{}.txt".format(
76
+ path,
77
+ app,
78
+ format_date(datetime.now().timestamp() * 1000),
79
+ ),
80
+ "a",
81
+ ) as file:
82
+ file.writelines(json.dumps(listData) + "\r\n")
83
+
84
+ logger.info("3、本次 {} 抓取数据 {} 条记录...".format(app, records))
85
+ logger.info("{} app --------------------------------- ".format(app))
86
+
87
+
88
+ if __name__ == "__main__":
89
+ schedule.every(nextTimeMin).minutes.do(job)
90
+ logger.info("Schedule Starting {0}min ...... ".format(nextTimeMin))
91
+ while True:
92
+ schedule.run_pending() # 运行所有可运行的任务
@@ -0,0 +1,123 @@
1
+ #!/usr/bin/env python
2
+ import csv
3
+ import logging
4
+ import time
5
+ import os
6
+ import sys
7
+
8
+ from datetime import datetime
9
+
10
+ from binance.lib.utils import config_logging
11
+ from binance.um_futures import UMFutures
12
+ from binance.error import ClientError, Error
13
+
14
+ import enums as enums
15
+ from time_tools import format_timestamp
16
+ from file_tools import create_path
17
+ from prepare_env import get_api_key, get_path
18
+
19
+ # config_logging(logging, logging.INFO)
20
+ api_key, api_secret = get_api_key()
21
+ um_futures_client = UMFutures(key=api_key)
22
+
23
+ data_path, log_path = get_path()
24
+ # POOL = ['AAVEUSDT','BTCBUSD', 'BTCDOMUSDT', 'BTCSTUSDT', 'BTCUSDT', 'BTCUSDT_231229', 'BTCUSDT_240329',
25
+ # 'BLURUSDT', 'DYDXUSDT', 'ETHBTC', 'ETHBUSD', 'ETHUSDT', 'ETHUSDT_231229', 'ETHUSDT_240329',
26
+ # 'GMTBUSD', 'GMTUSDT', 'LTCBUSD', 'LTCUSDT', 'MATICBUSD', 'MATICUSDT', 'SOLBUSD', 'SOLUSDT',
27
+ # ]
28
+ POOL = ["GMTBUSD"]
29
+
30
+ # 历史截止数据开关
31
+ hisSwitch = 1
32
+ # hisSwitch 打开的情况下,抓取数据截止时间
33
+ hisDateTime = 1653974399999
34
+
35
+ for symbol in POOL:
36
+ logging.basicConfig(
37
+ format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
38
+ datefmt="%Y-%m-%d %H:%M:%S",
39
+ level=logging.INFO,
40
+ filename="{}/{}_historical_trades_{}.log".format(
41
+ log_path, symbol, format_timestamp(datetime.now().timestamp() * 1000)
42
+ ),
43
+ )
44
+ logging.info("{} symbol 开始 ++++++++++++++++++++++++++++ ".format(symbol))
45
+
46
+ latestRecords = 1
47
+ records = 0 # 累计记录数
48
+ queryTimes = 0 # 执行次数
49
+ nextKey = 0
50
+ params = {"limit": 1000}
51
+
52
+ while latestRecords != 0: # 循环读取,直到记录为空
53
+ queryTimes = queryTimes + 1
54
+ if nextKey != 0:
55
+ params = {"limit": 1000, "fromId": nextKey}
56
+
57
+ logging.info("1、{}第{}次开始执行...".format(symbol, queryTimes))
58
+ listData = []
59
+ try:
60
+ listData = um_futures_client.historical_trades(symbol, **params)
61
+ # except ClientError as error:
62
+ # logging.error(
63
+ # "Found error. status: {}, error code: {}, error message: {}".format(
64
+ # error.status_code, error.error_code, error.error_message
65
+ # )
66
+ # )
67
+ # time.sleep(30)
68
+ # continue
69
+ # except ProxyError as error:
70
+ # logging.error(
71
+ # "Found error. error code: {}, error message: {}".format(
72
+ # error, error.error_message
73
+ # )
74
+ # )
75
+ # time.sleep(10)
76
+ # continue
77
+ except Exception as e:
78
+ print("Error:", e)
79
+ logging.error(e)
80
+ time.sleep(10)
81
+ continue
82
+ # listData 结构
83
+ # [
84
+ # {
85
+ # "id": 28457,
86
+ # "price": "4.00000100",
87
+ # "qty": "12.00000000",
88
+ # "quoteQty": "8000.00",
89
+ # "time": 1499865549590,
90
+ # "isBuyerMaker": true,
91
+ # }
92
+ # ]
93
+ latestRecords = len(listData)
94
+ records = latestRecords + records
95
+ logging.info("2、{}条写入文件...".format(latestRecords))
96
+
97
+ path = "{}/historical_trades/{}/".format(data_path, symbol)
98
+
99
+ create_path(path) # 不存在路径进行呢创建
100
+
101
+ with open(
102
+ "{}/{}_historical_trades.csv".format(path, symbol), "a", newline=""
103
+ ) as file:
104
+ writer = csv.writer(file)
105
+ # 时间戳倒序,插入文件尾部
106
+ writer.writerows(sorted(listData, key=lambda x: x["id"], reverse=True))
107
+
108
+ # 拿到最后一条记录后,获取close时间戳,变为下一次截止时间戳
109
+ if latestRecords > 0:
110
+ first = listData[0]
111
+ nextKey = first["id"] - 1000
112
+ curTime = first["time"]
113
+ logging.info("3、下个Key {} {}".format(format_timestamp(curTime), nextKey))
114
+ errorCount = 0
115
+ if curTime <= hisDateTime and hisSwitch == 1:
116
+ break
117
+ else:
118
+ logging.info("4、结束...")
119
+
120
+ time.sleep(0.01)
121
+
122
+ logging.info("5、{} 抓取数据 {} 条记录...".format(symbol, records))
123
+ logging.info("{} symbol --------------------------------- ".format(symbol))
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env python
2
+ import csv
3
+ import time
4
+ import os
5
+ import sys
6
+ import json
7
+ import schedule
8
+
9
+ curPath = os.path.abspath(os.path.dirname(__file__))
10
+ rootPath = os.path.split(curPath)[0]
11
+ sys.path.append(rootPath)
12
+
13
+
14
+ from datetime import datetime
15
+ from binance.um_futures import UMFutures
16
+ from binance.error import ClientError
17
+ from utils.time_tools import format_timestamp, format_date, format_date_to
18
+ from utils.file_tools import create_path
19
+ from utils.prepare_env import get_api_key, get_path
20
+ from utils import enums
21
+ from utils.log_tools import Logger
22
+
23
+ data_path, log_path = get_path()
24
+ um_futures_client = UMFutures()
25
+
26
+ # 下次执行周期 5min
27
+ nextTimeMin = 5
28
+
29
+ app = "index_info"
30
+ logger = Logger(app).get_log()
31
+
32
+
33
+ def job():
34
+ logger.info("{} app 开始 ++++++++++++++++++++++++++++ ".format(app))
35
+ listData = []
36
+ try:
37
+ listData = um_futures_client.index_info()
38
+ except Exception as e:
39
+ print("Error:", e)
40
+ logger.error(e)
41
+
42
+ latestRecords = len(listData)
43
+
44
+ path = "{}/{}/".format(data_path, app)
45
+ create_path(path) # 不存在路径进行呢创建
46
+
47
+ with open(
48
+ "{}{}_{}.txt".format(
49
+ path,
50
+ app,
51
+ format_date(datetime.now().timestamp() * 1000),
52
+ ),
53
+ "a",
54
+ ) as file:
55
+ file.writelines(
56
+ json.dumps(sorted(listData, key=lambda x: x["symbol"])) + "\r\n"
57
+ )
58
+
59
+ logger.info("1、本次 {} 抓取数据 {} 条记录...".format(app, records))
60
+ logger.info("{} app --------------------------------- ".format(app))
61
+
62
+
63
+ if __name__ == "__main__":
64
+ schedule.every(nextTimeMin).minutes.do(job)
65
+ logger.info("Schedule Starting {0}min ...... ".format(nextTimeMin))
66
+ while True:
67
+ schedule.run_pending() # 运行所有可运行的任务
@@ -0,0 +1,118 @@
1
+ #!/usr/bin/env python
2
+ import csv
3
+ import logging
4
+ import time
5
+ import os
6
+ import sys
7
+
8
+ curPath = os.path.abspath(os.path.dirname(__file__))
9
+ rootPath = os.path.split(curPath)[0]
10
+ sys.path.append(rootPath)
11
+
12
+
13
+ from datetime import datetime
14
+ from binance.um_futures import UMFutures
15
+ from binance.error import ClientError
16
+ from utils.time_tools import format_timestamp
17
+ from utils.file_tools import create_path
18
+ from utils.prepare_env import get_api_key, get_path
19
+ from utils import enums
20
+
21
+ data_path, log_path = get_path()
22
+ um_futures_client = UMFutures()
23
+
24
+ POOL = enums.CUR_SYMBOL_POOL
25
+ interval = enums.KLINE_INTERVAL_5MINUTE
26
+ # 历史截止数据开关
27
+ hisSwitch = 0
28
+ # hisSwitch 打开的情况下,抓取数据截止时间
29
+ hisDateTime = 1653974399999
30
+ # 发现异常后累计失败次数上限,超过后退出。
31
+ errorLimit = 100
32
+ # 异常后暂停秒数
33
+ sleepSec = 10
34
+
35
+ app = "index_price_kline"
36
+
37
+ for symbol in POOL:
38
+ fileName = "{}/{}_{}_{}.log".format(
39
+ log_path, symbol, app, format_timestamp(datetime.now().timestamp() * 1000)
40
+ )
41
+ logging.basicConfig(
42
+ format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
43
+ datefmt="%Y-%m-%d %H:%M:%S",
44
+ level=logging.INFO,
45
+ filename=fileName,
46
+ )
47
+ logging.info("{}_symbol 开始 ++++++++++++++++++++++++++++ ".format(symbol))
48
+
49
+ latestRecords = 1
50
+ records = 0 # 累计记录数
51
+ queryTimes = 0 # 执行次数
52
+ nextEndTime = 0 # 下次结束时间
53
+ errorCount = 0 # 异常次数
54
+ params = {"limit": 1000}
55
+ while latestRecords != 0: # 循环读取,直到记录为空
56
+ queryTimes = queryTimes + 1
57
+ if nextEndTime != 0:
58
+ params = {"limit": 1000, "endTime": nextEndTime}
59
+
60
+ logging.info("1、{}第{}次开始执行...".format(symbol, queryTimes))
61
+ listData = []
62
+ try:
63
+ listData = um_futures_client.index_price_klines(symbol, interval, **params)
64
+ except KeyError as err:
65
+ print("KeyError:", err)
66
+ logging.error(err)
67
+ break
68
+ except ClientError as error:
69
+ logging.error(
70
+ "Found error. status: {}, error code: {}, error message: {}".format(
71
+ error.status_code, error.error_code, error.error_message
72
+ )
73
+ )
74
+ if error.error_code == -4144 and error.status_code == 400:
75
+ break
76
+ except Exception as e:
77
+ print("Error:", e)
78
+ logging.error(e)
79
+ errorCount = errorCount + 1
80
+ if errorCount > errorLimit:
81
+ break
82
+ else:
83
+ time.sleep(sleepSec)
84
+ continue
85
+
86
+ latestRecords = len(listData)
87
+ records = latestRecords + records
88
+ logging.info("2、{}条写入文件...".format(latestRecords))
89
+
90
+ path = "{}/{}/{}/".format(data_path, app, symbol)
91
+ create_path(path) # 不存在路径进行呢创建
92
+
93
+ with open(
94
+ "{}{}_{}_{}.csv".format(path, app, symbol, interval),
95
+ "a",
96
+ newline="",
97
+ ) as file:
98
+ writer = csv.writer(file)
99
+ # 时间戳倒序,插入文件尾部
100
+ writer.writerows(sorted(listData, key=lambda x: x[0], reverse=True))
101
+
102
+ # 拿到最后一条记录后,获取close时间戳,变为下一次截止时间戳
103
+ if latestRecords > 0:
104
+ nextEndTime = listData[0][0] - 1 # -1 不和close时间戳相同,避免重新拉取重复数据
105
+ errorCount = 0
106
+ logging.info(
107
+ "3、下次结束时间 {} {}".format(format_timestamp(nextEndTime), nextEndTime)
108
+ )
109
+
110
+ if nextEndTime <= hisDateTime and hisSwitch == 1:
111
+ break
112
+ else:
113
+ logging.info("4、结束...")
114
+
115
+ # time.sleep(0.1)
116
+
117
+ logging.info("5、{} 抓取数据 {} 条记录...".format(symbol, records))
118
+ logging.info("{} symbol --------------------------------- ".format(symbol))
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env python
2
+ import csv
3
+ import logging
4
+ import time
5
+ import os
6
+ import sys
7
+
8
+ curPath = os.path.abspath(os.path.dirname(__file__))
9
+ # print ("curPath:",curPath)
10
+ rootPath = os.path.split(curPath)[0]
11
+ # print ("rootPath:",rootPath)
12
+ sys.path.append(rootPath)
13
+
14
+
15
+ from datetime import datetime
16
+ from binance.um_futures import UMFutures
17
+ from binance.error import ClientError
18
+ from utils.time_tools import format_timestamp
19
+ from utils.file_tools import create_path
20
+ from utils.prepare_env import get_api_key, get_path
21
+ from utils import enums
22
+
23
+ data_path, log_path = get_path()
24
+
25
+
26
+ # config_logging(logging, logging.INFO, "../../log/future/klines.log")
27
+
28
+ um_futures_client = UMFutures()
29
+
30
+ POOL = ["AAVEUSDT"]
31
+ interval = enums.KLINE_INTERVAL_5MINUTE
32
+ # 历史截止数据开关
33
+ hisSwitch = 0
34
+ # hisSwitch 打开的情况下,抓取数据截止时间
35
+ hisDateTime = 1653974399999
36
+
37
+ logging.basicConfig(
38
+ format="%(asctime)s %(name)s:%(levelname)s:%(message)s",
39
+ datefmt="%Y-%m-%d %H:%M:%S",
40
+ level=logging.INFO,
41
+ filename="{}/klines_{}.log".format(
42
+ log_path, format_timestamp(datetime.now().timestamp() * 1000)
43
+ ),
44
+ )
45
+ logging.info("{} symbol 开始 ++++++++++++++++++++++++++++ ".format(symbol))
46
+ for symbol in POOL:
47
+ latestRecords = 1
48
+ records = 0 # 累计记录数
49
+ queryTimes = 0 # 执行次数
50
+ nextEndTime = 0
51
+ params = {"limit": 1000}
52
+ while latestRecords != 0: # 循环读取,直到记录为空
53
+ queryTimes = queryTimes + 1
54
+ if nextEndTime != 0:
55
+ params = {"limit": 1000, "endTime": nextEndTime}
56
+
57
+ logging.info("1、{}第{}次开始执行...".format(symbol, queryTimes))
58
+ listData = []
59
+ try:
60
+ listData = um_futures_client.klines(symbol, interval, **params)
61
+ except Exception as e:
62
+ print("Error:", e)
63
+ logging.error(e)
64
+ time.sleep(10)
65
+ continue
66
+
67
+ latestRecords = len(listData)
68
+ records = latestRecords + records
69
+ logging.info("2、{}条写入文件...".format(latestRecords))
70
+
71
+ path = "{}/klines/{}/".format(data_path, symbol)
72
+ create_path(path) # 不存在路径进行呢创建
73
+
74
+ with open("{}klines_{}.csv".format(path, interval), "a", newline="") as file:
75
+ writer = csv.writer(file)
76
+ # 时间戳倒序,插入文件尾部
77
+ writer.writerows(sorted(listData, key=lambda x: x[0], reverse=True))
78
+
79
+ # 拿到最后一条记录后,获取close时间戳,变为下一次截止时间戳
80
+ if latestRecords > 0:
81
+ nextEndTime = listData[0][0] - 1 # -1 不和close时间戳相同,避免重新拉取重复数据
82
+ errorCount = 0
83
+ logging.info(
84
+ "3、下次结束时间 {} {}".format(format_timestamp(nextEndTime), nextEndTime)
85
+ )
86
+
87
+ if nextEndTime <= hisDateTime and hisSwitch == 1:
88
+ break
89
+ else:
90
+ logging.info("4、结束...")
91
+
92
+ # time.sleep(0.1)
93
+
94
+ logging.info("5、{} 抓取数据 {} 条记录...".format(symbol, records))
95
+ logging.info("{} symbol --------------------------------- ".format(symbol))