forked from cyberjunky/3commas-cyber-bots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tpincrement.py
executable file
·281 lines (228 loc) · 8.47 KB
/
tpincrement.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
#!/usr/bin/env python3
"""Cyberjunky's 3Commas bot helpers."""
import argparse
import configparser
import json
import os
import sqlite3
import sys
import time
from pathlib import Path
from helpers.logging import Logger, NotificationHandler
from helpers.misc import check_deal, wait_time_interval
from helpers.threecommas import init_threecommas_api
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": 3600,
"debug": False,
"logrotate": 7,
"botids": [12345, 67890],
"increment-step-scale": [0.10, 0.05, 0.05, 0.05, 0.05, 0.05],
"3c-apikey": "Your 3Commas API Key",
"3c-apisecret": "Your 3Commas API Secret",
"3c-apiselfsigned": "Your own generated API key, or empty",
"notifications": False,
"notify-urls": ["notify-url1"],
}
with open(f"{datadir}/{program}.ini", "w") as cfgfile:
cfg.write(cfgfile)
return None
def upgrade_config(cfg):
"""Upgrade config file if needed."""
try:
cfg.get("settings", "increment-step-scale")
except configparser.NoOptionError:
cfg.set(
"settings", "increment-step-scale", "[0.10, 0.05, 0.05, 0.05, 0.05, 0.05]"
)
cfg.remove_option("settings", "increment-percentage")
with open(f"{datadir}/{program}.ini", "w+") as cfgfile:
cfg.write(cfgfile)
logger.info("Upgraded the configuration file")
if not cfg.has_option("settings", "3c-apiselfsigned"):
cfg.set("settings", "3c-apiselfsigned", "")
with open(f"{datadir}/{program}.ini", "w+") as cfgfile:
cfg.write(cfgfile)
logger.info("Upgraded the configuration file (3c-apiselfsigned)")
return cfg
def update_deal(thebot, deal, to_increment, new_percentage):
"""Update deal with new take profit percentage."""
bot_name = thebot["name"]
deal_id = deal["id"]
error, data = api.request(
entity="deals",
action="update_deal",
action_id=str(deal_id),
payload={
"deal_id": thebot["id"],
"take_profit": new_percentage,
},
)
if data:
logger.info(
f"Incremented TP for deal {deal_id}/{deal['pair']} and bot \"{bot_name}\"\n"
f"Changed TP from {deal['take_profit']}% to {new_percentage}% (+{to_increment}%)",
True,
)
else:
if error and "msg" in error:
logger.error(
"Error occurred updating bot with new take profit values: %s"
% error["msg"]
)
else:
logger.error("Error occurred updating bot with new take profit values")
def increment_takeprofit(thebot):
"""Check deals from bot and compare safety orders against the database."""
deals_count = 0
deals = thebot["active_deals"]
if deals:
for deal in deals:
deal_id = deal["id"]
completed_safety_orders_count = int(deal["completed_safety_orders_count"])
to_increment = 0
deals_count += 1
existing_deal = check_deal(cursor, deal_id)
if existing_deal is not None:
db.execute(
f"UPDATE deals SET safety_count = {completed_safety_orders_count} "
f"WHERE dealid = {deal_id}"
)
else:
db.execute(
f"INSERT INTO deals (dealid, safety_count) VALUES ({deal_id}, "
f"{completed_safety_orders_count})"
)
existing_deal_safety_count = (
0 if existing_deal is None else existing_deal["safety_count"]
)
for cnt in range(
existing_deal_safety_count + 1, completed_safety_orders_count + 1
):
try:
to_increment += float(increment_step_scale[cnt - 1])
except IndexError:
pass
if to_increment != 0.0:
new_percentage = round(float(deal["take_profit"]) + to_increment, 2)
update_deal(thebot, deal, round(to_increment, 2), new_percentage)
logger.info(
f"Finished updating {deals_count} deals for bot \"{thebot['name']}\""
)
db.commit()
def init_tpincrement_db():
"""Create or open database to store bot and deals 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")
dbcursor.execute(
"CREATE TABLE deals (dealid INT Primary Key, safety_count INT)"
)
logger.info("Database tables created successfully")
return dbconnection
def upgrade_tpincrement_db():
"""Upgrade database if needed."""
try:
cursor.execute("ALTER TABLE deals DROP COLUMN increment")
logger.info("Database schema upgraded")
except sqlite3.OperationalError:
logger.debug("Database schema is up-to-date")
# 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="data directory to use", 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(config)
logger.info(f"Loaded configuration from '{datadir}/{program}.ini'")
# Initialize 3Commas API
api = init_threecommas_api(config)
# Initialize or open the database
db = init_tpincrement_db()
cursor = db.cursor()
# Upgrade the database if needed
upgrade_tpincrement_db()
# Auto increment TakeProfit %
while True:
config = load_config()
logger.info(f"Reloaded configuration from '{datadir}/{program}.ini'")
# Configuration settings
botids = json.loads(config.get("settings", "botids"))
timeint = int(config.get("settings", "timeinterval"))
increment_step_scale = json.loads(config.get("settings", "increment-step-scale"))
# Walk through all bots configured
for bot in botids:
boterror, botdata = api.request(
entity="bots",
action="show",
action_id=str(bot),
)
if botdata:
increment_takeprofit(botdata)
else:
if boterror and "status_code" in boterror:
if boterror["status_code"] == 404:
logger.error(
"Error occurred updating bots: bot with id '%s' was not found" % botid
)
else:
logger.error(
"Error occurred updating bots: %s" % boterror["msg"]
)
elif boterror and "msg" in boterror:
logger.error(
"Error occurred updating bots: %s" % boterror["msg"]
)
else:
logger.error("Error occurred updating bots")
if not wait_time_interval(logger, notification, timeint):
break