-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbot.py
119 lines (102 loc) · 5.28 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
import logging
import telegram
from exchange_data import *
from telegram.ext import CommandHandler
from telegram.ext import Updater
from dbhelper import DBHelper
from bitmex import *
api_id = 'INSERT BITMEX API ID HERE'
api_secret = 'INSERT BITMEX SECRET KEY HERE'
updater = Updater(token="INSERT BOT TOKEN HERE", use_context=True)
j = updater.job_queue
dispatcher = updater.dispatcher
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
instructions = ("This is the TradingAssistant Bot.\n\nTo set a price alert for a currency, use the setalert command and enter an exchange, trading pair and price as follows:\n\n /setalert binance,btcusdc,20000\n\n /setalert forex,usdeur,0.99\n\nIf you are setting a price alert for a stock, use the following format:\n\n /setalert stock,tsla,250\n\nTo get the current price of a currency or stock use the getprice command:\n\n /getprice binance, btcusd \n\n /getprice forex, eurusd\n\n /getprice stock,msft\n\n *note: capitalization does not matter and a single space can be typed after commas ")
# /help command
def help(update, context):
context.bot.send_message(chat_id=update.message.chat_id, text=instructions)
# /position command
def positions(update, context):
if update.message.chat.type == "private" and update.message.chat.username == "my_username":
context.bot.send_message(chat_id=update.message.chat_id, text=display_positions(api_secret, api_id))
else:
context.bot.send_message(chat_id=update.message.chat_id, text="Sorry, only my creator can use this function.")
# /balance command
def balance(update, context):
if update.message.chat.type == "private" and update.message.chat.username == "scuba_steve2345":
context.bot.send_message(chat_id=update.message.chat_id, text=display_balance_info(api_secret, api_id))
else:
context.bot.send_message(chat_id=update.message.chat_id, text="Sorry, only my creator can use this function.")
# /getprice command, bot can fetch the price on any supported exchange
def getprice(update, context):
message_text = update.message.text[10::]
msg = message_text.replace(" ","").split(",")
ans = get_price(msg[0], msg[1])
if ans == False:
context.bot.send_message(chat_id=update.message.chat_id, text="Invalid Trading Pair or Exchange")
else:
context.bot.send_message(chat_id=update.message.chat_id, text="The current price of " + msg[1].upper() + " on " + msg[0] + " is " + "{:.8f}".format(float(ans)))
# /setalert command
def setalert(update, context):
try:
message_text = update.message.text[10::]
if is_valid_request(message_text, update.message.chat_id) == False:
context.bot.send_message(chat_id=update.message.chat_id, text="Your Price Alert Was Not Set Successfully. Choose a valid price then try again.")
else:
context.bot.send_message(chat_id=update.message.chat_id, text="Your Price Alert Was Set Successfully.")
except Exception as e:
context.bot.send_message(chat_id=update.message.chat_id, text="Your Price Alert Was NOT Set Successfully. Try Again.")
print(e)
# checks if the alert request is valid
def is_valid_request(msg,chat_id):
db = DBHelper()
db.setup()
# remove whitespace and split the chosen exchange,trading pair and price into a list
msg = msg.replace(" ","").split(",")
cur_price = get_price(msg[0],msg[1])
# if request is valid, add to database
if cur_price != False:
if cur_price < float(msg[2]):
trigger = '>'
elif cur_price > float(msg[2]):
trigger = '<'
else:
return False
row_id = len(db.get_table()) + 1
db.add_alert((row_id, msg[0], msg[1], msg[2], chat_id, trigger))
else:
return False
# bot continuously checks if an alert has been reached
def check_prices(context):
db = DBHelper()
db.setup()
# Sample Row in Database: (ID, Exchange, Pair, Price, chat_id, trigger)
table = db.get_table()
for row in table:
cur_price = get_price(row[1],row[2])
if row[5] == '>' and cur_price >= float(row[3]) or row[5] == '<' and cur_price <= float(row[3]):
if row[1] == "stock":
response = row[2].upper() + " has reached " + row[3]
else:
response = row[2].upper() + " has reached " + row[3] + " on " + row[1]
db.remove_alert(row[0])
context.bot.send_message(chat_id = row[4], text = response )
if __name__ == "__main__":
#initialize database
db = DBHelper()
db.setup()
# bot checks prices with an interval of every 5 seconds
job_check_prices = j.run_repeating(check_prices, interval= 20, first =0)
# create and add handlers to dispatcher
help_handler = CommandHandler('help', help)
dispatcher.add_handler(help_handler)
position_handler = CommandHandler('positions', positions)
dispatcher.add_handler(position_handler)
balance_handler = CommandHandler('balance', balance)
dispatcher.add_handler(balance_handler)
setalert_handler = CommandHandler('setalert', setalert)
dispatcher.add_handler(setalert_handler)
getprice_handler = CommandHandler('getprice', getprice)
dispatcher.add_handler(getprice_handler)
updater.start_polling()