forked from cyberjunky/3commas-cyber-bots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
botwatcher.py
executable file
·345 lines (275 loc) · 10 KB
/
botwatcher.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
#!/usr/bin/env python3
"""Cyberjunky's 3Commas bot helpers."""
import argparse
import configparser
import os
import sqlite3
import sys
import time
from pathlib import Path
from helpers.logging import Logger, NotificationHandler
from helpers.datasources import (
get_shared_bot_data
)
from helpers.misc import (
remove_prefix,
wait_time_interval,
)
def load_config():
"""Create default or load existing config file."""
cfg = configparser.ConfigParser()
if cfg.read(f"{datadir}/{program}.ini"):
return cfg
cfg["settings"] = {
"timezone": "Europe/Amsterdam",
"timeinterval": 86400,
"debug": False,
"logrotate": 7,
"notifications": False,
"notify-urls": ["notify-url1"],
}
cfg["botwatch_12345"] = {
"secret": "secret",
"notify-pairs": "True",
}
with open(f"{datadir}/{program}.ini", "w") as cfgfile:
cfg.write(cfgfile)
return None
def upgrade_config(thelogger, cfg):
"""Upgrade config file if needed."""
for cfgsection in cfg.sections():
if cfgsection.startswith("botwatch_") and not cfg.has_option(cfgsection, "notify-pairs"):
cfg.set(cfgsection, "notify-pairs", "True")
cfg.set(cfgsection, "comment", "")
with open(f"{datadir}/{program}.ini", "w+") as cfgfile:
cfg.write(cfgfile)
thelogger.info(
f"Upgraded section {cfgsection} to have 'notify-pairs' and 'comment' property"
)
return cfg
def get_fields_and_types():
"""Get the data fields and there type"""
datafields = {}
datafields["bot_id"] = "INT"
datafields["active_safety_orders_count"] = "INT"
datafields["allowed_deals_on_same_pair"] = "INT"
datafields["bot_pair_or_pairs"] = "STRING"
datafields["enabled"] = "BIT"
datafields["martingale_step_coefficient"] = "FLOAT"
datafields["martingale_volume_coefficient"] = "FLOAT"
datafields["max_active_deals"] = "INT"
datafields["max_safety_orders"] = "INT"
datafields["min_volume_btc_24h"] = "INT"
datafields["profit_currency"] = "STRING"
datafields["safety_order_step_percentage"] = "FLOAT"
datafields["strategy"] = "STRING"
datafields["strategy_list"] = "STRING"
datafields["take_profit"] = "FLOAT"
datafields["take_profit_type"] = "STRING"
return datafields
def get_db_data(bot_id):
"""Get the saved dataset for the specified bot."""
record = cursor.execute(
f"SELECT * FROM bot_data "
f"WHERE bot_id = {bot_id}"
).fetchone()
return record
def store_bot_data(bot_data):
"""Store the latest data for the specified bot."""
datadef = get_fields_and_types()
values = []
for field, fieldtype in datadef.items():
# Some fields require specific handling, others can be added directly
if field in ("bot_pair_or_pairs", "strategy_list"):
values.append(str(bot_data[field])[1:-1])
else:
if fieldtype == "STRING":
if bot_data[field] is None:
values.append("None")
else:
values.append(str(bot_data[field]))
elif fieldtype == "FLOAT":
if bot_data[field] is None:
values.append(-1.0)
else:
values.append(float(bot_data[field]))
else:
if bot_data[field] is None:
values.append(-1)
else:
values.append(int(bot_data[field]))
db.execute(
f"INSERT OR REPLACE INTO bot_data ({str(datadef.keys())[11:-2]}) "
f"VALUES ({str(values)[1:-1]})"
)
db.commit()
logger.info(
f"Stored latest data for bot '{bot_data['bot_name']}' in database"
)
def process_shared_bot_data(cfg, data, bot_id):
"""Process the downloaded data."""
storeconfig = False
notifypairs = cfg.getboolean(
f"botwatch_{bot_id}", "notify-pairs", fallback = True
)
botinfo = data['bot_info']
dbdata = get_db_data(bot_id)
if dbdata:
# Compare the latest data with the saved data for changes
logger.info(
f"Comparing old and new data for bot \'{botinfo['bot_name']}\' ({bot_id})"
)
index = 0
datadef = get_fields_and_types()
for field, fieldtype in datadef.items():
old = None
new = None
if field in ("bot_pair_or_pairs", "strategy_list"):
old = str(dbdata[index])
if botinfo[field] is None:
new = "None"
else:
new = str(botinfo[field])[1:-1]
elif fieldtype == "FLOAT":
old = float(dbdata[index])
if botinfo[field] is None:
new = -1.0
else:
new = float(botinfo[field])
else:
old = dbdata[index]
if botinfo[field] is None:
new = -1
else:
new = botinfo[field]
if old != new:
storeconfig = True
# Option to disable some notifications, because some fields can change (like pairs)
# Store the changed config, could be usefull later for future development
notifychange = True
if field == "bot_pair_or_pairs" and not notifypairs:
notifychange = False
if notifychange:
logger.info(
f"\'{botinfo['bot_name']}\' ({bot_id}): {field} changed "
f"from: \n{old}\n to: \n{new}",
True
)
index += 1
else:
storeconfig = True
logger.info(
f"New bot to watch: '{botinfo['bot_name']}' (id: {botinfo['bot_id']}). Store current "
f"configuration only.",
True
)
# Store data if new bot or configuration has changed
if storeconfig:
store_bot_data(botinfo)
def init_botwatcher_db():
"""Create or open database to store bot data."""
try:
dbname = f"{program}.sqlite3"
dbpath = f"file:{datadir}/{dbname}?mode=rw"
dbconnection = sqlite3.connect(dbpath, uri=True)
dbconnection.row_factory = sqlite3.Row
logger.info(f"Database '{datadir}/{dbname}' opened successfully")
except sqlite3.OperationalError:
dbconnection = sqlite3.connect(f"{datadir}/{dbname}")
dbconnection.row_factory = sqlite3.Row
dbcursor = dbconnection.cursor()
logger.info(f"Database '{datadir}/{dbname}' created successfully")
datadef = get_fields_and_types()
tablestructure = ""
for field, fieldtype in datadef.items():
if tablestructure:
tablestructure += ", "
tablestructure += field + " " + fieldtype
if field == "bot_id":
tablestructure += " PRIMARY KEY"
dbcursor.execute(
f"CREATE TABLE bot_data ("
f"{tablestructure}"
f")"
)
logger.info("Database tables created successfully")
return dbconnection
# Start application
program = Path(__file__).stem
# Parse and interpret options.
parser = argparse.ArgumentParser(description="Cyberjunky's 3Commas bot helper.")
parser.add_argument(
"-d", "--datadir", help="directory to use for config and logs files", type=str
)
args = parser.parse_args()
if args.datadir:
datadir = args.datadir
else:
datadir = os.getcwd()
# Create or load configuration file
config = load_config()
if not config:
# Initialise temp logging
logger = Logger(datadir, program, None, 7, False, False)
logger.info(
f"Created example config file '{datadir}/{program}.ini', edit it and restart the program"
)
sys.exit(0)
else:
# Handle timezone
if hasattr(time, "tzset"):
os.environ["TZ"] = config.get(
"settings", "timezone", fallback="Europe/Amsterdam"
)
time.tzset()
# Init notification handler
notification = NotificationHandler(
program,
config.getboolean("settings", "notifications"),
config.get("settings", "notify-urls"),
)
# Initialise logging
logger = Logger(
datadir,
program,
notification,
int(config.get("settings", "logrotate", fallback=7)),
config.getboolean("settings", "debug"),
config.getboolean("settings", "notifications"),
)
# Upgrade config file if needed
config = upgrade_config(logger, config)
logger.info(f"Loaded configuration from '{datadir}/{program}.ini'")
# No 3Commas API required
# Initialize or open the database
db = init_botwatcher_db()
cursor = db.cursor()
# Bot monitor watching for configuration changes
while True:
# Reload config files and refetch data to catch changes
config = load_config()
logger.info(f"Reloaded configuration from '{datadir}/{program}.ini'")
# Configuration settings
timeint = int(config.get("settings", "timeinterval"))
for section in config.sections():
if section.startswith("botwatch_"):
# Bot configuration for section
botid = remove_prefix(section, "botwatch_")
botsecret = config.get(section, "secret")
if botid:
botdata = get_shared_bot_data(logger, botid, botsecret)
if botdata:
process_shared_bot_data(config, botdata, botid)
# No else case, exceptions are handled inside get_shared_bot_data
else:
logger.error(
f"No data fetched for section '{section}'. Check if bot still exists when "
f"this message does not disappear on future intervals!"
)
elif section not in ("settings"):
logger.warning(
f"Section '{section}' not processed (prefix 'botwatch_' missing)!",
False
)
if not wait_time_interval(logger, notification, timeint, False):
break