-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
430 lines (362 loc) · 16 KB
/
bot.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
import json
import time
import cbpro
import requests
import nicehash
import http.client
from time import sleep
from functools import wraps
from datetime import datetime, timedelta
from telegram.ext import Updater, CommandHandler
def get_config():
with open("config.json", "r") as read_file:
config = json.load(read_file)
return config
# https://github.com/nicehash/rest-clients-demo
host = "https://api2.nicehash.com"
organisation_id = get_config()["nicehash_organization_id"]
key = get_config()["nicehash_api_key"]
secret = get_config()["nicehahs_api_secret"]
private_api = nicehash.private_api(host, organisation_id, key, secret)
public_api = nicehash.public_api(host, True)
# LIST_OF_ADMINS = [12345678, 87654321]
LIST_OF_ADMINS = get_config()["telegram_admin_id"]
state = "OFF"
coin = None
period = int(1)
percentage_from_balance = int(50)
last_start = None
def get_balance(coin):
return float(private_api.get_accounts()[coin]["balance"])
def get_price(coin, current_balance):
if current_balance != 0:
price = float(
cbpro.PublicClient().get_product_ticker(product_id=f"{coin}-USD")["price"]
)
return round(price * current_balance)
else:
return 0
def restricted(func):
@wraps(func)
def wrapped(update, context, *args, **kwargs):
user_id = update.effective_user.id
if user_id not in LIST_OF_ADMINS:
# print("Unauthorized access denied for {}.".format(user_id))
context.bot.send_message(
chat_id=LIST_OF_ADMINS[0],
text=("Unauthorized access denied for {}.".format(user_id)),
)
return
return func(update, context, *args, **kwargs)
return wrapped
@restricted
def start(update, context):
context.bot.send_message(
chat_id=update.effective_chat.id,
text="I'm a bot, please talk to me! For showing all commands type /help",
)
@restricted
def help(update, context):
context.bot.send_message(
chat_id=update.effective_chat.id,
text="/balance\n\n/trade\n\n/autoexchange\n\n/price",
)
@restricted
def balance(update, context):
try:
coin = " ".join(context.args).upper()
if len(coin) == 0:
context.bot.send_message(
chat_id=update.effective_chat.id,
text="/balance <coin> \n\nAn example (BTC balance): \n/balance btc",
)
else:
if coin == "BTC":
btc_balance = get_balance(0)
balance = (
f"You have {str(btc_balance)} BTC ~$ {get_price(coin, btc_balance)}"
)
if coin == "ETH":
eth_balance = get_balance(1)
balance = (
f"You have {str(eth_balance)} ETH ~$ {get_price(coin, eth_balance)}"
)
if coin == "XRP":
xrp_balance = get_balance(2)
balance = (
f"You have {str(xrp_balance)} XRP ~$ {get_price(coin, xrp_balance)}"
)
if coin == "BCH":
bch_balance = get_balance(3)
balance = (
f"You have {str(bch_balance)} BCH ~$ {get_price(coin, bch_balance)}"
)
if coin == "LTC":
ltc_balance = get_balance(4)
balance = (
f"You have {str(ltc_balance)} LTC ~$ {get_price(coin, ltc_balance)}"
)
if coin == "ZEC":
zec_balance = get_balance(5)
balance = f"You have {str(zec_balance)} ZEC ~$ (currently not tradable on cbpro)"
if coin == "DASH":
dash_balance = get_balance(6)
balance = f"You have {str(dash_balance)} DASH ~$ {get_price(coin, dash_balance)}"
if coin == "XLM":
xlm_balance = get_balance(7)
balance = (
f"You have {str(xlm_balance)} XLM ~$ {get_price(coin, xlm_balance)}"
)
context.bot.send_message(chat_id=update.effective_chat.id, text=balance)
except Exception as e:
context.bot.send_message(chat_id=update.effective_chat.id, text=str(e))
@restricted
def trade(update, context):
def buy(pair, amount):
try:
if context.args[0].upper() == "BUY":
new_buy_market_order = private_api.create_exchange_buy_market_order(
public_api.get_exchange_markets_info()["symbols"][pair]["symbol"],
amount,
)
context.bot.send_message(
chat_id=update.effective_chat.id,
text=f'Bought {new_buy_market_order["executedQty"]} {context.args[1].upper()}',
)
except Exception as e:
context.bot.send_message(chat_id=update.effective_chat.id, text=str(e))
def sell(pair, amount):
try:
if context.args[0].upper() == "SELL":
new_sell_market_order = private_api.create_exchange_sell_market_order(
public_api.get_exchange_markets_info()["symbols"][pair]["symbol"],
amount,
)
context.bot.send_message(
chat_id=update.effective_chat.id,
text=f'Sold {new_sell_market_order["executedQty"]} {context.args[1].upper()}',
)
except Exception as e:
context.bot.send_message(chat_id=update.effective_chat.id, text=str(e))
try:
# context.args is list of strings /trade btc 100 -> ["btc", "100"]
# context.bot.send_message(chat_id=update.effective_chat.id, text=context.args)
if len(" ".join(context.args)) == 0:
context.bot.send_message(
chat_id=update.effective_chat.id,
text="/trade <buy/sell> <coin> <percentage_from_balance> \n\nAn example (buy XRP on all BTC balance): \n/trade buy xrp 100",
)
else:
if context.args[1].upper() == "LTC":
if context.args[0].upper() == "SELL":
pair = 0 # LTCBTC 0
amount = get_balance(4) * (float(context.args[2]) / 100)
sell(pair, amount)
if context.args[0].upper() == "BUY":
pair = 0 # LTCBTC 0
amount = get_balance(0) * (float(context.args[2]) / 100)
buy(pair, amount)
if context.args[1].upper() == "XRP":
if context.args[0].upper() == "SELL":
pair = 1 # XRPBTC 1
amount = get_balance(2) * (float(context.args[2]) / 100)
sell(pair, amount)
if context.args[0].upper() == "BUY":
pair = 1 # XRPBTC 1
amount = get_balance(0) * (float(context.args[2]) / 100)
buy(pair, amount)
if context.args[1].upper() == "ZEC":
if context.args[0].upper() == "SELL":
pair = 2 # ZECBTC 2
amount = get_balance(5) * (float(context.args[2]) / 100)
sell(pair, amount)
if context.args[0].upper() == "BUY":
pair = 2 # ZECBTC 2
amount = get_balance(0) * (float(context.args[2]) / 100)
buy(pair, amount)
if context.args[1].upper() == "BCH":
if context.args[0].upper() == "SELL":
pair = 3 # BCHBTC 3
amount = get_balance(3) * (float(context.args[2]) / 100)
sell(pair, amount)
if context.args[0].upper() == "BUY":
pair = 3 # BCHBTC 3
amount = get_balance(0) * (float(context.args[2]) / 100)
buy(pair, amount)
if context.args[1].upper() == "XLM":
if context.args[0].upper() == "SELL":
pair = 4 # XLMBTC 4
amount = get_balance(7) * (float(context.args[2]) / 100)
sell(pair, amount)
if context.args[0].upper() == "BUY":
pair = 4 # XLMBTC 4
amount = get_balance(0) * (float(context.args[2]) / 100)
buy(pair, amount)
if context.args[1].upper() == "DASH":
if context.args[0].upper() == "SELL":
pair = 5 # DASHBTC 5
amount = get_balance(6) * (float(context.args[2]) / 100)
sell(pair, amount)
if context.args[0].upper() == "BUY":
pair = 5 # DASHBTC 5
amount = get_balance(0) * (float(context.args[2]) / 100)
buy(pair, amount)
if context.args[1].upper() == "ETH":
if context.args[0].upper() == "SELL":
pair = 6 # ETHBTC 6
amount = get_balance(1) * (float(context.args[2]) / 100)
sell(pair, amount)
if context.args[0].upper() == "BUY":
pair = 6 # ETHBTC 6
amount = get_balance(0) * (float(context.args[2]) / 100)
buy(pair, amount)
except Exception as e:
context.bot.send_message(chat_id=update.effective_chat.id, text=str(e))
def auto_trade():
global coin
global period
global percentage_from_balance
global last_start
def buy(pair, amount):
try:
new_buy_market_order = private_api.create_exchange_buy_market_order(
public_api.get_exchange_markets_info()["symbols"][pair]["symbol"],
amount,
)
updater.bot.send_message(
chat_id=LIST_OF_ADMINS[0],
text=f'Bought {new_buy_market_order["executedQty"]} {coin}',
)
except Exception as e:
updater.bot.send_message(chat_id=LIST_OF_ADMINS[0], text=str(e))
try:
if last_start + timedelta(hours=period) < datetime.utcnow():
# if last_start + timedelta(seconds=19) < datetime.utcnow():
if coin == "LTC":
pair = 0 # LTCBTC 0
amount = get_balance(0) * (float(percentage_from_balance) / 100)
buy(pair, amount)
if coin == "XRP":
pair = 1 # XRPBTC 1
amount = get_balance(0) * (float(percentage_from_balance) / 100)
buy(pair, amount)
if coin == "ZEC":
pair = 2 # ZECBTC 2
amount = get_balance(0) * (float(percentage_from_balance) / 100)
buy(pair, amount)
if coin == "BCH":
pair = 3 # BCHBTC 3
amount = get_balance(0) * (float(percentage_from_balance) / 100)
buy(pair, amount)
if coin == "XLM":
pair = 4 # XLMBTC 4
amount = get_balance(0) * (float(percentage_from_balance) / 100)
buy(pair, amount)
if coin == "DASH":
pair = 5 # DASHBTC 5
amount = get_balance(0) * (float(percentage_from_balance) / 100)
buy(pair, amount)
if coin == "ETH":
pair = 6 # ETHBTC 6
amount = get_balance(0) * (float(percentage_from_balance) / 100)
buy(pair, amount)
last_start = datetime.utcnow()
except Exception as e:
updater.bot.send_message(chat_id=LIST_OF_ADMINS[0], text=str(e))
@restricted
def autoexchange(update, context):
global state
global coin
global period
global percentage_from_balance
global last_start
if len(" ".join(context.args)) == 0:
context.bot.send_message(
chat_id=update.effective_chat.id,
text="/autoexchange <state> <coin> <period_hours> <percentage_from_balance>\n\nTo start buy XRP on all BTC balance once a day:\n/autoexchange on xrp 24 100\n\nTo stop autoexchange:\n/autoexchange off\n\nTo see current status:\n/autoexchange status",
)
else:
if context.args[0].upper() == "STATUS":
if state == "ON":
context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"Autoexchange is {state}\nCoin is {coin}\nPeriod is {str(int(period))} hour(s)\n% from BTC balance is {percentage_from_balance}\nStart date {str(last_start)[:19]} (UTC)",
)
if state == "OFF":
context.bot.send_message(
chat_id=update.effective_chat.id, text=f"Autoexchange is {state}"
)
if context.args[0].upper() == "ON" and state == "ON":
context.bot.send_message(
chat_id=update.effective_chat.id,
text="Autoexchange is already running, stop it before new start",
)
if context.args[0].upper() == "OFF":
state = "OFF"
coin = None
period = int(1)
percentage_from_balance = int(50)
last_start = None
context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"Autoexchange disabled\nStop date {str(datetime.utcnow())[:19]} (UTC)",
)
if context.args[0].upper() == "ON" and state == "OFF":
state = context.args[0].upper()
coin = context.args[1].upper()
period = float(context.args[2])
percentage_from_balance = int(context.args[3])
if period < 1:
period = 1
context.bot.send_message(
chat_id=update.effective_chat.id,
text="Period must be one hour or more. I'll use default period (1 hour).",
)
last_start = datetime.utcnow()
context.bot.send_message(
chat_id=update.effective_chat.id,
text=f"Autoexchange enabled:\n(Buying {coin} once in {int(period)} hour(s) on {percentage_from_balance} % from BTC balance)\nStart date {str(last_start)[:19]} (UTC)",
)
def autoexchange_polling():
""" like a polling ;) """
global state
while True:
if state == "ON":
auto_trade()
time.sleep(19)
# updater.bot.send_message(
# chat_id=LIST_OF_ADMINS[0],
# text=f"{state} {coin} {period} {percentage_from_balance} {last_start}",
# )
continue
else:
time.sleep(19)
# updater.bot.send_message(
# chat_id=LIST_OF_ADMINS[0],
# text=f"{state} {coin} {period} {percentage_from_balance} {last_start}",
# )
continue
@restricted
def get_all_prices(update, context):
# Coinbace Pro Public API
# https://github.com/danpaquin/coinbasepro-python
btc_usd = cbpro.PublicClient().get_product_ticker(product_id="BTC-USD")["price"]
xrp_usd = cbpro.PublicClient().get_product_ticker(product_id="XRP-USD")["price"]
eth_usd = cbpro.PublicClient().get_product_ticker(product_id="ETH-USD")["price"]
bch_usd = cbpro.PublicClient().get_product_ticker(product_id="BCH-USD")["price"]
ltc_usd = cbpro.PublicClient().get_product_ticker(product_id="LTC-USD")["price"]
updater.bot.send_message(
chat_id=LIST_OF_ADMINS[0],
text=f"BTC-USD {str(btc_usd)}\nXRP-USD {str(xrp_usd)}\nETH-USD {str(eth_usd)}\nBCH-USD {str(bch_usd)}\nLTC-USD {str(ltc_usd)}\n\nCoinbasePro rates\n{str(datetime.utcnow())[:19]} (UTC)",
)
if __name__ == "__main__":
updater = Updater(get_config()["telegram_bot_token"], use_context=True)
updater.dispatcher.add_handler(CommandHandler("start", start))
updater.dispatcher.add_handler(CommandHandler("help", help))
updater.dispatcher.add_handler(CommandHandler("balance", balance))
updater.dispatcher.add_handler(CommandHandler("trade", trade))
updater.dispatcher.add_handler(CommandHandler("autoexchange", autoexchange))
updater.dispatcher.add_handler(CommandHandler("price", get_all_prices))
updater.start_polling()
autoexchange_polling()
updater.idle()