-
Notifications
You must be signed in to change notification settings - Fork 5
/
telegramBot.py
187 lines (157 loc) · 6.93 KB
/
telegramBot.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
import subprocess
import configparser
import os
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
from collections import defaultdict
import ast
import config
from trader import trader
helpMessage = '''
Below you can see all the commands:
Buy_market --market market --quantity quantity
Sell_market --market market --quantity quantity
Buy_limit --market market'] --quantity quantity --rate rate
Sell_limit --market market'] --quantity quantity --rate rate
Get_open_trades --market market
Cancel_order --market market --orderID orderID
Get_balance --symbol symbol
Get_market_price --market market
Sell_OCO_order --market market --quantity quantity --takeProfitPrice takeProfitPrice --stopLimit stopLimit --stopLossPrice stopLossPrice
Trade --market market --quantity quantity --takeProfitPrice takeProfitPrice --stopLossPrice stopLossPrice
Trade_pct --market market --quantity quantity --takeProfitPct takeProfitPct --stopLossPct stopLossPct
Transfer_dust --symbol symbol
*you can also use amount of BTC instead of quantity (--amount amount)
*for Get_balance market argument is optional
*if you dont use amount or quantity minimum quantity will be used
*for Trade you can add multiple targets separating them with comma
'''
### Get admin chat_id from config file
### For more security replies only send to admin chat_id
adminCID = config.telegram_admin_chatID
adminCID = ast.literal_eval(adminCID)
### Enable logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO
)
logger = logging.getLogger(__name__)
trader_class = trader()
### This function run command and send output to user
def runCMD(bot, update):
if not isAdmin(bot, update):
return
chat_id = update.message.chat_id
try:
usercommand = update.message.text
usercommand = usercommand.split()
options = defaultdict()
response = ""
for i in range(1, len(usercommand), 2):
if(usercommand[i][2:] == "takeProfitPrice_list"):
options[usercommand[i][2:]] = usercommand[i+1].split(",")
else:
options[usercommand[i][2:]] = usercommand[i+1]
if 'quantity' not in options:
if 'amount' in options:
lastBid, lastAsk = trader_class.get_market_price(options['market'])
options['quantity'] = (float(options['amount']) / lastBid)
else:
options['quantity'] = '0'
if(usercommand[0] == "Buy_market"):
response = trader_class.buy_market(options['market'], float(options['quantity']))
elif(usercommand[0] == "Sell_market"):
response = trader_class.sell_market(options['market'], float(options['quantity']))
elif(usercommand[0] == "Buy_limit"):
response = trader_class.buy_limit(options['market'], float(options['quantity']), options['rate'])
elif(usercommand[0] == "Sell_limit"):
response = trader_class.sell_limit(options['market'], float(options['quantity']), options['rate'])
elif(usercommand[0] == "Get_open_trades"):
response = trader_class.get_open_trades(options['market'])
elif(usercommand[0] == "Cancel_order"):
response = trader_class.cancel_order(options['market'], options['orderID'])
elif(usercommand[0] == "Get_balance"):
if 'market' in options:
response = trader_class.get_balance(options['market'])
else:
response = trader_class.get_balance()
elif(usercommand[0] == "Get_market_price"):
response = trader_class.get_market_price(options['market'])
elif(usercommand[0] == "Sell_OCO_order"):
response = trader_class.sell_OCO_order(options['market'], float(options['quantity']), options['takeProfitPrice'], options['stopLimit'], options['stopLossPrice'])
elif(usercommand[0] == "Trade"):
if 'takeProfitPrice_list' in options:
response = trader_class.trade(options['market'], float(options['quantity']), options['takeProfitPrice_list'], options['stopLossPrice'])
else:
response = trader_class.trade(options['market'], float(options['quantity']), options['takeProfitPrice'], options['stopLossPrice'])
elif(usercommand[0] == "Trade_pct"):
response = trader_class.trade_pct(options['market'], float(options['quantity']), options['takeProfitPct'], options['stopLossPct'])
elif(usercommand[0] == "Transfer_dust"):
response = trader_class.transfer_dust(options['symbol'])
if response:
chunk_size=4000
if len(response)>chunk_size:
response = [ response[i:i+chunk_size] for i in range(0, len(response), chunk_size) ]
for message in response:
bot.sendMessage(text=str(message), chat_id=adminCID)
else:
bot.sendMessage(text=str(response), chat_id=adminCID)
except Exception as e:
bot.sendMessage(text=str(e), chat_id=chat_id)
### This function ping 8.8.8.8 and send you result
def ping8(bot, update):
if not isAdmin(bot, update):
return
chat_id = update.message.chat_id
cmdOut = str(
subprocess.check_output(
"ping", "8.8.8.8 -c4", stderr=subprocess.STDOUT, shell=True
),
"utf-8",
)
bot.sendMessage(text=cmdOut, chat_id=chat_id)
def startCMD(bot, update):
if not isAdmin(bot, update):
return
chat_id = update.message.chat_id
bot.sendMessage(
text="Welcome to Binance Trader bot, Please use /help and read carefully!!",
chat_id=chat_id,
)
def helpCMD(bot, update):
if not isAdmin(bot, update):
return
chat_id = update.message.chat_id
bot.sendMessage(
text=helpMessage,
chat_id=chat_id,
)
def error(bot, update, error):
"""Log Errors caused by Updates."""
logger.warning('Update "%s" caused error "%s"', update, error)
def isAdmin(bot, update):
print(update)
chat_id = update.message.chat_id
if int(chat_id) in adminCID:
return True
else:
update.message.reply_text(
"You cannot use this bot, because you are not Admin!!!!"
)
alertMessage = """Some one tried to use this bot with this information:\n chat_id is {} and username is {} """.format(
update.message.chat_id, update.message.from_user.username
)
for admin in adminCID:
bot.sendMessage(text=alertMessage, chat_id=admin)
return False
def main():
updater = Updater(config.telegram_token)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", startCMD))
dp.add_handler(CommandHandler("ping8", ping8))
dp.add_handler(CommandHandler("help", helpCMD))
dp.add_handler(MessageHandler(Filters.text, runCMD))
dp.add_error_handler(error)
updater.start_polling()
updater.idle()
if __name__ == "__main__":
main()