2018-03-02 15:22:00 +00:00
|
|
|
# pragma pylint: disable=unused-argument, unused-variable, protected-access, invalid-name
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
This module manage Telegram communication
|
|
|
|
"""
|
2020-06-07 08:09:39 +00:00
|
|
|
import json
|
2018-03-25 19:37:14 +00:00
|
|
|
import logging
|
2021-05-29 06:12:25 +00:00
|
|
|
import re
|
2021-05-20 05:17:08 +00:00
|
|
|
from datetime import date, datetime, timedelta
|
2022-01-26 18:53:46 +00:00
|
|
|
from functools import partial
|
2021-03-01 19:08:49 +00:00
|
|
|
from html import escape
|
2020-12-20 16:22:23 +00:00
|
|
|
from itertools import chain
|
2021-05-17 12:59:03 +00:00
|
|
|
from math import isnan
|
2021-06-13 18:34:08 +00:00
|
|
|
from typing import Any, Callable, Dict, List, Optional, Union
|
2021-07-04 15:04:39 +00:00
|
|
|
|
2020-09-28 17:39:41 +00:00
|
|
|
import arrow
|
2017-11-20 21:26:32 +00:00
|
|
|
from tabulate import tabulate
|
2021-06-13 18:21:43 +00:00
|
|
|
from telegram import (CallbackQuery, InlineKeyboardButton, InlineKeyboardMarkup, KeyboardButton,
|
|
|
|
ParseMode, ReplyKeyboardMarkup, Update)
|
2021-06-13 18:04:24 +00:00
|
|
|
from telegram.error import BadRequest, NetworkError, TelegramError
|
2021-04-14 21:20:10 +00:00
|
|
|
from telegram.ext import CallbackContext, CallbackQueryHandler, CommandHandler, Updater
|
2020-08-15 18:15:02 +00:00
|
|
|
from telegram.utils.helpers import escape_markdown
|
2018-03-17 21:44:47 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
from freqtrade.__init__ import __version__
|
2021-02-28 08:03:27 +00:00
|
|
|
from freqtrade.constants import DUST_PER_COIN
|
2022-03-03 06:07:33 +00:00
|
|
|
from freqtrade.enums import RPCMessageType, SignalDirection, TradingMode
|
2020-12-22 11:34:21 +00:00
|
|
|
from freqtrade.exceptions import OperationalException
|
2021-07-04 15:04:39 +00:00
|
|
|
from freqtrade.misc import chunks, plural, round_coin_value
|
2021-10-16 15:57:51 +00:00
|
|
|
from freqtrade.persistence import Trade
|
2021-06-09 17:51:44 +00:00
|
|
|
from freqtrade.rpc import RPC, RPCException, RPCHandler
|
2017-11-02 17:56:57 +00:00
|
|
|
|
2020-09-28 17:39:41 +00:00
|
|
|
|
2018-03-25 19:37:14 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
2018-06-08 21:50:38 +00:00
|
|
|
logger.debug('Included module rpc.telegram ...')
|
|
|
|
|
2019-04-10 04:59:10 +00:00
|
|
|
MAX_TELEGRAM_MESSAGE_LENGTH = 4096
|
2019-04-08 17:59:30 +00:00
|
|
|
|
|
|
|
|
2019-03-24 18:44:52 +00:00
|
|
|
def authorized_only(command_handler: Callable[..., None]) -> Callable[..., Any]:
|
2017-05-14 12:14:16 +00:00
|
|
|
"""
|
|
|
|
Decorator to check if the message comes from the correct chat_id
|
|
|
|
:param command_handler: Telegram CommandHandler
|
|
|
|
:return: decorated function
|
|
|
|
"""
|
2020-06-05 17:09:49 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
def wrapper(self, *args, **kwargs):
|
2018-06-08 22:58:24 +00:00
|
|
|
""" Decorator logic """
|
2019-09-02 18:14:41 +00:00
|
|
|
update = kwargs.get('update') or args[0]
|
2017-09-08 17:25:39 +00:00
|
|
|
|
2017-11-07 21:27:16 +00:00
|
|
|
# Reject unauthorized messages
|
2021-02-03 18:06:52 +00:00
|
|
|
if update.callback_query:
|
|
|
|
cchat_id = int(update.callback_query.message.chat.id)
|
|
|
|
else:
|
|
|
|
cchat_id = int(update.message.chat_id)
|
2018-02-13 03:45:59 +00:00
|
|
|
|
|
|
|
chat_id = int(self._config['telegram']['chat_id'])
|
2021-02-03 18:06:52 +00:00
|
|
|
if cchat_id != chat_id:
|
2018-03-25 19:37:14 +00:00
|
|
|
logger.info(
|
2018-02-13 03:45:59 +00:00
|
|
|
'Rejected unauthorized message from: %s',
|
|
|
|
update.message.chat_id
|
|
|
|
)
|
2017-11-07 21:27:16 +00:00
|
|
|
return wrapper
|
2021-10-16 15:57:51 +00:00
|
|
|
# Rollback session to avoid getting data stored in a transaction.
|
|
|
|
Trade.query.session.rollback()
|
2021-06-17 04:57:35 +00:00
|
|
|
logger.debug(
|
2018-02-13 03:45:59 +00:00
|
|
|
'Executing handler: %s for chat_id: %s',
|
|
|
|
command_handler.__name__,
|
|
|
|
chat_id
|
|
|
|
)
|
2017-11-07 21:27:16 +00:00
|
|
|
try:
|
2018-02-13 03:45:59 +00:00
|
|
|
return command_handler(self, *args, **kwargs)
|
2017-11-07 21:27:16 +00:00
|
|
|
except BaseException:
|
2018-03-25 19:37:14 +00:00
|
|
|
logger.exception('Exception occurred within Telegram module')
|
2017-09-08 13:51:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
return wrapper
|
2017-09-08 13:51:00 +00:00
|
|
|
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2020-12-24 08:01:53 +00:00
|
|
|
class Telegram(RPCHandler):
|
2018-06-08 22:58:24 +00:00
|
|
|
""" This class handles all telegram communication """
|
2018-06-08 01:49:09 +00:00
|
|
|
|
2020-12-24 08:01:53 +00:00
|
|
|
def __init__(self, rpc: RPC, config: Dict[str, Any]) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
Init the Telegram call, and init the super class RPCHandler
|
|
|
|
:param rpc: instance of RPC Helper class
|
|
|
|
:param config: Configuration object
|
2018-02-13 03:45:59 +00:00
|
|
|
:return: None
|
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
super().__init__(rpc, config)
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2020-12-01 18:55:20 +00:00
|
|
|
self._updater: Updater
|
2020-12-22 11:34:21 +00:00
|
|
|
self._init_keyboard()
|
2018-02-13 03:45:59 +00:00
|
|
|
self._init()
|
|
|
|
|
2020-12-22 11:34:21 +00:00
|
|
|
def _init_keyboard(self) -> None:
|
2020-12-20 21:36:56 +00:00
|
|
|
"""
|
|
|
|
Validates the keyboard configuration from telegram config
|
|
|
|
section.
|
|
|
|
"""
|
2021-06-17 17:50:49 +00:00
|
|
|
self._keyboard: List[List[Union[str, KeyboardButton]]] = [
|
2020-12-20 21:36:56 +00:00
|
|
|
['/daily', '/profit', '/balance'],
|
|
|
|
['/status', '/status table', '/performance'],
|
|
|
|
['/count', '/start', '/stop', '/help']
|
|
|
|
]
|
|
|
|
# do not allow commands with mandatory arguments and critical cmds
|
|
|
|
# like /forcesell and /forcebuy
|
|
|
|
# TODO: DRY! - its not good to list all valid cmds here. But otherwise
|
2021-06-25 13:45:49 +00:00
|
|
|
# this needs refactoring of the whole telegram module (same
|
2020-12-20 21:36:56 +00:00
|
|
|
# problem in _help()).
|
2021-05-29 06:12:25 +00:00
|
|
|
valid_keys: List[str] = [r'/start$', r'/stop$', r'/status$', r'/status table$',
|
2022-04-03 08:39:35 +00:00
|
|
|
r'/trades$', r'/performance$', r'/buys', r'/entries',
|
|
|
|
r'/sells', r'/exits', r'/mix_tags',
|
2021-10-21 14:25:38 +00:00
|
|
|
r'/daily$', r'/daily \d+$', r'/profit$', r'/profit \d+',
|
2021-05-29 06:12:25 +00:00
|
|
|
r'/stats$', r'/count$', r'/locks$', r'/balance$',
|
|
|
|
r'/stopbuy$', r'/reload_config$', r'/show_config$',
|
2021-12-11 15:09:20 +00:00
|
|
|
r'/logs$', r'/whitelist$', r'/blacklist$', r'/bl_delete$',
|
2021-11-27 23:23:02 +00:00
|
|
|
r'/weekly$', r'/weekly \d+$', r'/monthly$', r'/monthly \d+$',
|
2022-01-26 19:17:00 +00:00
|
|
|
r'/forcebuy$', r'/forcelong$', r'/forceshort$',
|
2022-02-11 16:02:04 +00:00
|
|
|
r'/edge$', r'/health$', r'/help$', r'/version$']
|
2021-05-29 06:12:25 +00:00
|
|
|
# Create keys for generation
|
|
|
|
valid_keys_print = [k.replace('$', '') for k in valid_keys]
|
2020-12-20 21:36:56 +00:00
|
|
|
|
2020-12-22 11:34:21 +00:00
|
|
|
# custom keyboard specified in config.json
|
2020-12-20 21:36:56 +00:00
|
|
|
cust_keyboard = self._config['telegram'].get('keyboard', [])
|
|
|
|
if cust_keyboard:
|
2021-05-29 06:12:25 +00:00
|
|
|
combined = "(" + ")|(".join(valid_keys) + ")"
|
2020-12-20 21:36:56 +00:00
|
|
|
# check for valid shortcuts
|
|
|
|
invalid_keys = [b for b in chain.from_iterable(cust_keyboard)
|
2021-05-29 06:12:25 +00:00
|
|
|
if not re.match(combined, b)]
|
2020-12-20 21:36:56 +00:00
|
|
|
if len(invalid_keys):
|
2020-12-23 15:00:01 +00:00
|
|
|
err_msg = ('config.telegram.keyboard: Invalid commands for '
|
|
|
|
f'custom Telegram keyboard: {invalid_keys}'
|
2021-05-29 06:12:25 +00:00
|
|
|
f'\nvalid commands are: {valid_keys_print}')
|
2020-12-22 11:34:21 +00:00
|
|
|
raise OperationalException(err_msg)
|
2020-12-20 21:36:56 +00:00
|
|
|
else:
|
|
|
|
self._keyboard = cust_keyboard
|
2020-12-22 11:34:21 +00:00
|
|
|
logger.info('using custom keyboard from '
|
2020-12-20 21:36:56 +00:00
|
|
|
f'config.json: {self._keyboard}')
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
def _init(self) -> None:
|
|
|
|
"""
|
|
|
|
Initializes this module with the given config,
|
|
|
|
registers all known command handlers
|
|
|
|
and starts polling for message updates
|
|
|
|
"""
|
2019-09-02 18:14:41 +00:00
|
|
|
self._updater = Updater(token=self._config['telegram']['token'], workers=0,
|
|
|
|
use_context=True)
|
2018-02-13 03:45:59 +00:00
|
|
|
|
|
|
|
# Register command handler and start telegram message polling
|
|
|
|
handles = [
|
|
|
|
CommandHandler('status', self._status),
|
|
|
|
CommandHandler('profit', self._profit),
|
|
|
|
CommandHandler('balance', self._balance),
|
|
|
|
CommandHandler('start', self._start),
|
|
|
|
CommandHandler('stop', self._stop),
|
2022-01-26 19:17:00 +00:00
|
|
|
CommandHandler(['forcesell', 'forceexit'], self._forceexit),
|
2022-01-27 05:40:41 +00:00
|
|
|
CommandHandler(['forcebuy', 'forcelong'], partial(
|
|
|
|
self._forceenter, order_side=SignalDirection.LONG)),
|
|
|
|
CommandHandler('forceshort', partial(
|
|
|
|
self._forceenter, order_side=SignalDirection.SHORT)),
|
2020-07-19 15:02:53 +00:00
|
|
|
CommandHandler('trades', self._trades),
|
2020-08-04 12:49:59 +00:00
|
|
|
CommandHandler('delete', self._delete_trade),
|
2018-02-13 03:45:59 +00:00
|
|
|
CommandHandler('performance', self._performance),
|
2021-11-21 08:51:16 +00:00
|
|
|
CommandHandler(['buys', 'entries'], self._enter_tag_performance),
|
2022-04-03 08:39:35 +00:00
|
|
|
CommandHandler(['sells', 'exits'], self._exit_reason_performance),
|
2021-10-12 21:02:28 +00:00
|
|
|
CommandHandler('mix_tags', self._mix_tag_performance),
|
2020-12-09 19:26:11 +00:00
|
|
|
CommandHandler('stats', self._stats),
|
2018-02-13 03:45:59 +00:00
|
|
|
CommandHandler('daily', self._daily),
|
2021-11-04 19:47:01 +00:00
|
|
|
CommandHandler('weekly', self._weekly),
|
|
|
|
CommandHandler('monthly', self._monthly),
|
2018-02-13 03:45:59 +00:00
|
|
|
CommandHandler('count', self._count),
|
2020-10-17 13:15:35 +00:00
|
|
|
CommandHandler('locks', self._locks),
|
2021-03-01 19:08:49 +00:00
|
|
|
CommandHandler(['unlock', 'delete_locks'], self._delete_locks),
|
2020-06-10 14:55:47 +00:00
|
|
|
CommandHandler(['reload_config', 'reload_conf'], self._reload_config),
|
|
|
|
CommandHandler(['show_config', 'show_conf'], self._show_config),
|
2019-03-17 18:35:25 +00:00
|
|
|
CommandHandler('stopbuy', self._stopbuy),
|
2018-11-10 19:15:06 +00:00
|
|
|
CommandHandler('whitelist', self._whitelist),
|
2019-09-02 18:17:23 +00:00
|
|
|
CommandHandler('blacklist', self._blacklist),
|
2021-12-11 15:09:20 +00:00
|
|
|
CommandHandler(['blacklist_delete', 'bl_delete'], self._blacklist_delete),
|
2020-08-14 13:44:36 +00:00
|
|
|
CommandHandler('logs', self._logs),
|
2019-03-24 21:56:42 +00:00
|
|
|
CommandHandler('edge', self._edge),
|
2022-01-23 19:58:46 +00:00
|
|
|
CommandHandler('health', self._health),
|
2018-02-13 03:45:59 +00:00
|
|
|
CommandHandler('help', self._help),
|
2021-02-13 18:40:04 +00:00
|
|
|
CommandHandler('version', self._version),
|
2021-02-03 18:06:52 +00:00
|
|
|
]
|
|
|
|
callbacks = [
|
|
|
|
CallbackQueryHandler(self._status_table, pattern='update_status_table'),
|
|
|
|
CallbackQueryHandler(self._daily, pattern='update_daily'),
|
2021-11-05 21:51:35 +00:00
|
|
|
CallbackQueryHandler(self._weekly, pattern='update_weekly'),
|
2021-11-04 19:47:01 +00:00
|
|
|
CallbackQueryHandler(self._monthly, pattern='update_monthly'),
|
2021-02-03 18:06:52 +00:00
|
|
|
CallbackQueryHandler(self._profit, pattern='update_profit'),
|
2021-02-03 18:16:27 +00:00
|
|
|
CallbackQueryHandler(self._balance, pattern='update_balance'),
|
|
|
|
CallbackQueryHandler(self._performance, pattern='update_performance'),
|
2021-11-21 08:51:16 +00:00
|
|
|
CallbackQueryHandler(self._enter_tag_performance,
|
|
|
|
pattern='update_enter_tag_performance'),
|
2022-04-03 08:39:35 +00:00
|
|
|
CallbackQueryHandler(self._exit_reason_performance,
|
|
|
|
pattern='update_exit_reason_performance'),
|
2021-10-21 14:25:38 +00:00
|
|
|
CallbackQueryHandler(self._mix_tag_performance, pattern='update_mix_tag_performance'),
|
2021-06-13 18:04:24 +00:00
|
|
|
CallbackQueryHandler(self._count, pattern='update_count'),
|
2022-01-27 05:40:41 +00:00
|
|
|
CallbackQueryHandler(self._forceenter_inline),
|
2018-02-13 03:45:59 +00:00
|
|
|
]
|
|
|
|
for handle in handles:
|
|
|
|
self._updater.dispatcher.add_handler(handle)
|
2021-02-03 18:06:52 +00:00
|
|
|
|
2021-06-13 18:21:43 +00:00
|
|
|
for callback in callbacks:
|
|
|
|
self._updater.dispatcher.add_handler(callback)
|
2021-02-03 18:06:52 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
self._updater.start_polling(
|
|
|
|
bootstrap_retries=-1,
|
2021-12-31 11:52:32 +00:00
|
|
|
timeout=20,
|
|
|
|
read_latency=60, # Assumed transmission latency
|
2021-04-07 04:57:05 +00:00
|
|
|
drop_pending_updates=True,
|
2018-02-13 03:45:59 +00:00
|
|
|
)
|
2018-03-25 19:37:14 +00:00
|
|
|
logger.info(
|
2018-02-13 03:45:59 +00:00
|
|
|
'rpc.telegram is listening for following commands: %s',
|
|
|
|
[h.command for h in handles]
|
|
|
|
)
|
|
|
|
|
|
|
|
def cleanup(self) -> None:
|
|
|
|
"""
|
|
|
|
Stops all running telegram threads.
|
|
|
|
:return: None
|
|
|
|
"""
|
2021-12-31 11:52:32 +00:00
|
|
|
# This can take up to `timeout` from the call to `start_polling`.
|
2018-02-13 03:45:59 +00:00
|
|
|
self._updater.stop()
|
|
|
|
|
2021-04-20 04:41:58 +00:00
|
|
|
def _format_buy_msg(self, msg: Dict[str, Any]) -> str:
|
|
|
|
if self._rpc._fiat_converter:
|
|
|
|
msg['stake_amount_fiat'] = self._rpc._fiat_converter.convert_amount(
|
|
|
|
msg['stake_amount'], msg['stake_currency'], msg['fiat_currency'])
|
|
|
|
else:
|
|
|
|
msg['stake_amount_fiat'] = 0
|
2021-12-29 13:24:12 +00:00
|
|
|
is_fill = msg['type'] in [RPCMessageType.BUY_FILL, RPCMessageType.SHORT_FILL]
|
2021-11-14 08:19:21 +00:00
|
|
|
emoji = '\N{CHECK MARK}' if is_fill else '\N{LARGE BLUE CIRCLE}'
|
2021-04-20 04:41:58 +00:00
|
|
|
|
2021-12-30 16:18:46 +00:00
|
|
|
enter_side = ({'enter': 'Long', 'entered': 'Longed'} if msg['type']
|
|
|
|
in [RPCMessageType.BUY_FILL, RPCMessageType.BUY]
|
|
|
|
else {'enter': 'Short', 'entered': 'Shorted'})
|
2021-11-14 08:19:21 +00:00
|
|
|
message = (
|
2021-12-29 13:24:12 +00:00
|
|
|
f"{emoji} *{msg['exchange']}:*"
|
|
|
|
f" {enter_side['entered'] if is_fill else enter_side['enter']} {msg['pair']}"
|
2021-07-21 18:53:15 +00:00
|
|
|
f" (#{msg['trade_id']})\n"
|
|
|
|
)
|
2021-11-21 08:24:20 +00:00
|
|
|
message += f"*Enter Tag:* `{msg['enter_tag']}`\n" if msg.get('enter_tag', None) else ""
|
2021-11-14 08:19:21 +00:00
|
|
|
message += f"*Amount:* `{msg['amount']:.8f}`\n"
|
2021-12-30 16:32:36 +00:00
|
|
|
if msg.get('leverage') and msg.get('leverage', 1.0) != 1.0:
|
|
|
|
message += f"*Leverage:* `{msg['leverage']}`\n"
|
2021-11-13 20:46:00 +00:00
|
|
|
|
2021-12-29 13:24:12 +00:00
|
|
|
if msg['type'] in [RPCMessageType.BUY_FILL, RPCMessageType.SHORT_FILL]:
|
2021-11-13 20:46:00 +00:00
|
|
|
message += f"*Open Rate:* `{msg['open_rate']:.8f}`\n"
|
2021-12-29 13:24:12 +00:00
|
|
|
elif msg['type'] in [RPCMessageType.BUY, RPCMessageType.SHORT]:
|
2021-11-13 20:46:00 +00:00
|
|
|
message += f"*Open Rate:* `{msg['limit']:.8f}`\n"\
|
|
|
|
f"*Current Rate:* `{msg['current_rate']:.8f}`\n"
|
|
|
|
|
|
|
|
message += f"*Total:* `({round_coin_value(msg['stake_amount'], msg['stake_currency'])}"
|
2021-11-13 15:23:47 +00:00
|
|
|
|
2021-11-13 20:46:00 +00:00
|
|
|
if msg.get('fiat_currency', None):
|
|
|
|
message += f", {round_coin_value(msg['stake_amount_fiat'], msg['fiat_currency'])}"
|
2021-07-21 18:53:15 +00:00
|
|
|
|
2021-04-20 04:41:58 +00:00
|
|
|
message += ")`"
|
|
|
|
return message
|
|
|
|
|
|
|
|
def _format_sell_msg(self, msg: Dict[str, Any]) -> str:
|
|
|
|
msg['amount'] = round(msg['amount'], 8)
|
|
|
|
msg['profit_percent'] = round(msg['profit_ratio'] * 100, 2)
|
|
|
|
msg['duration'] = msg['close_date'].replace(
|
|
|
|
microsecond=0) - msg['open_date'].replace(microsecond=0)
|
|
|
|
msg['duration_min'] = msg['duration'].total_seconds() / 60
|
|
|
|
|
2021-11-21 08:24:20 +00:00
|
|
|
msg['enter_tag'] = msg['enter_tag'] if "enter_tag" in msg.keys() else None
|
2021-04-20 04:41:58 +00:00
|
|
|
msg['emoji'] = self._get_sell_emoji(msg)
|
2021-12-30 16:18:46 +00:00
|
|
|
msg['leverage_text'] = (f"*Leverage:* `{msg['leverage']:.1f}`\n"
|
2021-12-30 16:34:45 +00:00
|
|
|
if msg.get('leverage', None) and msg.get('leverage', 1.0) != 1.0
|
|
|
|
else "")
|
2021-04-20 04:41:58 +00:00
|
|
|
|
|
|
|
# Check if all sell properties are available.
|
|
|
|
# This might not be the case if the message origin is triggered by /forcesell
|
|
|
|
if (all(prop in msg for prop in ['gain', 'fiat_currency', 'stake_currency'])
|
|
|
|
and self._rpc._fiat_converter):
|
|
|
|
msg['profit_fiat'] = self._rpc._fiat_converter.convert_amount(
|
|
|
|
msg['profit_amount'], msg['stake_currency'], msg['fiat_currency'])
|
2021-11-14 08:19:21 +00:00
|
|
|
msg['profit_extra'] = (
|
|
|
|
f" ({msg['gain']}: {msg['profit_amount']:.8f} {msg['stake_currency']}"
|
|
|
|
f" / {msg['profit_fiat']:.3f} {msg['fiat_currency']})")
|
2021-06-01 17:08:22 +00:00
|
|
|
else:
|
|
|
|
msg['profit_extra'] = ''
|
2021-11-14 08:19:21 +00:00
|
|
|
is_fill = msg['type'] == RPCMessageType.SELL_FILL
|
2021-12-30 16:18:46 +00:00
|
|
|
message = (
|
|
|
|
f"{msg['emoji']} *{msg['exchange']}:* "
|
|
|
|
f"{'Exited' if is_fill else 'Exiting'} {msg['pair']} (#{msg['trade_id']})\n"
|
|
|
|
f"*{'Profit' if is_fill else 'Unrealized Profit'}:* "
|
|
|
|
f"`{msg['profit_ratio']:.2%}{msg['profit_extra']}`\n"
|
|
|
|
f"*Enter Tag:* `{msg['enter_tag']}`\n"
|
2022-03-24 19:33:47 +00:00
|
|
|
f"*Exit Reason:* `{msg['exit_reason']}`\n"
|
2021-12-30 16:18:46 +00:00
|
|
|
f"*Duration:* `{msg['duration']} ({msg['duration_min']:.1f} min)`\n"
|
|
|
|
f"*Direction:* `{msg['direction']}`\n"
|
|
|
|
f"{msg['leverage_text']}"
|
|
|
|
f"*Amount:* `{msg['amount']:.8f}`\n"
|
2021-12-29 13:24:12 +00:00
|
|
|
f"*Open Rate:* `{msg['open_rate']:.8f}`\n"
|
2021-12-30 16:18:46 +00:00
|
|
|
)
|
2021-11-13 19:52:59 +00:00
|
|
|
if msg['type'] == RPCMessageType.SELL:
|
2021-11-22 06:13:22 +00:00
|
|
|
message += (f"*Current Rate:* `{msg['current_rate']:.8f}`\n"
|
2021-11-14 08:19:21 +00:00
|
|
|
f"*Close Rate:* `{msg['limit']:.8f}`")
|
2021-11-13 19:52:59 +00:00
|
|
|
|
|
|
|
elif msg['type'] == RPCMessageType.SELL_FILL:
|
2021-11-14 08:19:21 +00:00
|
|
|
message += f"*Close Rate:* `{msg['close_rate']:.8f}`"
|
2021-06-01 17:08:22 +00:00
|
|
|
|
2021-04-20 04:41:58 +00:00
|
|
|
return message
|
|
|
|
|
2021-09-19 17:25:36 +00:00
|
|
|
def compose_message(self, msg: Dict[str, Any], msg_type: RPCMessageType) -> str:
|
2021-12-29 13:24:12 +00:00
|
|
|
if msg_type in [RPCMessageType.BUY, RPCMessageType.BUY_FILL, RPCMessageType.SHORT,
|
|
|
|
RPCMessageType.SHORT_FILL]:
|
2021-04-20 04:41:58 +00:00
|
|
|
message = self._format_buy_msg(msg)
|
2018-07-03 18:26:48 +00:00
|
|
|
|
2021-11-13 15:23:47 +00:00
|
|
|
elif msg_type in [RPCMessageType.SELL, RPCMessageType.SELL_FILL]:
|
|
|
|
message = self._format_sell_msg(msg)
|
|
|
|
|
2021-12-29 13:24:12 +00:00
|
|
|
elif msg_type in (RPCMessageType.BUY_CANCEL, RPCMessageType.SHORT_CANCEL,
|
|
|
|
RPCMessageType.SELL_CANCEL):
|
|
|
|
msg['message_side'] = 'enter' if msg_type in [RPCMessageType.BUY_CANCEL,
|
|
|
|
RPCMessageType.SHORT_CANCEL] else 'exit'
|
2020-06-06 15:28:00 +00:00
|
|
|
message = ("\N{WARNING SIGN} *{exchange}:* "
|
2021-12-29 13:24:12 +00:00
|
|
|
"Cancelling {message_side} Order for {pair} (#{trade_id}). "
|
2021-03-06 13:07:47 +00:00
|
|
|
"Reason: {reason}.".format(**msg))
|
2020-02-08 20:02:52 +00:00
|
|
|
|
2021-09-20 17:12:59 +00:00
|
|
|
elif msg_type == RPCMessageType.PROTECTION_TRIGGER:
|
|
|
|
message = (
|
|
|
|
"*Protection* triggered due to {reason}. "
|
2021-09-20 17:49:18 +00:00
|
|
|
"`{pair}` will be locked until `{lock_end_time}`."
|
2021-09-20 17:12:59 +00:00
|
|
|
).format(**msg)
|
2021-11-13 02:49:07 +00:00
|
|
|
|
2021-09-20 17:23:40 +00:00
|
|
|
elif msg_type == RPCMessageType.PROTECTION_TRIGGER_GLOBAL:
|
|
|
|
message = (
|
|
|
|
"*Protection* triggered due to {reason}. "
|
2021-09-20 17:49:18 +00:00
|
|
|
"*All pairs* will be locked until `{lock_end_time}`."
|
2021-09-20 17:23:40 +00:00
|
|
|
).format(**msg)
|
2021-11-13 02:49:07 +00:00
|
|
|
|
2021-05-27 09:35:27 +00:00
|
|
|
elif msg_type == RPCMessageType.STATUS:
|
2018-07-03 18:26:48 +00:00
|
|
|
message = '*Status:* `{status}`'.format(**msg)
|
|
|
|
|
2021-05-27 09:35:27 +00:00
|
|
|
elif msg_type == RPCMessageType.WARNING:
|
2020-06-05 17:09:49 +00:00
|
|
|
message = '\N{WARNING SIGN} *Warning:* `{status}`'.format(**msg)
|
2018-08-15 02:39:32 +00:00
|
|
|
|
2021-05-27 09:35:27 +00:00
|
|
|
elif msg_type == RPCMessageType.STARTUP:
|
2018-08-15 02:39:32 +00:00
|
|
|
message = '{status}'.format(**msg)
|
|
|
|
|
2018-07-03 18:26:48 +00:00
|
|
|
else:
|
2021-05-27 09:35:27 +00:00
|
|
|
raise NotImplementedError('Unknown message type: {}'.format(msg_type))
|
2021-09-19 17:25:36 +00:00
|
|
|
return message
|
|
|
|
|
|
|
|
def send_msg(self, msg: Dict[str, Any]) -> None:
|
|
|
|
""" Send a message to telegram channel """
|
|
|
|
|
|
|
|
default_noti = 'on'
|
|
|
|
|
|
|
|
msg_type = msg['type']
|
|
|
|
noti = ''
|
|
|
|
if msg_type == RPCMessageType.SELL:
|
|
|
|
sell_noti = self._config['telegram'] \
|
|
|
|
.get('notification_settings', {}).get(str(msg_type), {})
|
|
|
|
# For backward compatibility sell still can be string
|
|
|
|
if isinstance(sell_noti, str):
|
|
|
|
noti = sell_noti
|
|
|
|
else:
|
2022-03-24 19:33:47 +00:00
|
|
|
noti = sell_noti.get(str(msg['exit_reason']), default_noti)
|
2021-09-19 17:25:36 +00:00
|
|
|
else:
|
|
|
|
noti = self._config['telegram'] \
|
|
|
|
.get('notification_settings', {}).get(str(msg_type), default_noti)
|
|
|
|
|
|
|
|
if noti == 'off':
|
|
|
|
logger.info(f"Notification '{msg_type}' not sent.")
|
|
|
|
# Notification disabled
|
|
|
|
return
|
|
|
|
|
|
|
|
message = self.compose_message(msg, msg_type)
|
2018-07-03 18:26:48 +00:00
|
|
|
|
2020-09-19 17:38:33 +00:00
|
|
|
self._send_msg(message, disable_notification=(noti == 'silent'))
|
2018-06-08 01:49:09 +00:00
|
|
|
|
2020-06-06 13:38:42 +00:00
|
|
|
def _get_sell_emoji(self, msg):
|
2020-06-06 11:32:06 +00:00
|
|
|
"""
|
|
|
|
Get emoji for sell-side
|
|
|
|
"""
|
|
|
|
|
|
|
|
if float(msg['profit_percent']) >= 5.0:
|
|
|
|
return "\N{ROCKET}"
|
|
|
|
elif float(msg['profit_percent']) >= 0.0:
|
|
|
|
return "\N{EIGHT SPOKED ASTERISK}"
|
2022-03-24 19:33:47 +00:00
|
|
|
elif msg['exit_reason'] == "stop_loss":
|
2021-11-12 21:18:04 +00:00
|
|
|
return "\N{WARNING SIGN}"
|
2020-06-06 11:32:06 +00:00
|
|
|
else:
|
|
|
|
return "\N{CROSS MARK}"
|
|
|
|
|
2022-02-26 07:19:45 +00:00
|
|
|
def _prepare_entry_details(self, filled_orders: List, base_currency: str, is_open: bool):
|
2022-01-22 06:54:49 +00:00
|
|
|
"""
|
2022-02-07 01:03:54 +00:00
|
|
|
Prepare details of trade with entry adjustment enabled
|
2022-01-22 06:54:49 +00:00
|
|
|
"""
|
2022-02-26 07:19:45 +00:00
|
|
|
lines: List[str] = []
|
|
|
|
if len(filled_orders) > 0:
|
|
|
|
first_avg = filled_orders[0]["safe_price"]
|
|
|
|
|
2022-02-03 18:47:03 +00:00
|
|
|
for x, order in enumerate(filled_orders):
|
2022-03-04 18:42:29 +00:00
|
|
|
if not order['ft_is_entry']:
|
2022-02-27 15:54:14 +00:00
|
|
|
continue
|
2022-02-07 01:52:59 +00:00
|
|
|
cur_entry_datetime = arrow.get(order["order_filled_date"])
|
2022-02-07 01:03:54 +00:00
|
|
|
cur_entry_amount = order["amount"]
|
2022-02-26 07:19:45 +00:00
|
|
|
cur_entry_average = order["safe_price"]
|
2022-01-22 06:54:49 +00:00
|
|
|
lines.append(" ")
|
|
|
|
if x == 0:
|
2022-02-26 07:23:13 +00:00
|
|
|
lines.append(f"*Entry #{x+1}:*")
|
|
|
|
lines.append(
|
|
|
|
f"*Entry Amount:* {cur_entry_amount} ({order['cost']:.8f} {base_currency})")
|
|
|
|
lines.append(f"*Average Entry Price:* {cur_entry_average}")
|
2022-01-22 06:54:49 +00:00
|
|
|
else:
|
|
|
|
sumA = 0
|
|
|
|
sumB = 0
|
|
|
|
for y in range(x):
|
2022-02-26 07:19:45 +00:00
|
|
|
sumA += (filled_orders[y]["amount"] * filled_orders[y]["safe_price"])
|
2022-02-03 18:47:03 +00:00
|
|
|
sumB += filled_orders[y]["amount"]
|
2022-02-26 07:19:45 +00:00
|
|
|
prev_avg_price = sumA / sumB
|
|
|
|
price_to_1st_entry = ((cur_entry_average - first_avg) / first_avg)
|
|
|
|
minus_on_entry = 0
|
|
|
|
if prev_avg_price:
|
|
|
|
minus_on_entry = (cur_entry_average - prev_avg_price) / prev_avg_price
|
|
|
|
|
2022-02-07 01:52:59 +00:00
|
|
|
dur_entry = cur_entry_datetime - arrow.get(filled_orders[x-1]["order_filled_date"])
|
2022-02-07 01:03:54 +00:00
|
|
|
days = dur_entry.days
|
|
|
|
hours, remainder = divmod(dur_entry.seconds, 3600)
|
2022-01-22 06:54:49 +00:00
|
|
|
minutes, seconds = divmod(remainder, 60)
|
2022-02-26 07:23:13 +00:00
|
|
|
lines.append(f"*Entry #{x+1}:* at {minus_on_entry:.2%} avg profit")
|
2022-02-06 07:08:27 +00:00
|
|
|
if is_open:
|
2022-02-07 01:52:59 +00:00
|
|
|
lines.append("({})".format(cur_entry_datetime
|
2022-02-06 07:08:27 +00:00
|
|
|
.humanize(granularity=["day", "hour", "minute"])))
|
2022-02-26 07:23:13 +00:00
|
|
|
lines.append(
|
|
|
|
f"*Entry Amount:* {cur_entry_amount} ({order['cost']:.8f} {base_currency})")
|
|
|
|
lines.append(f"*Average Entry Price:* {cur_entry_average} "
|
|
|
|
f"({price_to_1st_entry:.2%} from 1st entry rate)")
|
|
|
|
lines.append(f"*Order filled at:* {order['order_filled_date']}")
|
|
|
|
lines.append(f"({days}d {hours}h {minutes}m {seconds}s from previous entry)")
|
2022-01-22 06:54:49 +00:00
|
|
|
return lines
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _status(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /status.
|
|
|
|
Returns the current TradeThread status
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
|
2020-12-01 18:55:20 +00:00
|
|
|
if context.args and 'table' in context.args:
|
2019-09-02 18:17:23 +00:00
|
|
|
self._status_table(update, context)
|
2018-02-13 03:45:59 +00:00
|
|
|
return
|
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
try:
|
2021-01-17 19:39:35 +00:00
|
|
|
|
2021-01-17 20:26:55 +00:00
|
|
|
# Check if there's at least one numerical ID provided.
|
|
|
|
# If so, try to get only these trades.
|
2021-01-18 14:26:53 +00:00
|
|
|
trade_ids = []
|
2021-01-17 19:39:35 +00:00
|
|
|
if context.args and len(context.args) > 0:
|
2021-01-18 14:26:53 +00:00
|
|
|
trade_ids = [int(i) for i in context.args if i.isnumeric()]
|
2021-01-17 19:39:35 +00:00
|
|
|
|
|
|
|
results = self._rpc._rpc_trade_status(trade_ids=trade_ids)
|
2022-02-03 18:41:45 +00:00
|
|
|
position_adjust = self._config.get('position_adjustment_enable', False)
|
2022-02-06 02:21:16 +00:00
|
|
|
max_entries = self._config.get('max_entry_position_adjustment', -1)
|
2019-03-27 20:12:57 +00:00
|
|
|
messages = []
|
|
|
|
for r in results:
|
2021-04-13 04:17:11 +00:00
|
|
|
r['open_date_hum'] = arrow.get(r['open_date']).humanize()
|
2022-03-04 18:42:29 +00:00
|
|
|
r['num_entries'] = len([o for o in r['orders'] if o['ft_is_entry']])
|
2022-03-24 19:33:47 +00:00
|
|
|
r['exit_reason'] = r.get('exit_reason', "")
|
2019-03-27 20:12:57 +00:00
|
|
|
lines = [
|
2022-02-06 03:16:56 +00:00
|
|
|
"*Trade ID:* `{trade_id}`" +
|
|
|
|
("` (since {open_date_hum})`" if r['is_open'] else ""),
|
2019-03-27 20:12:57 +00:00
|
|
|
"*Current Pair:* {pair}",
|
2021-12-29 13:24:12 +00:00
|
|
|
"*Direction:* " + ("`Short`" if r.get('is_short') else "`Long`"),
|
|
|
|
"*Leverage:* `{leverage}`" if r.get('leverage') else "",
|
2019-04-03 14:28:44 +00:00
|
|
|
"*Amount:* `{amount} ({stake_amount} {base_currency})`",
|
2021-11-21 08:24:20 +00:00
|
|
|
"*Enter Tag:* `{enter_tag}`" if r['enter_tag'] else "",
|
2022-03-24 19:33:47 +00:00
|
|
|
"*Exit Reason:* `{exit_reason}`" if r['exit_reason'] else "",
|
2022-01-22 06:54:49 +00:00
|
|
|
]
|
|
|
|
|
2022-02-03 18:41:45 +00:00
|
|
|
if position_adjust:
|
2022-02-06 03:04:23 +00:00
|
|
|
max_buy_str = (f"/{max_entries + 1}" if (max_entries > 0) else "")
|
2022-02-07 01:03:54 +00:00
|
|
|
lines.append("*Number of Entries:* `{num_entries}`" + max_buy_str)
|
2022-01-22 06:54:49 +00:00
|
|
|
|
|
|
|
lines.extend([
|
2019-03-27 20:12:57 +00:00
|
|
|
"*Open Rate:* `{open_rate:.8f}`",
|
2022-01-22 06:54:49 +00:00
|
|
|
"*Close Rate:* `{close_rate:.8f}`" if r['close_rate'] else "",
|
|
|
|
"*Open Date:* `{open_date}`",
|
|
|
|
"*Close Date:* `{close_date}`" if r['close_date'] else "",
|
2022-02-06 02:49:02 +00:00
|
|
|
"*Current Rate:* `{current_rate:.8f}`" if r['is_open'] else "",
|
2020-11-03 07:34:12 +00:00
|
|
|
("*Current Profit:* " if r['is_open'] else "*Close Profit: *")
|
2021-11-11 11:58:38 +00:00
|
|
|
+ "`{profit_ratio:.2%}`",
|
2022-01-22 06:54:49 +00:00
|
|
|
])
|
|
|
|
|
2022-02-06 02:49:02 +00:00
|
|
|
if r['is_open']:
|
|
|
|
if (r['stop_loss_abs'] != r['initial_stop_loss_abs']
|
|
|
|
and r['initial_stop_loss_ratio'] is not None):
|
|
|
|
# Adding initial stoploss only if it is different from stoploss
|
|
|
|
lines.append("*Initial Stoploss:* `{initial_stop_loss_abs:.8f}` "
|
2022-02-06 03:16:56 +00:00
|
|
|
"`({initial_stop_loss_ratio:.2%})`")
|
2022-02-06 02:49:02 +00:00
|
|
|
|
|
|
|
# Adding stoploss and stoploss percentage only if it is not None
|
|
|
|
lines.append("*Stoploss:* `{stop_loss_abs:.8f}` " +
|
2022-02-06 03:16:56 +00:00
|
|
|
("`({stop_loss_ratio:.2%})`" if r['stop_loss_ratio'] else ""))
|
2022-02-06 02:49:02 +00:00
|
|
|
lines.append("*Stoploss distance:* `{stoploss_current_dist:.8f}` "
|
2022-02-06 03:16:56 +00:00
|
|
|
"`({stoploss_current_dist_ratio:.2%})`")
|
2022-02-06 02:49:02 +00:00
|
|
|
if r['open_order']:
|
2022-04-03 09:17:01 +00:00
|
|
|
if r['exit_order_status']:
|
|
|
|
lines.append("*Open Order:* `{open_order}` - `{exit_order_status}`")
|
2022-02-06 02:49:02 +00:00
|
|
|
else:
|
|
|
|
lines.append("*Open Order:* `{open_order}`")
|
2020-05-17 08:52:20 +00:00
|
|
|
|
2022-02-07 01:03:54 +00:00
|
|
|
lines_detail = self._prepare_entry_details(
|
2022-02-27 15:54:14 +00:00
|
|
|
r['orders'], r['base_currency'], r['is_open'])
|
|
|
|
lines.extend(lines_detail if lines_detail else "")
|
2020-05-17 08:52:20 +00:00
|
|
|
|
2019-07-14 18:14:35 +00:00
|
|
|
# Filter empty lines using list-comprehension
|
2020-05-18 09:40:25 +00:00
|
|
|
messages.append("\n".join([line for line in lines if line]).format(**r))
|
2019-03-27 20:12:57 +00:00
|
|
|
|
2018-06-22 01:54:10 +00:00
|
|
|
for msg in messages:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(msg)
|
2019-03-27 20:12:57 +00:00
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _status_table(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /status table.
|
|
|
|
Returns the current TradeThread status in table format
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2018-06-08 02:52:50 +00:00
|
|
|
try:
|
2021-05-17 08:12:11 +00:00
|
|
|
fiat_currency = self._config.get('fiat_display_currency', '')
|
2021-05-17 12:59:03 +00:00
|
|
|
statlist, head, fiat_profit_sum = self._rpc._rpc_status_table(
|
2021-05-17 08:12:11 +00:00
|
|
|
self._config['stake_currency'], fiat_currency)
|
2020-12-24 08:01:53 +00:00
|
|
|
|
2021-05-17 12:59:03 +00:00
|
|
|
show_total = not isnan(fiat_profit_sum) and len(statlist) > 1
|
2021-03-22 19:40:11 +00:00
|
|
|
max_trades_per_msg = 50
|
2021-03-23 20:52:46 +00:00
|
|
|
"""
|
|
|
|
Calculate the number of messages of 50 trades per message
|
|
|
|
0.99 is used to make sure that there are no extra (empty) messages
|
|
|
|
As an example with 50 trades, there will be int(50/50 + 0.99) = 1 message
|
|
|
|
"""
|
2021-05-17 08:12:11 +00:00
|
|
|
messages_count = max(int(len(statlist) / max_trades_per_msg + 0.99), 1)
|
|
|
|
for i in range(0, messages_count):
|
2021-05-17 09:41:44 +00:00
|
|
|
trades = statlist[i * max_trades_per_msg:(i + 1) * max_trades_per_msg]
|
2021-05-17 08:12:11 +00:00
|
|
|
if show_total and i == messages_count - 1:
|
|
|
|
# append total line
|
2021-05-17 12:59:03 +00:00
|
|
|
trades.append(["Total", "", "", f"{fiat_profit_sum:.2f} {fiat_currency}"])
|
2021-05-17 08:12:11 +00:00
|
|
|
|
2021-05-17 09:41:44 +00:00
|
|
|
message = tabulate(trades,
|
2021-03-22 19:40:11 +00:00
|
|
|
headers=head,
|
|
|
|
tablefmt='simple')
|
2021-05-17 08:12:11 +00:00
|
|
|
if show_total and i == messages_count - 1:
|
|
|
|
# insert separators line between Total
|
|
|
|
lines = message.split("\n")
|
|
|
|
message = "\n".join(lines[:-1] + [lines[1]] + [lines[-1]])
|
2021-06-13 18:39:25 +00:00
|
|
|
self._send_msg(f"<pre>{message}</pre>", parse_mode=ParseMode.HTML,
|
|
|
|
reload_able=True, callback_path="update_status_table",
|
2021-06-13 18:34:08 +00:00
|
|
|
query=update.callback_query)
|
2018-06-08 02:52:50 +00:00
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _daily(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /daily <n>
|
|
|
|
Returns a daily profit (in BTC) over the last n days.
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2018-06-23 22:17:10 +00:00
|
|
|
stake_cur = self._config['stake_currency']
|
2018-07-26 06:26:23 +00:00
|
|
|
fiat_disp_cur = self._config.get('fiat_display_currency', '')
|
2018-02-13 03:45:59 +00:00
|
|
|
try:
|
2020-12-05 07:16:40 +00:00
|
|
|
timescale = int(context.args[0]) if context.args else 7
|
2019-09-02 18:17:23 +00:00
|
|
|
except (TypeError, ValueError, IndexError):
|
2018-02-13 03:45:59 +00:00
|
|
|
timescale = 7
|
2018-06-08 02:52:50 +00:00
|
|
|
try:
|
2020-12-24 08:01:53 +00:00
|
|
|
stats = self._rpc._rpc_daily_profit(
|
2018-06-08 02:52:50 +00:00
|
|
|
timescale,
|
2018-06-23 22:17:10 +00:00
|
|
|
stake_cur,
|
|
|
|
fiat_disp_cur
|
2018-06-08 02:52:50 +00:00
|
|
|
)
|
2020-05-17 18:12:01 +00:00
|
|
|
stats_tab = tabulate(
|
|
|
|
[[day['date'],
|
2021-02-13 15:05:56 +00:00
|
|
|
f"{round_coin_value(day['abs_profit'], stats['stake_currency'])}",
|
2020-08-18 18:12:14 +00:00
|
|
|
f"{day['fiat_value']:.3f} {stats['fiat_display_currency']}",
|
2020-05-17 18:12:01 +00:00
|
|
|
f"{day['trade_count']} trades"] for day in stats['data']],
|
|
|
|
headers=[
|
2021-11-05 19:24:40 +00:00
|
|
|
'Day',
|
2020-05-17 18:12:01 +00:00
|
|
|
f'Profit {stake_cur}',
|
|
|
|
f'Profit {fiat_disp_cur}',
|
2020-05-18 09:40:25 +00:00
|
|
|
'Trades',
|
2020-05-17 18:12:01 +00:00
|
|
|
],
|
|
|
|
tablefmt='simple')
|
2019-01-17 19:28:21 +00:00
|
|
|
message = f'<b>Daily Profit over the last {timescale} days</b>:\n<pre>{stats_tab}</pre>'
|
2021-06-13 18:39:25 +00:00
|
|
|
self._send_msg(message, parse_mode=ParseMode.HTML, reload_able=True,
|
|
|
|
callback_path="update_daily", query=update.callback_query)
|
2018-06-08 02:52:50 +00:00
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2021-11-04 19:47:01 +00:00
|
|
|
@authorized_only
|
|
|
|
def _weekly(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /weekly <n>
|
|
|
|
Returns a weekly profit (in BTC) over the last n weeks.
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
stake_cur = self._config['stake_currency']
|
|
|
|
fiat_disp_cur = self._config.get('fiat_display_currency', '')
|
|
|
|
try:
|
|
|
|
timescale = int(context.args[0]) if context.args else 8
|
|
|
|
except (TypeError, ValueError, IndexError):
|
|
|
|
timescale = 8
|
|
|
|
try:
|
|
|
|
stats = self._rpc._rpc_weekly_profit(
|
|
|
|
timescale,
|
|
|
|
stake_cur,
|
|
|
|
fiat_disp_cur
|
|
|
|
)
|
|
|
|
stats_tab = tabulate(
|
|
|
|
[[week['date'],
|
|
|
|
f"{round_coin_value(week['abs_profit'], stats['stake_currency'])}",
|
|
|
|
f"{week['fiat_value']:.3f} {stats['fiat_display_currency']}",
|
|
|
|
f"{week['trade_count']} trades"] for week in stats['data']],
|
|
|
|
headers=[
|
2021-11-05 19:24:40 +00:00
|
|
|
'Monday',
|
2021-11-04 19:47:01 +00:00
|
|
|
f'Profit {stake_cur}',
|
|
|
|
f'Profit {fiat_disp_cur}',
|
|
|
|
'Trades',
|
|
|
|
],
|
|
|
|
tablefmt='simple')
|
2021-11-05 19:24:40 +00:00
|
|
|
message = f'<b>Weekly Profit over the last {timescale} weeks ' \
|
|
|
|
f'(starting from Monday)</b>:\n<pre>{stats_tab}</pre> '
|
2021-11-04 19:47:01 +00:00
|
|
|
self._send_msg(message, parse_mode=ParseMode.HTML, reload_able=True,
|
|
|
|
callback_path="update_weekly", query=update.callback_query)
|
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
|
|
|
@authorized_only
|
|
|
|
def _monthly(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /monthly <n>
|
|
|
|
Returns a monthly profit (in BTC) over the last n months.
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
stake_cur = self._config['stake_currency']
|
|
|
|
fiat_disp_cur = self._config.get('fiat_display_currency', '')
|
|
|
|
try:
|
|
|
|
timescale = int(context.args[0]) if context.args else 6
|
|
|
|
except (TypeError, ValueError, IndexError):
|
|
|
|
timescale = 6
|
|
|
|
try:
|
|
|
|
stats = self._rpc._rpc_monthly_profit(
|
|
|
|
timescale,
|
|
|
|
stake_cur,
|
|
|
|
fiat_disp_cur
|
|
|
|
)
|
|
|
|
stats_tab = tabulate(
|
|
|
|
[[month['date'],
|
|
|
|
f"{round_coin_value(month['abs_profit'], stats['stake_currency'])}",
|
|
|
|
f"{month['fiat_value']:.3f} {stats['fiat_display_currency']}",
|
|
|
|
f"{month['trade_count']} trades"] for month in stats['data']],
|
|
|
|
headers=[
|
|
|
|
'Month',
|
|
|
|
f'Profit {stake_cur}',
|
|
|
|
f'Profit {fiat_disp_cur}',
|
|
|
|
'Trades',
|
|
|
|
],
|
|
|
|
tablefmt='simple')
|
2021-11-05 19:24:40 +00:00
|
|
|
message = f'<b>Monthly Profit over the last {timescale} months' \
|
|
|
|
f'</b>:\n<pre>{stats_tab}</pre> '
|
2021-11-04 19:47:01 +00:00
|
|
|
self._send_msg(message, parse_mode=ParseMode.HTML, reload_able=True,
|
|
|
|
callback_path="update_monthly", query=update.callback_query)
|
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _profit(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /profit.
|
|
|
|
Returns a cumulative profit statistics.
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2018-06-23 22:17:10 +00:00
|
|
|
stake_cur = self._config['stake_currency']
|
2018-07-26 06:26:23 +00:00
|
|
|
fiat_disp_cur = self._config.get('fiat_display_currency', '')
|
2018-06-23 22:17:10 +00:00
|
|
|
|
2021-05-19 21:33:33 +00:00
|
|
|
start_date = datetime.fromtimestamp(0)
|
2021-06-08 18:10:43 +00:00
|
|
|
timescale = None
|
2021-05-28 07:17:26 +00:00
|
|
|
try:
|
2021-05-28 14:18:23 +00:00
|
|
|
if context.args:
|
2021-06-23 04:30:08 +00:00
|
|
|
timescale = int(context.args[0]) - 1
|
2021-05-28 14:18:23 +00:00
|
|
|
today_start = datetime.combine(date.today(), datetime.min.time())
|
|
|
|
start_date = today_start - timedelta(days=timescale)
|
2021-05-28 07:17:26 +00:00
|
|
|
except (TypeError, ValueError, IndexError):
|
|
|
|
pass
|
2021-05-19 21:33:33 +00:00
|
|
|
|
2020-12-24 08:01:53 +00:00
|
|
|
stats = self._rpc._rpc_trade_statistics(
|
2020-05-29 08:10:45 +00:00
|
|
|
stake_cur,
|
2021-05-19 21:33:33 +00:00
|
|
|
fiat_disp_cur,
|
|
|
|
start_date)
|
2020-05-29 08:10:45 +00:00
|
|
|
profit_closed_coin = stats['profit_closed_coin']
|
2021-11-11 11:58:38 +00:00
|
|
|
profit_closed_ratio_mean = stats['profit_closed_ratio_mean']
|
2021-07-14 18:55:11 +00:00
|
|
|
profit_closed_percent = stats['profit_closed_percent']
|
2020-05-29 08:10:45 +00:00
|
|
|
profit_closed_fiat = stats['profit_closed_fiat']
|
|
|
|
profit_all_coin = stats['profit_all_coin']
|
2021-11-11 11:58:38 +00:00
|
|
|
profit_all_ratio_mean = stats['profit_all_ratio_mean']
|
2021-07-14 18:55:11 +00:00
|
|
|
profit_all_percent = stats['profit_all_percent']
|
2020-05-29 08:10:45 +00:00
|
|
|
profit_all_fiat = stats['profit_all_fiat']
|
|
|
|
trade_count = stats['trade_count']
|
|
|
|
first_trade_date = stats['first_trade_date']
|
|
|
|
latest_trade_date = stats['latest_trade_date']
|
|
|
|
avg_duration = stats['avg_duration']
|
|
|
|
best_pair = stats['best_pair']
|
2021-11-11 11:58:38 +00:00
|
|
|
best_pair_profit_ratio = stats['best_pair_profit_ratio']
|
2020-05-30 17:42:09 +00:00
|
|
|
if stats['trade_count'] == 0:
|
|
|
|
markdown_msg = 'No trades yet.'
|
2020-05-29 08:10:45 +00:00
|
|
|
else:
|
2020-05-30 17:42:09 +00:00
|
|
|
# Message to display
|
|
|
|
if stats['closed_trade_count'] > 0:
|
|
|
|
markdown_msg = ("*ROI:* Closed trades\n"
|
2021-02-13 15:05:56 +00:00
|
|
|
f"∙ `{round_coin_value(profit_closed_coin, stake_cur)} "
|
2021-11-11 11:58:38 +00:00
|
|
|
f"({profit_closed_ratio_mean:.2%}) "
|
2021-07-14 18:55:11 +00:00
|
|
|
f"({profit_closed_percent} \N{GREEK CAPITAL LETTER SIGMA}%)`\n"
|
2021-02-13 15:05:56 +00:00
|
|
|
f"∙ `{round_coin_value(profit_closed_fiat, fiat_disp_cur)}`\n")
|
2020-05-30 17:42:09 +00:00
|
|
|
else:
|
|
|
|
markdown_msg = "`No closed trade` \n"
|
|
|
|
|
2021-06-08 18:10:43 +00:00
|
|
|
markdown_msg += (
|
|
|
|
f"*ROI:* All trades\n"
|
|
|
|
f"∙ `{round_coin_value(profit_all_coin, stake_cur)} "
|
2021-11-11 11:58:38 +00:00
|
|
|
f"({profit_all_ratio_mean:.2%}) "
|
2021-07-14 18:55:11 +00:00
|
|
|
f"({profit_all_percent} \N{GREEK CAPITAL LETTER SIGMA}%)`\n"
|
2021-06-08 18:10:43 +00:00
|
|
|
f"∙ `{round_coin_value(profit_all_fiat, fiat_disp_cur)}`\n"
|
|
|
|
f"*Total Trade Count:* `{trade_count}`\n"
|
|
|
|
f"*{'First Trade opened' if not timescale else 'Showing Profit since'}:* "
|
|
|
|
f"`{first_trade_date}`\n"
|
|
|
|
f"*Latest Trade opened:* `{latest_trade_date}\n`"
|
|
|
|
f"*Win / Loss:* `{stats['winning_trades']} / {stats['losing_trades']}`"
|
2021-08-06 22:19:36 +00:00
|
|
|
)
|
2020-05-30 17:42:09 +00:00
|
|
|
if stats['closed_trade_count'] > 0:
|
|
|
|
markdown_msg += (f"\n*Avg. Duration:* `{avg_duration}`\n"
|
2021-11-11 11:58:38 +00:00
|
|
|
f"*Best Performing:* `{best_pair}: {best_pair_profit_ratio:.2%}`")
|
2021-06-13 18:39:25 +00:00
|
|
|
self._send_msg(markdown_msg, reload_able=True, callback_path="update_profit",
|
2021-06-13 18:34:08 +00:00
|
|
|
query=update.callback_query)
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2020-12-05 13:39:50 +00:00
|
|
|
@authorized_only
|
|
|
|
def _stats(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /stats
|
|
|
|
Show stats of recent trades
|
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
stats = self._rpc._rpc_stats()
|
2020-12-05 13:39:50 +00:00
|
|
|
|
|
|
|
reason_map = {
|
|
|
|
'roi': 'ROI',
|
|
|
|
'stop_loss': 'Stoploss',
|
|
|
|
'trailing_stop_loss': 'Trail. Stop',
|
|
|
|
'stoploss_on_exchange': 'Stoploss',
|
|
|
|
'sell_signal': 'Sell Signal',
|
|
|
|
'force_sell': 'Forcesell',
|
|
|
|
'emergency_sell': 'Emergency Sell',
|
|
|
|
}
|
2022-03-24 19:33:47 +00:00
|
|
|
exit_reasons_tabulate = [
|
2020-12-10 06:39:50 +00:00
|
|
|
[
|
2020-12-05 13:39:50 +00:00
|
|
|
reason_map.get(reason, reason),
|
|
|
|
sum(count.values()),
|
2020-12-07 13:54:39 +00:00
|
|
|
count['wins'],
|
|
|
|
count['losses']
|
2022-03-24 19:33:47 +00:00
|
|
|
] for reason, count in stats['exit_reasons'].items()
|
2020-12-10 06:39:50 +00:00
|
|
|
]
|
2022-03-24 19:33:47 +00:00
|
|
|
exit_reasons_msg = 'No trades yet.'
|
|
|
|
for reason in chunks(exit_reasons_tabulate, 25):
|
|
|
|
exit_reasons_msg = tabulate(
|
2021-11-14 09:20:04 +00:00
|
|
|
reason,
|
2022-03-24 19:33:47 +00:00
|
|
|
headers=['Exit Reason', 'Exits', 'Wins', 'Losses']
|
2021-11-14 09:20:04 +00:00
|
|
|
)
|
2022-03-24 19:33:47 +00:00
|
|
|
if len(exit_reasons_tabulate) > 25:
|
|
|
|
self._send_msg(exit_reasons_msg, ParseMode.MARKDOWN)
|
|
|
|
exit_reasons_msg = ''
|
2021-11-14 09:20:04 +00:00
|
|
|
|
2020-12-07 13:54:39 +00:00
|
|
|
durations = stats['durations']
|
2021-08-06 22:19:36 +00:00
|
|
|
duration_msg = tabulate(
|
|
|
|
[
|
|
|
|
['Wins', str(timedelta(seconds=durations['wins']))
|
2022-02-10 06:03:19 +00:00
|
|
|
if durations['wins'] is not None else 'N/A'],
|
2021-08-06 22:19:36 +00:00
|
|
|
['Losses', str(timedelta(seconds=durations['losses']))
|
2022-02-10 06:03:19 +00:00
|
|
|
if durations['losses'] is not None else 'N/A']
|
2020-12-07 13:54:39 +00:00
|
|
|
],
|
2020-12-05 13:39:50 +00:00
|
|
|
headers=['', 'Avg. Duration']
|
|
|
|
)
|
2022-03-24 19:33:47 +00:00
|
|
|
msg = (f"""```\n{exit_reasons_msg}```\n```\n{duration_msg}```""")
|
2020-12-05 13:39:50 +00:00
|
|
|
|
|
|
|
self._send_msg(msg, ParseMode.MARKDOWN)
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _balance(self, update: Update, context: CallbackContext) -> None:
|
2018-06-08 22:58:24 +00:00
|
|
|
""" Handler for /balance """
|
2018-06-08 02:52:50 +00:00
|
|
|
try:
|
2020-12-24 08:01:53 +00:00
|
|
|
result = self._rpc._rpc_balance(self._config['stake_currency'],
|
|
|
|
self._config.get('fiat_display_currency', ''))
|
2019-12-15 08:38:18 +00:00
|
|
|
|
2021-02-28 08:03:27 +00:00
|
|
|
balance_dust_level = self._config['telegram'].get('balance_dust_level', 0.0)
|
|
|
|
if not balance_dust_level:
|
|
|
|
balance_dust_level = DUST_PER_COIN.get(self._config['stake_currency'], 1.0)
|
2021-02-17 22:09:39 +00:00
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
output = ''
|
2019-12-15 08:38:18 +00:00
|
|
|
if self._config['dry_run']:
|
2021-09-19 11:16:30 +00:00
|
|
|
output += "*Warning:* Simulated balances in Dry Mode.\n"
|
2022-02-19 15:39:47 +00:00
|
|
|
starting_cap = round_coin_value(
|
|
|
|
result['starting_capital'], self._config['stake_currency'])
|
|
|
|
output += f"Starting capital: `{starting_cap}`"
|
|
|
|
starting_cap_fiat = round_coin_value(
|
|
|
|
result['starting_capital_fiat'], self._config['fiat_display_currency']
|
|
|
|
) if result['starting_capital_fiat'] > 0 else ''
|
|
|
|
output += (f" `, {starting_cap_fiat}`.\n"
|
2021-09-19 11:16:30 +00:00
|
|
|
) if result['starting_capital_fiat'] > 0 else '.\n'
|
|
|
|
|
2021-07-03 19:44:48 +00:00
|
|
|
total_dust_balance = 0
|
|
|
|
total_dust_currencies = 0
|
2021-02-13 15:05:56 +00:00
|
|
|
for curr in result['currencies']:
|
2021-07-10 08:02:05 +00:00
|
|
|
curr_output = ''
|
2021-02-17 22:09:39 +00:00
|
|
|
if curr['est_stake'] > balance_dust_level:
|
2022-02-19 15:28:51 +00:00
|
|
|
if curr['is_position']:
|
|
|
|
curr_output = (
|
|
|
|
f"*{curr['currency']}:*\n"
|
|
|
|
f"\t`{curr['side']}: {curr['position']:.8f}`\n"
|
|
|
|
f"\t`Leverage: {curr['leverage']:.1f}`\n"
|
|
|
|
f"\t`Est. {curr['stake']}: "
|
|
|
|
f"{round_coin_value(curr['est_stake'], curr['stake'], False)}`\n")
|
|
|
|
else:
|
|
|
|
curr_output = (
|
|
|
|
f"*{curr['currency']}:*\n"
|
|
|
|
f"\t`Available: {curr['free']:.8f}`\n"
|
|
|
|
f"\t`Balance: {curr['balance']:.8f}`\n"
|
|
|
|
f"\t`Pending: {curr['used']:.8f}`\n"
|
|
|
|
f"\t`Est. {curr['stake']}: "
|
|
|
|
f"{round_coin_value(curr['est_stake'], curr['stake'], False)}`\n")
|
2021-07-03 19:44:48 +00:00
|
|
|
elif curr['est_stake'] <= balance_dust_level:
|
|
|
|
total_dust_balance += curr['est_stake']
|
|
|
|
total_dust_currencies += 1
|
2019-04-08 17:59:30 +00:00
|
|
|
|
2021-06-25 13:45:49 +00:00
|
|
|
# Handle overflowing message length
|
2019-04-10 04:59:10 +00:00
|
|
|
if len(output + curr_output) >= MAX_TELEGRAM_MESSAGE_LENGTH:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(output)
|
2019-04-08 17:59:30 +00:00
|
|
|
output = curr_output
|
|
|
|
else:
|
|
|
|
output += curr_output
|
2018-06-08 02:52:50 +00:00
|
|
|
|
2021-07-03 19:44:48 +00:00
|
|
|
if total_dust_balance > 0:
|
|
|
|
output += (
|
2021-07-03 19:56:05 +00:00
|
|
|
f"*{total_dust_currencies} Other "
|
2021-07-03 20:08:29 +00:00
|
|
|
f"{plural(total_dust_currencies, 'Currency', 'Currencies')} "
|
|
|
|
f"(< {balance_dust_level} {result['stake']}):*\n"
|
2021-07-03 19:44:48 +00:00
|
|
|
f"\t`Est. {result['stake']}: "
|
|
|
|
f"{round_coin_value(total_dust_balance, result['stake'], False)}`\n")
|
2022-01-16 12:39:50 +00:00
|
|
|
tc = result['trade_count'] > 0
|
|
|
|
stake_improve = f" `({result['starting_capital_ratio']:.2%})`" if tc else ''
|
|
|
|
fiat_val = f" `({result['starting_capital_fiat_ratio']:.2%})`" if tc else ''
|
2021-07-03 19:44:48 +00:00
|
|
|
|
2020-06-06 15:28:00 +00:00
|
|
|
output += ("\n*Estimated Value*:\n"
|
2021-09-19 11:16:30 +00:00
|
|
|
f"\t`{result['stake']}: "
|
|
|
|
f"{round_coin_value(result['total'], result['stake'], False)}`"
|
2022-01-16 12:39:50 +00:00
|
|
|
f"{stake_improve}\n"
|
2021-02-13 15:05:56 +00:00
|
|
|
f"\t`{result['symbol']}: "
|
2021-09-19 11:16:30 +00:00
|
|
|
f"{round_coin_value(result['value'], result['symbol'], False)}`"
|
2022-01-16 12:39:50 +00:00
|
|
|
f"{fiat_val}\n")
|
2021-06-13 18:39:25 +00:00
|
|
|
self._send_msg(output, reload_able=True, callback_path="update_balance",
|
2021-06-13 18:34:08 +00:00
|
|
|
query=update.callback_query)
|
2018-06-08 02:52:50 +00:00
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _start(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /start.
|
|
|
|
Starts TradeThread
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
msg = self._rpc._rpc_start()
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg('Status: `{status}`'.format(**msg))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _stop(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /stop.
|
|
|
|
Stops TradeThread
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
msg = self._rpc._rpc_stop()
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg('Status: `{status}`'.format(**msg))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2018-06-09 02:29:48 +00:00
|
|
|
@authorized_only
|
2020-06-09 21:03:55 +00:00
|
|
|
def _reload_config(self, update: Update, context: CallbackContext) -> None:
|
2018-06-09 02:29:48 +00:00
|
|
|
"""
|
2020-06-09 21:03:55 +00:00
|
|
|
Handler for /reload_config.
|
2018-06-09 02:29:48 +00:00
|
|
|
Triggers a config file reload
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
msg = self._rpc._rpc_reload_config()
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg('Status: `{status}`'.format(**msg))
|
2018-06-09 02:29:48 +00:00
|
|
|
|
2019-03-17 18:35:25 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _stopbuy(self, update: Update, context: CallbackContext) -> None:
|
2019-03-17 18:35:25 +00:00
|
|
|
"""
|
|
|
|
Handler for /stop_buy.
|
|
|
|
Sets max_open_trades to 0 and gracefully sells all open trades
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
msg = self._rpc._rpc_stopbuy()
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg('Status: `{status}`'.format(**msg))
|
2019-03-17 18:35:25 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
@authorized_only
|
2022-01-26 19:17:00 +00:00
|
|
|
def _forceexit(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /forcesell <id>.
|
|
|
|
Sells the given trade at current price
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
|
2020-12-01 18:55:20 +00:00
|
|
|
trade_id = context.args[0] if context.args and len(context.args) > 0 else None
|
|
|
|
if not trade_id:
|
|
|
|
self._send_msg("You must specify a trade-id or 'all'.")
|
|
|
|
return
|
2018-06-08 02:52:50 +00:00
|
|
|
try:
|
2022-01-26 19:17:00 +00:00
|
|
|
msg = self._rpc._rpc_forceexit(trade_id)
|
2022-03-07 19:32:16 +00:00
|
|
|
self._send_msg('Forceexit Result: `{result}`'.format(**msg))
|
2019-04-30 04:23:14 +00:00
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2022-01-26 18:53:46 +00:00
|
|
|
def _forceenter_action(self, pair, price: Optional[float], order_side: SignalDirection):
|
2022-02-11 18:37:35 +00:00
|
|
|
if pair != 'cancel':
|
|
|
|
try:
|
2022-02-23 05:27:56 +00:00
|
|
|
self._rpc._rpc_force_entry(pair, price, order_side=order_side)
|
2022-02-11 18:37:35 +00:00
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
2021-04-10 23:13:04 +00:00
|
|
|
|
2022-01-27 05:40:41 +00:00
|
|
|
def _forceenter_inline(self, update: Update, _: CallbackContext) -> None:
|
2021-04-15 12:31:20 +00:00
|
|
|
if update.callback_query:
|
|
|
|
query = update.callback_query
|
2022-01-27 05:40:41 +00:00
|
|
|
if query.data and '_||_' in query.data:
|
|
|
|
pair, side = query.data.split('_||_')
|
|
|
|
order_side = SignalDirection(side)
|
|
|
|
query.answer()
|
|
|
|
query.edit_message_text(text=f"Manually entering {order_side} for {pair}")
|
|
|
|
self._forceenter_action(pair, None, order_side)
|
2021-04-10 23:13:04 +00:00
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def _layout_inline_keyboard(buttons: List[InlineKeyboardButton],
|
|
|
|
cols=3) -> List[List[InlineKeyboardButton]]:
|
|
|
|
return [buttons[i:i + cols] for i in range(0, len(buttons), cols)]
|
|
|
|
|
2018-10-09 17:25:43 +00:00
|
|
|
@authorized_only
|
2022-01-27 05:31:45 +00:00
|
|
|
def _forceenter(
|
2022-01-26 18:53:46 +00:00
|
|
|
self, update: Update, context: CallbackContext, order_side: SignalDirection) -> None:
|
2018-10-09 17:25:43 +00:00
|
|
|
"""
|
2022-01-27 05:31:45 +00:00
|
|
|
Handler for /forcelong <asset> <price> and `/forceshort <asset> <price>
|
2018-10-09 17:25:43 +00:00
|
|
|
Buys a pair trade at the given or current price
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2020-12-01 18:55:20 +00:00
|
|
|
if context.args:
|
|
|
|
pair = context.args[0]
|
|
|
|
price = float(context.args[1]) if len(context.args) > 1 else None
|
2022-01-26 18:53:46 +00:00
|
|
|
self._forceenter_action(pair, price, order_side)
|
2021-03-31 21:08:53 +00:00
|
|
|
else:
|
|
|
|
whitelist = self._rpc._rpc_whitelist()['whitelist']
|
2022-01-26 18:53:46 +00:00
|
|
|
pair_buttons = [
|
|
|
|
InlineKeyboardButton(text=pair, callback_data=f"{pair}_||_{order_side}")
|
2022-02-23 05:27:56 +00:00
|
|
|
for pair in sorted(whitelist)
|
2022-01-26 18:53:46 +00:00
|
|
|
]
|
2022-02-11 18:37:35 +00:00
|
|
|
buttons_aligned = self._layout_inline_keyboard(pair_buttons)
|
2021-06-13 18:04:24 +00:00
|
|
|
|
2022-02-11 18:37:35 +00:00
|
|
|
buttons_aligned.append([InlineKeyboardButton(text='Cancel', callback_data='cancel')])
|
2021-06-13 18:04:24 +00:00
|
|
|
self._send_msg(msg="Which pair?",
|
2022-02-23 05:27:56 +00:00
|
|
|
keyboard=buttons_aligned,
|
2022-01-26 18:53:46 +00:00
|
|
|
query=update.callback_query)
|
2018-10-09 17:25:43 +00:00
|
|
|
|
2020-07-19 15:02:53 +00:00
|
|
|
@authorized_only
|
|
|
|
def _trades(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /trades <n>
|
|
|
|
Returns last n recent trades.
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2020-07-23 02:36:05 +00:00
|
|
|
stake_cur = self._config['stake_currency']
|
2020-07-19 15:02:53 +00:00
|
|
|
try:
|
2020-12-01 18:55:20 +00:00
|
|
|
nrecent = int(context.args[0]) if context.args else 10
|
2020-07-19 15:02:53 +00:00
|
|
|
except (TypeError, ValueError, IndexError):
|
|
|
|
nrecent = 10
|
|
|
|
try:
|
2020-12-24 08:01:53 +00:00
|
|
|
trades = self._rpc._rpc_trade_history(
|
2020-07-19 15:02:53 +00:00
|
|
|
nrecent
|
|
|
|
)
|
|
|
|
trades_tab = tabulate(
|
2021-03-08 21:21:56 +00:00
|
|
|
[[arrow.get(trade['close_date']).humanize(),
|
|
|
|
trade['pair'] + " (#" + str(trade['trade_id']) + ")",
|
2021-11-11 11:58:38 +00:00
|
|
|
f"{(trade['close_profit']):.2%} ({trade['close_profit_abs']})"]
|
2020-07-23 05:50:45 +00:00
|
|
|
for trade in trades['trades']],
|
2020-07-19 15:02:53 +00:00
|
|
|
headers=[
|
2021-03-08 21:21:56 +00:00
|
|
|
'Close Date',
|
|
|
|
'Pair (ID)',
|
2020-07-23 02:36:05 +00:00
|
|
|
f'Profit ({stake_cur})',
|
2020-07-19 15:02:53 +00:00
|
|
|
],
|
|
|
|
tablefmt='simple')
|
2020-07-23 05:12:14 +00:00
|
|
|
message = (f"<b>{min(trades['trades_count'], nrecent)} recent trades</b>:\n"
|
|
|
|
+ (f"<pre>{trades_tab}</pre>" if trades['trades_count'] > 0 else ''))
|
2020-07-19 15:02:53 +00:00
|
|
|
self._send_msg(message, parse_mode=ParseMode.HTML)
|
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
2020-07-20 04:08:18 +00:00
|
|
|
@authorized_only
|
2020-08-04 12:49:59 +00:00
|
|
|
def _delete_trade(self, update: Update, context: CallbackContext) -> None:
|
2020-07-20 04:08:18 +00:00
|
|
|
"""
|
|
|
|
Handler for /delete <id>.
|
|
|
|
Delete the given trade
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
try:
|
2020-12-01 18:55:20 +00:00
|
|
|
if not context.args or len(context.args) == 0:
|
|
|
|
raise RPCException("Trade-id not set.")
|
|
|
|
trade_id = int(context.args[0])
|
2020-12-24 08:01:53 +00:00
|
|
|
msg = self._rpc._rpc_delete(trade_id)
|
2020-08-04 17:56:49 +00:00
|
|
|
self._send_msg((
|
2020-08-04 17:57:28 +00:00
|
|
|
'`{result_msg}`\n'
|
2020-08-04 17:56:49 +00:00
|
|
|
'Please make sure to take care of this asset on the exchange manually.'
|
|
|
|
).format(**msg))
|
2020-07-20 04:08:18 +00:00
|
|
|
|
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _performance(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /performance.
|
|
|
|
Shows a performance statistic from finished trades
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2018-06-08 02:52:50 +00:00
|
|
|
try:
|
2020-12-24 08:01:53 +00:00
|
|
|
trades = self._rpc._rpc_performance()
|
2021-04-03 17:12:36 +00:00
|
|
|
output = "<b>Performance:</b>\n"
|
|
|
|
for i, trade in enumerate(trades):
|
2021-05-15 17:49:21 +00:00
|
|
|
stat_line = (
|
|
|
|
f"{i+1}.\t <code>{trade['pair']}\t"
|
|
|
|
f"{round_coin_value(trade['profit_abs'], self._config['stake_currency'])} "
|
2021-11-11 11:58:38 +00:00
|
|
|
f"({trade['profit_ratio']:.2%}) "
|
2021-05-15 17:49:21 +00:00
|
|
|
f"({trade['count']})</code>\n")
|
2021-04-03 17:12:36 +00:00
|
|
|
|
|
|
|
if len(output + stat_line) >= MAX_TELEGRAM_MESSAGE_LENGTH:
|
2021-04-13 17:20:57 +00:00
|
|
|
self._send_msg(output, parse_mode=ParseMode.HTML)
|
2021-04-03 17:12:36 +00:00
|
|
|
output = stat_line
|
|
|
|
else:
|
|
|
|
output += stat_line
|
|
|
|
|
2021-06-13 18:34:08 +00:00
|
|
|
self._send_msg(output, parse_mode=ParseMode.HTML,
|
2021-06-13 18:39:25 +00:00
|
|
|
reload_able=True, callback_path="update_performance",
|
2021-06-13 18:34:08 +00:00
|
|
|
query=update.callback_query)
|
2018-06-08 02:52:50 +00:00
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2021-10-12 21:02:28 +00:00
|
|
|
@authorized_only
|
2021-11-21 08:51:16 +00:00
|
|
|
def _enter_tag_performance(self, update: Update, context: CallbackContext) -> None:
|
2021-10-12 21:02:28 +00:00
|
|
|
"""
|
|
|
|
Handler for /buys PAIR .
|
|
|
|
Shows a performance statistic from finished trades
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
try:
|
2021-10-18 20:56:41 +00:00
|
|
|
pair = None
|
2021-10-28 18:39:42 +00:00
|
|
|
if context.args and isinstance(context.args[0], str):
|
2021-10-12 21:02:28 +00:00
|
|
|
pair = context.args[0]
|
|
|
|
|
2021-11-21 08:51:16 +00:00
|
|
|
trades = self._rpc._rpc_enter_tag_performance(pair)
|
2022-04-03 08:39:35 +00:00
|
|
|
output = "<b>Entry Tag Performance:</b>\n"
|
2021-10-12 21:02:28 +00:00
|
|
|
for i, trade in enumerate(trades):
|
|
|
|
stat_line = (
|
2021-11-21 08:24:20 +00:00
|
|
|
f"{i+1}.\t <code>{trade['enter_tag']}\t"
|
2021-10-12 21:02:28 +00:00
|
|
|
f"{round_coin_value(trade['profit_abs'], self._config['stake_currency'])} "
|
2021-11-11 11:58:38 +00:00
|
|
|
f"({trade['profit_ratio']:.2%}) "
|
2021-10-12 21:02:28 +00:00
|
|
|
f"({trade['count']})</code>\n")
|
|
|
|
|
|
|
|
if len(output + stat_line) >= MAX_TELEGRAM_MESSAGE_LENGTH:
|
|
|
|
self._send_msg(output, parse_mode=ParseMode.HTML)
|
|
|
|
output = stat_line
|
|
|
|
else:
|
|
|
|
output += stat_line
|
|
|
|
|
|
|
|
self._send_msg(output, parse_mode=ParseMode.HTML,
|
2021-11-21 08:51:16 +00:00
|
|
|
reload_able=True, callback_path="update_enter_tag_performance",
|
2021-10-12 21:02:28 +00:00
|
|
|
query=update.callback_query)
|
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
|
|
|
@authorized_only
|
2022-04-03 08:39:35 +00:00
|
|
|
def _exit_reason_performance(self, update: Update, context: CallbackContext) -> None:
|
2021-10-12 21:02:28 +00:00
|
|
|
"""
|
|
|
|
Handler for /sells.
|
|
|
|
Shows a performance statistic from finished trades
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
try:
|
2021-10-18 20:56:41 +00:00
|
|
|
pair = None
|
2021-10-28 18:39:42 +00:00
|
|
|
if context.args and isinstance(context.args[0], str):
|
2021-10-12 21:02:28 +00:00
|
|
|
pair = context.args[0]
|
|
|
|
|
2022-04-03 08:39:35 +00:00
|
|
|
trades = self._rpc._rpc_exit_reason_performance(pair)
|
|
|
|
output = "<b>Exit Reason Performance:</b>\n"
|
2021-10-12 21:02:28 +00:00
|
|
|
for i, trade in enumerate(trades):
|
|
|
|
stat_line = (
|
2022-04-03 08:39:35 +00:00
|
|
|
f"{i+1}.\t <code>{trade['exit_reason']}\t"
|
2021-10-12 21:02:28 +00:00
|
|
|
f"{round_coin_value(trade['profit_abs'], self._config['stake_currency'])} "
|
2021-11-11 11:58:38 +00:00
|
|
|
f"({trade['profit_ratio']:.2%}) "
|
2021-10-12 21:02:28 +00:00
|
|
|
f"({trade['count']})</code>\n")
|
|
|
|
|
|
|
|
if len(output + stat_line) >= MAX_TELEGRAM_MESSAGE_LENGTH:
|
|
|
|
self._send_msg(output, parse_mode=ParseMode.HTML)
|
|
|
|
output = stat_line
|
|
|
|
else:
|
|
|
|
output += stat_line
|
|
|
|
|
|
|
|
self._send_msg(output, parse_mode=ParseMode.HTML,
|
2022-04-03 08:39:35 +00:00
|
|
|
reload_able=True, callback_path="update_exit_reason_performance",
|
2021-10-12 21:02:28 +00:00
|
|
|
query=update.callback_query)
|
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
|
|
|
@authorized_only
|
|
|
|
def _mix_tag_performance(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /mix_tags.
|
|
|
|
Shows a performance statistic from finished trades
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
try:
|
2021-10-18 20:56:41 +00:00
|
|
|
pair = None
|
2021-10-28 18:39:42 +00:00
|
|
|
if context.args and isinstance(context.args[0], str):
|
2021-10-12 21:02:28 +00:00
|
|
|
pair = context.args[0]
|
|
|
|
|
|
|
|
trades = self._rpc._rpc_mix_tag_performance(pair)
|
2021-10-18 20:56:41 +00:00
|
|
|
output = "<b>Mix Tag Performance:</b>\n"
|
2021-10-12 21:02:28 +00:00
|
|
|
for i, trade in enumerate(trades):
|
|
|
|
stat_line = (
|
|
|
|
f"{i+1}.\t <code>{trade['mix_tag']}\t"
|
|
|
|
f"{round_coin_value(trade['profit_abs'], self._config['stake_currency'])} "
|
2021-11-11 11:58:38 +00:00
|
|
|
f"({trade['profit']:.2%}) "
|
2021-10-12 21:02:28 +00:00
|
|
|
f"({trade['count']})</code>\n")
|
|
|
|
|
|
|
|
if len(output + stat_line) >= MAX_TELEGRAM_MESSAGE_LENGTH:
|
|
|
|
self._send_msg(output, parse_mode=ParseMode.HTML)
|
|
|
|
output = stat_line
|
|
|
|
else:
|
|
|
|
output += stat_line
|
|
|
|
|
|
|
|
self._send_msg(output, parse_mode=ParseMode.HTML,
|
|
|
|
reload_able=True, callback_path="update_mix_tag_performance",
|
|
|
|
query=update.callback_query)
|
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _count(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /count.
|
|
|
|
Returns the number of trades running
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2018-06-08 02:52:50 +00:00
|
|
|
try:
|
2020-12-24 08:01:53 +00:00
|
|
|
counts = self._rpc._rpc_count()
|
2019-04-06 17:58:45 +00:00
|
|
|
message = tabulate({k: [v] for k, v in counts.items()},
|
|
|
|
headers=['current', 'max', 'total stake'],
|
|
|
|
tablefmt='simple')
|
2018-06-08 02:52:50 +00:00
|
|
|
message = "<pre>{}</pre>".format(message)
|
|
|
|
logger.debug(message)
|
2021-06-13 18:34:08 +00:00
|
|
|
self._send_msg(message, parse_mode=ParseMode.HTML,
|
2021-06-13 18:39:25 +00:00
|
|
|
reload_able=True, callback_path="update_count",
|
2021-06-13 18:34:08 +00:00
|
|
|
query=update.callback_query)
|
2018-06-08 02:52:50 +00:00
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2020-10-17 13:15:35 +00:00
|
|
|
@authorized_only
|
|
|
|
def _locks(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /locks.
|
2020-10-20 17:39:38 +00:00
|
|
|
Returns the currently active locks
|
2020-10-17 13:15:35 +00:00
|
|
|
"""
|
2021-04-24 11:28:24 +00:00
|
|
|
rpc_locks = self._rpc._rpc_locks()
|
2021-05-15 08:50:00 +00:00
|
|
|
if not rpc_locks['locks']:
|
|
|
|
self._send_msg('No active locks.', parse_mode=ParseMode.HTML)
|
|
|
|
|
2021-04-24 11:28:24 +00:00
|
|
|
for locks in chunks(rpc_locks['locks'], 25):
|
2020-10-17 13:15:35 +00:00
|
|
|
message = tabulate([[
|
2021-04-24 11:28:24 +00:00
|
|
|
lock['id'],
|
2020-10-17 13:15:35 +00:00
|
|
|
lock['pair'],
|
2020-10-17 18:32:23 +00:00
|
|
|
lock['lock_end_time'],
|
2021-04-24 11:28:24 +00:00
|
|
|
lock['reason']] for lock in locks],
|
|
|
|
headers=['ID', 'Pair', 'Until', 'Reason'],
|
2020-10-17 13:15:35 +00:00
|
|
|
tablefmt='simple')
|
2021-04-24 11:28:24 +00:00
|
|
|
message = f"<pre>{escape(message)}</pre>"
|
2020-10-17 13:15:35 +00:00
|
|
|
logger.debug(message)
|
|
|
|
self._send_msg(message, parse_mode=ParseMode.HTML)
|
|
|
|
|
2021-03-01 19:08:49 +00:00
|
|
|
@authorized_only
|
|
|
|
def _delete_locks(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /delete_locks.
|
|
|
|
Returns the currently active locks
|
|
|
|
"""
|
2021-03-02 05:59:58 +00:00
|
|
|
arg = context.args[0] if context.args and len(context.args) > 0 else None
|
|
|
|
lockid = None
|
|
|
|
pair = None
|
|
|
|
if arg:
|
|
|
|
try:
|
|
|
|
lockid = int(arg)
|
|
|
|
except ValueError:
|
|
|
|
pair = arg
|
|
|
|
|
|
|
|
self._rpc._rpc_delete_lock(lockid=lockid, pair=pair)
|
|
|
|
self._locks(update, context)
|
2020-10-17 13:15:35 +00:00
|
|
|
|
2018-11-10 19:15:06 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _whitelist(self, update: Update, context: CallbackContext) -> None:
|
2018-11-10 19:15:06 +00:00
|
|
|
"""
|
|
|
|
Handler for /whitelist
|
|
|
|
Shows the currently active whitelist
|
|
|
|
"""
|
|
|
|
try:
|
2020-12-24 08:01:53 +00:00
|
|
|
whitelist = self._rpc._rpc_whitelist()
|
2018-12-03 19:31:25 +00:00
|
|
|
|
|
|
|
message = f"Using whitelist `{whitelist['method']}` with {whitelist['length']} pairs\n"
|
2018-11-10 19:15:06 +00:00
|
|
|
message += f"`{', '.join(whitelist['whitelist'])}`"
|
|
|
|
|
|
|
|
logger.debug(message)
|
|
|
|
self._send_msg(message)
|
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2018-11-10 19:15:06 +00:00
|
|
|
|
2019-03-24 15:08:48 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _blacklist(self, update: Update, context: CallbackContext) -> None:
|
2019-03-24 15:08:48 +00:00
|
|
|
"""
|
|
|
|
Handler for /blacklist
|
|
|
|
Shows the currently active blacklist
|
|
|
|
"""
|
2021-12-11 15:20:09 +00:00
|
|
|
self.send_blacklist_msg(self._rpc._rpc_blacklist(context.args))
|
2019-03-24 15:08:48 +00:00
|
|
|
|
2021-12-11 15:09:20 +00:00
|
|
|
def send_blacklist_msg(self, blacklist: Dict):
|
2021-12-11 15:20:09 +00:00
|
|
|
errmsgs = []
|
|
|
|
for pair, error in blacklist['errors'].items():
|
|
|
|
errmsgs.append(f"Error adding `{pair}` to blacklist: `{error['error_msg']}`")
|
|
|
|
if errmsgs:
|
|
|
|
self._send_msg('\n'.join(errmsgs))
|
2019-03-24 15:28:14 +00:00
|
|
|
|
2021-12-11 15:20:09 +00:00
|
|
|
message = f"Blacklist contains {blacklist['length']} pairs\n"
|
|
|
|
message += f"`{', '.join(blacklist['blacklist'])}`"
|
2019-03-24 15:08:48 +00:00
|
|
|
|
2021-12-11 15:20:09 +00:00
|
|
|
logger.debug(message)
|
|
|
|
self._send_msg(message)
|
2019-03-24 15:08:48 +00:00
|
|
|
|
2021-12-11 15:09:20 +00:00
|
|
|
@authorized_only
|
|
|
|
def _blacklist_delete(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /bl_delete
|
|
|
|
Deletes pair(s) from current blacklist
|
|
|
|
"""
|
2021-12-11 19:08:03 +00:00
|
|
|
self.send_blacklist_msg(self._rpc._rpc_blacklist_delete(context.args or []))
|
2019-03-24 15:08:48 +00:00
|
|
|
|
2020-08-14 13:44:36 +00:00
|
|
|
@authorized_only
|
|
|
|
def _logs(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /logs
|
|
|
|
Shows the latest logs
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
try:
|
2020-12-01 18:55:20 +00:00
|
|
|
limit = int(context.args[0]) if context.args else 10
|
2020-08-14 13:44:36 +00:00
|
|
|
except (TypeError, ValueError, IndexError):
|
|
|
|
limit = 10
|
2020-12-06 18:57:48 +00:00
|
|
|
logs = RPC._rpc_get_logs(limit)['logs']
|
2020-08-15 06:31:36 +00:00
|
|
|
msgs = ''
|
2020-08-15 18:15:02 +00:00
|
|
|
msg_template = "*{}* {}: {} \\- `{}`"
|
2020-08-14 13:44:36 +00:00
|
|
|
for logrec in logs:
|
2020-08-15 18:15:02 +00:00
|
|
|
msg = msg_template.format(escape_markdown(logrec[0], version=2),
|
|
|
|
escape_markdown(logrec[2], version=2),
|
|
|
|
escape_markdown(logrec[3], version=2),
|
|
|
|
escape_markdown(logrec[4], version=2))
|
2020-08-15 06:31:36 +00:00
|
|
|
if len(msgs + msg) + 10 >= MAX_TELEGRAM_MESSAGE_LENGTH:
|
2020-08-14 13:44:36 +00:00
|
|
|
# Send message immediately if it would become too long
|
2020-08-15 18:15:02 +00:00
|
|
|
self._send_msg(msgs, parse_mode=ParseMode.MARKDOWN_V2)
|
2020-08-15 06:31:36 +00:00
|
|
|
msgs = msg + '\n'
|
2020-08-14 13:44:36 +00:00
|
|
|
else:
|
|
|
|
# Append message to messages to send
|
2020-08-15 06:31:36 +00:00
|
|
|
msgs += msg + '\n'
|
2020-08-14 13:44:36 +00:00
|
|
|
|
2020-08-15 06:31:36 +00:00
|
|
|
if msgs:
|
2020-08-15 18:15:02 +00:00
|
|
|
self._send_msg(msgs, parse_mode=ParseMode.MARKDOWN_V2)
|
2020-08-14 13:44:36 +00:00
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
2019-03-24 21:36:33 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _edge(self, update: Update, context: CallbackContext) -> None:
|
2019-03-24 21:36:33 +00:00
|
|
|
"""
|
|
|
|
Handler for /edge
|
2019-03-27 20:22:25 +00:00
|
|
|
Shows information related to Edge
|
2019-03-24 21:36:33 +00:00
|
|
|
"""
|
|
|
|
try:
|
2020-12-24 08:01:53 +00:00
|
|
|
edge_pairs = self._rpc._rpc_edge()
|
2021-05-08 17:43:31 +00:00
|
|
|
if not edge_pairs:
|
|
|
|
message = '<b>Edge only validated following pairs:</b>'
|
|
|
|
self._send_msg(message, parse_mode=ParseMode.HTML)
|
|
|
|
|
|
|
|
for chunk in chunks(edge_pairs, 25):
|
|
|
|
edge_pairs_tab = tabulate(chunk, headers='keys', tablefmt='simple')
|
|
|
|
message = (f'<b>Edge only validated following pairs:</b>\n'
|
|
|
|
f'<pre>{edge_pairs_tab}</pre>')
|
|
|
|
|
|
|
|
self._send_msg(message, parse_mode=ParseMode.HTML)
|
|
|
|
|
2019-03-24 21:36:33 +00:00
|
|
|
except RPCException as e:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._send_msg(str(e))
|
2019-03-24 21:36:33 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _help(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /help.
|
|
|
|
Show commands of the bot
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2022-01-27 05:40:41 +00:00
|
|
|
forceenter_text = ("*/forcelong <pair> [<rate>]:* `Instantly buys the given pair. "
|
|
|
|
"Optionally takes a rate at which to buy "
|
|
|
|
"(only applies to limit orders).` \n"
|
|
|
|
)
|
2022-01-27 05:31:45 +00:00
|
|
|
if self._rpc._freqtrade.trading_mode != TradingMode.SPOT:
|
2022-01-27 05:40:41 +00:00
|
|
|
forceenter_text += ("*/forceshort <pair> [<rate>]:* `Instantly shorts the given pair. "
|
|
|
|
"Optionally takes a rate at which to sell "
|
|
|
|
"(only applies to limit orders).` \n")
|
2021-11-13 07:46:06 +00:00
|
|
|
message = (
|
|
|
|
"_BotControl_\n"
|
|
|
|
"------------\n"
|
|
|
|
"*/start:* `Starts the trader`\n"
|
|
|
|
"*/stop:* Stops the trader\n"
|
|
|
|
"*/stopbuy:* `Stops buying, but handles open trades gracefully` \n"
|
2022-01-26 19:17:00 +00:00
|
|
|
"*/forceexit <trade_id>|all:* `Instantly exits the given trade or all trades, "
|
2021-11-13 07:46:06 +00:00
|
|
|
"regardless of profit`\n"
|
2022-01-27 05:40:41 +00:00
|
|
|
f"{forceenter_text if self._config.get('forcebuy_enable', False) else ''}"
|
2021-11-13 07:46:06 +00:00
|
|
|
"*/delete <trade_id>:* `Instantly delete the given trade in the database`\n"
|
|
|
|
"*/whitelist:* `Show current whitelist` \n"
|
|
|
|
"*/blacklist [pair]:* `Show current blacklist, or adds one or more pairs "
|
|
|
|
"to the blacklist.` \n"
|
2021-12-11 19:08:03 +00:00
|
|
|
"*/blacklist_delete [pairs]| /bl_delete [pairs]:* "
|
|
|
|
"`Delete pair / pattern from blacklist. Will reset on reload_conf.` \n"
|
2021-11-13 07:46:06 +00:00
|
|
|
"*/reload_config:* `Reload configuration file` \n"
|
|
|
|
"*/unlock <pair|id>:* `Unlock this Pair (or this lock id if it's numeric)`\n"
|
|
|
|
|
|
|
|
"_Current state_\n"
|
|
|
|
"------------\n"
|
|
|
|
"*/show_config:* `Show running configuration` \n"
|
|
|
|
"*/locks:* `Show currently locked pairs`\n"
|
|
|
|
"*/balance:* `Show account balance per currency`\n"
|
|
|
|
"*/logs [limit]:* `Show latest logs - defaults to 10` \n"
|
|
|
|
"*/count:* `Show number of active trades compared to allowed number of trades`\n"
|
|
|
|
"*/edge:* `Shows validated pairs by Edge if it is enabled` \n"
|
2022-01-23 19:58:46 +00:00
|
|
|
"*/health* `Show latest process timestamp - defaults to 1970-01-01 00:00:00` \n"
|
2021-11-13 07:46:06 +00:00
|
|
|
|
|
|
|
"_Statistics_\n"
|
|
|
|
"------------\n"
|
|
|
|
"*/status <trade_id>|[table]:* `Lists all open trades`\n"
|
|
|
|
" *<trade_id> :* `Lists one or more specific trades.`\n"
|
|
|
|
" `Separate multiple <trade_id> with a blank space.`\n"
|
|
|
|
" *table :* `will display trades in a table`\n"
|
|
|
|
" `pending buy orders are marked with an asterisk (*)`\n"
|
|
|
|
" `pending sell orders are marked with a double asterisk (**)`\n"
|
2021-11-21 08:51:16 +00:00
|
|
|
"*/buys <pair|none>:* `Shows the enter_tag performance`\n"
|
2022-04-03 17:39:13 +00:00
|
|
|
"*/sells <pair|none>:* `Shows the exit reason performance`\n"
|
|
|
|
"*/mix_tags <pair|none>:* `Shows combined entry tag + exit reason performance`\n"
|
2021-11-13 07:46:06 +00:00
|
|
|
"*/trades [limit]:* `Lists last closed trades (limited to 10 by default)`\n"
|
|
|
|
"*/profit [<n>]:* `Lists cumulative profit from all finished trades, "
|
|
|
|
"over the last n days`\n"
|
|
|
|
"*/performance:* `Show performance of each finished trade grouped by pair`\n"
|
|
|
|
"*/daily <n>:* `Shows profit or loss per day, over the last n days`\n"
|
|
|
|
"*/weekly <n>:* `Shows statistics per week, over the last n weeks`\n"
|
|
|
|
"*/monthly <n>:* `Shows statistics per month, over the last n months`\n"
|
|
|
|
"*/stats:* `Shows Wins / losses by Sell reason as well as "
|
|
|
|
"Avg. holding durationsfor buys and sells.`\n"
|
|
|
|
"*/help:* `This help message`\n"
|
|
|
|
"*/version:* `Show version`"
|
|
|
|
)
|
|
|
|
|
|
|
|
self._send_msg(message, parse_mode=ParseMode.MARKDOWN)
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2022-01-23 19:58:46 +00:00
|
|
|
@authorized_only
|
|
|
|
def _health(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /health
|
|
|
|
Shows the last process timestamp
|
|
|
|
"""
|
|
|
|
try:
|
|
|
|
health = self._rpc._health()
|
2022-01-28 06:57:43 +00:00
|
|
|
message = f"Last process: `{health['last_process_loc']}`"
|
2022-01-23 19:58:46 +00:00
|
|
|
self._send_msg(message)
|
|
|
|
except RPCException as e:
|
|
|
|
self._send_msg(str(e))
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
@authorized_only
|
2019-09-02 18:14:41 +00:00
|
|
|
def _version(self, update: Update, context: CallbackContext) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for /version.
|
|
|
|
Show version information
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2021-11-20 16:26:07 +00:00
|
|
|
strategy_version = self._rpc._freqtrade.strategy.version()
|
2021-12-04 13:40:05 +00:00
|
|
|
version_string = f'*Version:* `{__version__}`'
|
|
|
|
if strategy_version is not None:
|
|
|
|
version_string += f', *Strategy version: * `{strategy_version}`'
|
|
|
|
|
|
|
|
self._send_msg(version_string)
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2019-11-17 14:03:45 +00:00
|
|
|
@authorized_only
|
|
|
|
def _show_config(self, update: Update, context: CallbackContext) -> None:
|
|
|
|
"""
|
|
|
|
Handler for /show_config.
|
|
|
|
Show config information information
|
|
|
|
:param bot: telegram bot
|
|
|
|
:param update: message update
|
|
|
|
:return: None
|
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
val = RPC._rpc_show_config(self._config, self._rpc._freqtrade.state)
|
2020-11-08 10:26:02 +00:00
|
|
|
|
2019-12-13 19:27:06 +00:00
|
|
|
if val['trailing_stop']:
|
|
|
|
sl_info = (
|
|
|
|
f"*Initial Stoploss:* `{val['stoploss']}`\n"
|
|
|
|
f"*Trailing stop positive:* `{val['trailing_stop_positive']}`\n"
|
|
|
|
f"*Trailing stop offset:* `{val['trailing_stop_positive_offset']}`\n"
|
|
|
|
f"*Only trail above offset:* `{val['trailing_only_offset_is_reached']}`\n"
|
|
|
|
)
|
|
|
|
|
|
|
|
else:
|
|
|
|
sl_info = f"*Stoploss:* `{val['stoploss']}`\n"
|
|
|
|
|
2022-01-20 01:03:26 +00:00
|
|
|
if val['position_adjustment_enable']:
|
|
|
|
pa_info = (
|
|
|
|
f"*Position adjustment:* On\n"
|
2022-01-27 15:57:50 +00:00
|
|
|
f"*Max enter position adjustment:* `{val['max_entry_position_adjustment']}`\n"
|
2022-01-20 01:03:26 +00:00
|
|
|
)
|
|
|
|
else:
|
2022-01-21 00:35:22 +00:00
|
|
|
pa_info = "*Position adjustment:* Off\n"
|
2022-01-20 01:03:26 +00:00
|
|
|
|
2019-11-17 14:03:45 +00:00
|
|
|
self._send_msg(
|
|
|
|
f"*Mode:* `{'Dry-run' if val['dry_run'] else 'Live'}`\n"
|
|
|
|
f"*Exchange:* `{val['exchange']}`\n"
|
2022-01-26 18:49:15 +00:00
|
|
|
f"*Market: * `{val['trading_mode']}`\n"
|
2019-11-17 14:03:45 +00:00
|
|
|
f"*Stake per trade:* `{val['stake_amount']} {val['stake_currency']}`\n"
|
2020-05-05 19:21:05 +00:00
|
|
|
f"*Max open Trades:* `{val['max_open_trades']}`\n"
|
2019-11-17 14:03:45 +00:00
|
|
|
f"*Minimum ROI:* `{val['minimal_roi']}`\n"
|
2022-03-27 16:03:49 +00:00
|
|
|
f"*Entry strategy:* ```\n{json.dumps(val['entry_pricing'])}```\n"
|
2022-03-28 17:16:12 +00:00
|
|
|
f"*Exit strategy:* ```\n{json.dumps(val['exit_pricing'])}```\n"
|
2019-12-13 19:27:06 +00:00
|
|
|
f"{sl_info}"
|
2022-01-20 01:03:26 +00:00
|
|
|
f"{pa_info}"
|
2020-06-01 18:43:20 +00:00
|
|
|
f"*Timeframe:* `{val['timeframe']}`\n"
|
2020-05-05 19:28:59 +00:00
|
|
|
f"*Strategy:* `{val['strategy']}`\n"
|
2020-05-05 19:21:05 +00:00
|
|
|
f"*Current state:* `{val['state']}`"
|
2019-11-17 14:03:45 +00:00
|
|
|
)
|
|
|
|
|
2021-06-13 18:21:43 +00:00
|
|
|
def _update_msg(self, query: CallbackQuery, msg: str, callback_path: str = "",
|
2021-06-13 18:04:24 +00:00
|
|
|
reload_able: bool = False, parse_mode: str = ParseMode.MARKDOWN) -> None:
|
2021-02-03 18:06:52 +00:00
|
|
|
if reload_able:
|
2021-06-13 18:04:24 +00:00
|
|
|
reply_markup = InlineKeyboardMarkup([
|
|
|
|
[InlineKeyboardButton("Refresh", callback_data=callback_path)],
|
2021-08-06 22:19:36 +00:00
|
|
|
])
|
2021-02-03 18:06:52 +00:00
|
|
|
else:
|
|
|
|
reply_markup = InlineKeyboardMarkup([[]])
|
2021-06-13 18:04:24 +00:00
|
|
|
msg += "\nUpdated: {}".format(datetime.now().ctime())
|
2021-06-13 18:21:43 +00:00
|
|
|
if not query.message:
|
|
|
|
return
|
|
|
|
chat_id = query.message.chat_id
|
|
|
|
message_id = query.message.message_id
|
|
|
|
|
2021-02-03 18:06:52 +00:00
|
|
|
try:
|
2021-06-19 07:31:34 +00:00
|
|
|
self._updater.bot.edit_message_text(
|
|
|
|
chat_id=chat_id,
|
|
|
|
message_id=message_id,
|
|
|
|
text=msg,
|
|
|
|
parse_mode=parse_mode,
|
|
|
|
reply_markup=reply_markup
|
2021-02-03 18:06:52 +00:00
|
|
|
)
|
2021-06-19 07:31:34 +00:00
|
|
|
except BadRequest as e:
|
|
|
|
if 'not modified' in e.message.lower():
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
logger.warning('TelegramError: %s', e.message)
|
|
|
|
except TelegramError as telegram_err:
|
|
|
|
logger.warning('TelegramError: %s! Giving up on that message.', telegram_err.message)
|
2021-02-03 18:06:52 +00:00
|
|
|
|
2020-12-01 18:55:20 +00:00
|
|
|
def _send_msg(self, msg: str, parse_mode: str = ParseMode.MARKDOWN,
|
2021-03-31 21:08:53 +00:00
|
|
|
disable_notification: bool = False,
|
2021-06-17 17:50:49 +00:00
|
|
|
keyboard: List[List[InlineKeyboardButton]] = None,
|
2021-06-13 18:04:24 +00:00
|
|
|
callback_path: str = "",
|
2021-06-13 18:34:08 +00:00
|
|
|
reload_able: bool = False,
|
|
|
|
query: Optional[CallbackQuery] = None) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Send given markdown message
|
|
|
|
:param msg: message
|
|
|
|
:param bot: alternative bot
|
|
|
|
:param parse_mode: telegram parse mode
|
|
|
|
:return: None
|
|
|
|
"""
|
2021-06-17 17:50:49 +00:00
|
|
|
reply_markup: Union[InlineKeyboardMarkup, ReplyKeyboardMarkup]
|
2021-06-13 18:34:08 +00:00
|
|
|
if query:
|
|
|
|
self._update_msg(query=query, msg=msg, parse_mode=parse_mode,
|
|
|
|
callback_path=callback_path, reload_able=reload_able)
|
|
|
|
return
|
2021-06-13 18:04:24 +00:00
|
|
|
if reload_able and self._config['telegram'].get('reload', True):
|
|
|
|
reply_markup = InlineKeyboardMarkup([
|
|
|
|
[InlineKeyboardButton("Refresh", callback_data=callback_path)]])
|
2021-02-03 18:06:52 +00:00
|
|
|
else:
|
2021-06-13 18:04:24 +00:00
|
|
|
if keyboard is not None:
|
|
|
|
reply_markup = InlineKeyboardMarkup(keyboard, resize_keyboard=True)
|
|
|
|
else:
|
|
|
|
reply_markup = ReplyKeyboardMarkup(self._keyboard, resize_keyboard=True)
|
2017-11-17 18:47:29 +00:00
|
|
|
try:
|
2018-02-13 03:45:59 +00:00
|
|
|
try:
|
2019-09-02 18:14:41 +00:00
|
|
|
self._updater.bot.send_message(
|
2018-02-13 03:45:59 +00:00
|
|
|
self._config['telegram']['chat_id'],
|
|
|
|
text=msg,
|
|
|
|
parse_mode=parse_mode,
|
2020-09-19 17:38:33 +00:00
|
|
|
reply_markup=reply_markup,
|
|
|
|
disable_notification=disable_notification,
|
2018-02-13 03:45:59 +00:00
|
|
|
)
|
|
|
|
except NetworkError as network_err:
|
|
|
|
# Sometimes the telegram server resets the current connection,
|
|
|
|
# if this is the case we send the message again.
|
2018-03-25 19:37:14 +00:00
|
|
|
logger.warning(
|
2018-03-04 10:06:40 +00:00
|
|
|
'Telegram NetworkError: %s! Trying one more time.',
|
2018-02-13 03:45:59 +00:00
|
|
|
network_err.message
|
|
|
|
)
|
2019-09-02 18:14:41 +00:00
|
|
|
self._updater.bot.send_message(
|
2018-02-13 03:45:59 +00:00
|
|
|
self._config['telegram']['chat_id'],
|
|
|
|
text=msg,
|
|
|
|
parse_mode=parse_mode,
|
2020-09-19 17:38:33 +00:00
|
|
|
reply_markup=reply_markup,
|
|
|
|
disable_notification=disable_notification,
|
2018-02-13 03:45:59 +00:00
|
|
|
)
|
|
|
|
except TelegramError as telegram_err:
|
2018-03-25 19:37:14 +00:00
|
|
|
logger.warning(
|
2018-03-04 10:06:40 +00:00
|
|
|
'TelegramError: %s! Giving up on that message.',
|
2018-02-13 03:45:59 +00:00
|
|
|
telegram_err.message
|
2017-12-16 02:39:47 +00:00
|
|
|
)
|