forked from cyberjunky/3commas-cyber-bots
-
Notifications
You must be signed in to change notification settings - Fork 0
/
watchlist.py
executable file
·227 lines (182 loc) · 6.39 KB
/
watchlist.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
#!/usr/bin/env python3
"""Cyberjunky's 3Commas bot helpers."""
import argparse
import configparser
import json
import os
import sys
import time
from pathlib import Path
from telethon import TelegramClient, events
from helpers.logging import Logger, NotificationHandler
from helpers.threecommas import (
init_threecommas_api,
load_blacklist,
prefetch_marketcodes
)
from helpers.watchlist import process_botlist
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",
"debug": False,
"logrotate": 7,
"usdt-botids": [12345, 67890],
"btc-botids": [12345, 67890],
"3c-apikey": "Your 3Commas API Key",
"3c-apisecret": "Your 3Commas API Secret",
"3c-apiselfsigned": "Your own generated API key, or empty",
"tgram-phone-number": "Your Telegram Phone number",
"tgram-channel": "Telegram Channel to watch",
"tgram-api-id": "Your Telegram API ID",
"tgram-api-hash": "Your Telegram API Hash",
"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."""
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
async def handle_custom_event(event):
"""Handle the received Telegram event"""
logger.debug(
"Received telegram message '%s'"
% (event.message.text.replace("\n", " - "))
)
# Parse the event and do some error checking
trigger = event.raw_text.splitlines()
try:
exchange = trigger[0].replace("\n", "")
pair = trigger[1].replace("#", "").replace("\n", "")
base = pair.split("_")[0].replace("#", "").replace("\n", "")
coin = pair.split("_")[1].replace("\n", "")
# Fix for future pair format
if coin.endswith(base) and len(coin) > len(base):
coin = coin.replace(base, "")
trade = trigger[2].replace("\n", "")
if trade == "LONG" and len(trigger) == 4 and trigger[3] == "CLOSE":
trade = "CLOSE"
except IndexError:
logger.debug("Invalid trigger message format!")
return
logger.info(
f"Received message on {exchange}% for {base}_{coin}"
)
if exchange.lower() not in ("binance", "ftx", "kucoin"):
logger.debug(
f"Exchange '{exchange}' is not yet supported."
)
return
if trade not in ('LONG', 'CLOSE'):
logger.debug(f"Trade type '{trade}' is not supported yet!")
return
if base == "USDT":
botids = json.loads(config.get("settings", "usdt-botids"))
if len(botids) == 0:
logger.debug(
"No valid usdt-botids configured for '%s', disabled" % base
)
return
elif base == "BTC":
botids = json.loads(config.get("settings", "btc-botids"))
if len(botids) == 0:
logger.debug("No valid btc-botids configured for '%s', disabled" % base)
return
else:
logger.error(
"Error the base of pair '%s' being '%s' is not supported yet!" % (pair, base)
)
return
if len(botids) == 0:
logger.debug(
f"{base}_{coin}: no valid botids configured for base '{base}'."
)
return
await client.loop.run_in_executor(
None, process_botlist, logger, api, blacklistfile, blacklist, marketcodes, botids, coin, trade
)
# 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)
parser.add_argument("-b", "--blacklist", help="blacklist to use", type=str)
args = parser.parse_args()
if args.datadir:
datadir = args.datadir
else:
datadir = os.getcwd()
# pylint: disable-msg=C0103
if args.blacklist:
blacklistfile = f"{datadir}/{args.blacklist}"
else:
blacklistfile = ""
# Create or load configuration file
config = load_config()
if not config:
logger = Logger(datadir, program, None, 7, False, False)
logger.info(
f"Created example config file '{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)
# Prefetch marketcodes for all bots
botids = json.loads(config.get("settings", "usdt-botids")) + json.loads(config.get("settings", "btc-botids"))
marketcodes = prefetch_marketcodes(logger, api, botids)
# Prefetch blacklists
blacklist = load_blacklist(logger, api, blacklistfile)
# Watchlist telegram trigger
client = TelegramClient(
f"{datadir}/{program}",
config.get("settings", "tgram-api-id"),
config.get("settings", "tgram-api-hash"),
).start(config.get("settings", "tgram-phone-number"))
@client.on(events.NewMessage(chats=config.get("settings", "tgram-channel")))
async def callback(event):
"""Receive Telegram message."""
await handle_custom_event(event)
notification.send_notification()
# Start telegram client
client.start()
logger.info(
"Listening to telegram chat '%s' for triggers"
% config.get("settings", "tgram-channel"),
True,
)
client.run_until_disconnected()