2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
This module contains class to define a RPC communications
|
|
|
|
"""
|
2018-03-25 19:37:14 +00:00
|
|
|
import logging
|
2018-06-08 01:49:09 +00:00
|
|
|
from abc import abstractmethod
|
2021-03-01 06:51:33 +00:00
|
|
|
from datetime import date, datetime, timedelta, timezone
|
2019-11-12 13:58:41 +00:00
|
|
|
from math import isnan
|
2022-11-14 06:25:52 +00:00
|
|
|
from typing import Any, Dict, Generator, List, Optional, Tuple, Union
|
2018-03-17 21:44:47 +00:00
|
|
|
|
2018-03-02 15:22:00 +00:00
|
|
|
import arrow
|
2021-10-06 17:36:28 +00:00
|
|
|
import psutil
|
2021-11-05 19:24:40 +00:00
|
|
|
from dateutil.relativedelta import relativedelta
|
2022-01-28 06:57:43 +00:00
|
|
|
from dateutil.tz import tzlocal
|
2021-02-11 19:21:07 +00:00
|
|
|
from numpy import NAN, inf, int64, mean
|
2022-02-09 05:48:26 +00:00
|
|
|
from pandas import DataFrame, NaT
|
2018-03-17 21:44:47 +00:00
|
|
|
|
2021-11-06 15:12:25 +00:00
|
|
|
from freqtrade import __version__
|
2020-07-02 05:10:56 +00:00
|
|
|
from freqtrade.configuration.timerange import TimeRange
|
2022-09-18 11:20:36 +00:00
|
|
|
from freqtrade.constants import CANCEL_REASON, DATETIME_PRINT_FORMAT, Config
|
2020-07-02 05:10:56 +00:00
|
|
|
from freqtrade.data.history import load_data
|
2022-06-18 09:14:28 +00:00
|
|
|
from freqtrade.data.metrics import calculate_max_drawdown
|
2023-02-19 16:11:21 +00:00
|
|
|
from freqtrade.enums import (CandleType, ExitCheckTuple, ExitType, MarketDirection, SignalDirection,
|
|
|
|
State, TradingMode)
|
2020-08-14 13:44:36 +00:00
|
|
|
from freqtrade.exceptions import ExchangeError, PricingError
|
2020-08-04 17:43:22 +00:00
|
|
|
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_msecs
|
2020-08-14 13:44:36 +00:00
|
|
|
from freqtrade.loggers import bufferHandler
|
2022-09-02 05:15:03 +00:00
|
|
|
from freqtrade.misc import decimals_per_coin, shorten_date
|
2022-09-28 04:47:46 +00:00
|
|
|
from freqtrade.persistence import Order, PairLocks, Trade
|
2021-03-01 06:51:33 +00:00
|
|
|
from freqtrade.persistence.models import PairLock
|
2020-12-30 08:57:31 +00:00
|
|
|
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
|
2018-12-11 19:27:30 +00:00
|
|
|
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
|
2022-02-19 09:58:17 +00:00
|
|
|
from freqtrade.wallets import PositionWallet, Wallet
|
2018-02-13 03:45:59 +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 02:52:50 +00:00
|
|
|
class RPCException(Exception):
|
2018-06-08 22:58:24 +00:00
|
|
|
"""
|
|
|
|
Should be raised with a rpc-formatted message in an _rpc_* method
|
|
|
|
if the required state is wrong, i.e.:
|
|
|
|
|
|
|
|
raise RPCException('*Status:* `no active trade`')
|
|
|
|
"""
|
2020-02-08 20:02:52 +00:00
|
|
|
|
2018-06-22 01:32:45 +00:00
|
|
|
def __init__(self, message: str) -> None:
|
|
|
|
super().__init__(self)
|
|
|
|
self.message = message
|
|
|
|
|
|
|
|
def __str__(self):
|
|
|
|
return self.message
|
|
|
|
|
2019-04-04 05:13:40 +00:00
|
|
|
def __json__(self):
|
|
|
|
return {
|
|
|
|
'msg': self.message
|
|
|
|
}
|
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
|
2020-12-24 08:01:53 +00:00
|
|
|
class RPCHandler:
|
2018-07-21 18:44:38 +00:00
|
|
|
|
2022-09-18 11:20:36 +00:00
|
|
|
def __init__(self, rpc: 'RPC', config: Config) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
2020-12-24 08:01:53 +00:00
|
|
|
Initializes RPCHandlers
|
|
|
|
: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
|
|
|
self._rpc = rpc
|
2022-09-18 11:20:36 +00:00
|
|
|
self._config: Config = config
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2018-06-23 10:28:32 +00:00
|
|
|
@property
|
|
|
|
def name(self) -> str:
|
|
|
|
""" Returns the lowercase name of the implementation """
|
|
|
|
return self.__class__.__name__.lower()
|
|
|
|
|
2018-06-08 01:49:09 +00:00
|
|
|
@abstractmethod
|
2018-06-08 02:52:50 +00:00
|
|
|
def cleanup(self) -> None:
|
2018-06-08 01:49:09 +00:00
|
|
|
""" Cleanup pending module resources """
|
|
|
|
|
|
|
|
@abstractmethod
|
2018-06-24 22:04:27 +00:00
|
|
|
def send_msg(self, msg: Dict[str, str]) -> None:
|
2018-06-08 01:49:09 +00:00
|
|
|
""" Sends a message to all registered rpc modules """
|
|
|
|
|
2020-12-24 08:01:53 +00:00
|
|
|
|
|
|
|
class RPC:
|
|
|
|
"""
|
|
|
|
RPC class can be used to have extra feature, like bot data, and access to DB data
|
|
|
|
"""
|
|
|
|
# Bind _fiat_converter if needed
|
|
|
|
_fiat_converter: Optional[CryptoToFiatConverter] = None
|
|
|
|
|
|
|
|
def __init__(self, freqtrade) -> None:
|
|
|
|
"""
|
|
|
|
Initializes all enabled rpc modules
|
|
|
|
:param freqtrade: Instance of a freqtrade bot
|
|
|
|
:return: None
|
|
|
|
"""
|
|
|
|
self._freqtrade = freqtrade
|
2022-09-18 11:20:36 +00:00
|
|
|
self._config: Config = freqtrade.config
|
2022-05-17 22:11:10 +00:00
|
|
|
if self._config.get('fiat_display_currency'):
|
2020-12-24 08:01:53 +00:00
|
|
|
self._fiat_converter = CryptoToFiatConverter()
|
|
|
|
|
2020-11-08 10:26:02 +00:00
|
|
|
@staticmethod
|
2021-12-04 13:49:45 +00:00
|
|
|
def _rpc_show_config(config, botstate: Union[State, str],
|
|
|
|
strategy_version: Optional[str] = None) -> Dict[str, Any]:
|
2019-11-17 13:56:08 +00:00
|
|
|
"""
|
|
|
|
Return a dict of config options.
|
|
|
|
Explicitly does NOT return the full config to avoid leakage of sensitive
|
|
|
|
information via rpc.
|
|
|
|
"""
|
|
|
|
val = {
|
2021-11-06 15:12:25 +00:00
|
|
|
'version': __version__,
|
2021-12-04 13:49:45 +00:00
|
|
|
'strategy_version': strategy_version,
|
2020-01-20 19:24:40 +00:00
|
|
|
'dry_run': config['dry_run'],
|
2021-11-20 19:09:37 +00:00
|
|
|
'trading_mode': config.get('trading_mode', 'spot'),
|
|
|
|
'short_allowed': config.get('trading_mode', 'spot') != 'spot',
|
2019-11-17 13:56:08 +00:00
|
|
|
'stake_currency': config['stake_currency'],
|
2021-10-18 20:56:41 +00:00
|
|
|
'stake_currency_decimals': decimals_per_coin(config['stake_currency']),
|
2022-02-15 19:01:35 +00:00
|
|
|
'stake_amount': str(config['stake_amount']),
|
2021-07-14 18:51:42 +00:00
|
|
|
'available_capital': config.get('available_capital'),
|
2021-01-15 19:47:12 +00:00
|
|
|
'max_open_trades': (config['max_open_trades']
|
|
|
|
if config['max_open_trades'] != float('inf') else -1),
|
2020-11-08 10:26:02 +00:00
|
|
|
'minimal_roi': config['minimal_roi'].copy() if 'minimal_roi' in config else {},
|
|
|
|
'stoploss': config.get('stoploss'),
|
2023-02-08 06:06:03 +00:00
|
|
|
'stoploss_on_exchange': config.get('stoploss_on_exchange', False),
|
2020-11-08 10:26:02 +00:00
|
|
|
'trailing_stop': config.get('trailing_stop'),
|
2019-11-17 14:12:53 +00:00
|
|
|
'trailing_stop_positive': config.get('trailing_stop_positive'),
|
|
|
|
'trailing_stop_positive_offset': config.get('trailing_stop_positive_offset'),
|
|
|
|
'trailing_only_offset_is_reached': config.get('trailing_only_offset_is_reached'),
|
2021-11-06 15:12:25 +00:00
|
|
|
'unfilledtimeout': config.get('unfilledtimeout'),
|
2021-01-30 19:11:18 +00:00
|
|
|
'use_custom_stoploss': config.get('use_custom_stoploss'),
|
2021-11-06 15:12:25 +00:00
|
|
|
'order_types': config.get('order_types'),
|
2021-01-16 15:19:49 +00:00
|
|
|
'bot_name': config.get('bot_name', 'freqtrade'),
|
2020-11-08 10:26:02 +00:00
|
|
|
'timeframe': config.get('timeframe'),
|
|
|
|
'timeframe_ms': timeframe_to_msecs(config['timeframe']
|
2021-04-02 17:58:08 +00:00
|
|
|
) if 'timeframe' in config else 0,
|
2020-11-08 10:26:02 +00:00
|
|
|
'timeframe_min': timeframe_to_minutes(config['timeframe']
|
2021-04-02 17:58:08 +00:00
|
|
|
) if 'timeframe' in config else 0,
|
2019-11-17 13:56:08 +00:00
|
|
|
'exchange': config['exchange']['name'],
|
|
|
|
'strategy': config['strategy'],
|
2022-04-08 11:39:41 +00:00
|
|
|
'force_entry_enable': config.get('force_entry_enable', False),
|
2022-03-27 16:03:49 +00:00
|
|
|
'exit_pricing': config.get('exit_pricing', {}),
|
|
|
|
'entry_pricing': config.get('entry_pricing', {}),
|
2020-11-08 10:26:02 +00:00
|
|
|
'state': str(botstate),
|
2022-01-20 01:03:26 +00:00
|
|
|
'runmode': config['runmode'].value,
|
|
|
|
'position_adjustment_enable': config.get('position_adjustment_enable', False),
|
2022-01-27 15:57:50 +00:00
|
|
|
'max_entry_position_adjustment': (
|
2022-01-28 16:07:34 +00:00
|
|
|
config.get('max_entry_position_adjustment', -1)
|
|
|
|
if config.get('max_entry_position_adjustment') != float('inf')
|
2022-01-27 15:57:50 +00:00
|
|
|
else -1)
|
2019-11-17 13:56:08 +00:00
|
|
|
}
|
|
|
|
return val
|
|
|
|
|
2021-01-18 14:26:53 +00:00
|
|
|
def _rpc_trade_status(self, trade_ids: List[int] = []) -> List[Dict[str, Any]]:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Below follows the RPC backend it is prefixed with rpc_ to raise awareness that it is
|
|
|
|
a remotely exposed function
|
|
|
|
"""
|
2021-01-17 19:39:35 +00:00
|
|
|
# Fetch open trades
|
|
|
|
if trade_ids:
|
2022-03-24 18:58:53 +00:00
|
|
|
trades: List[Trade] = Trade.get_trades(trade_filter=Trade.id.in_(trade_ids)).all()
|
2021-01-17 19:39:35 +00:00
|
|
|
else:
|
|
|
|
trades = Trade.get_open_trades()
|
|
|
|
|
2018-10-10 18:58:21 +00:00
|
|
|
if not trades:
|
2018-06-22 01:37:19 +00:00
|
|
|
raise RPCException('no active trade')
|
2018-02-13 03:45:59 +00:00
|
|
|
else:
|
2018-06-22 01:54:10 +00:00
|
|
|
results = []
|
2018-02-13 03:45:59 +00:00
|
|
|
for trade in trades:
|
2022-09-28 04:47:46 +00:00
|
|
|
order: Optional[Order] = None
|
2022-12-15 06:04:59 +00:00
|
|
|
current_profit_fiat: Optional[float] = None
|
2023-02-28 19:31:02 +00:00
|
|
|
total_profit_fiat: Optional[float] = None
|
2018-02-13 03:45:59 +00:00
|
|
|
if trade.open_order_id:
|
2022-09-28 04:47:46 +00:00
|
|
|
order = trade.select_order_by_order_id(trade.open_order_id)
|
2018-02-13 03:45:59 +00:00
|
|
|
# calculate profit and send message to user
|
2021-04-17 17:29:34 +00:00
|
|
|
if trade.is_open:
|
|
|
|
try:
|
2021-07-18 03:58:54 +00:00
|
|
|
current_rate = self._freqtrade.exchange.get_rate(
|
2022-03-28 05:03:10 +00:00
|
|
|
trade.pair, side='exit', is_short=trade.is_short, refresh=False)
|
2021-04-17 17:29:34 +00:00
|
|
|
except (ExchangeError, PricingError):
|
|
|
|
current_rate = NAN
|
2022-12-15 06:04:59 +00:00
|
|
|
if len(trade.select_filled_orders(trade.entry_side)) > 0:
|
|
|
|
current_profit = trade.calc_profit_ratio(
|
|
|
|
current_rate) if not isnan(current_rate) else NAN
|
|
|
|
current_profit_abs = trade.calc_profit(
|
|
|
|
current_rate) if not isnan(current_rate) else NAN
|
|
|
|
else:
|
|
|
|
current_profit = current_profit_abs = current_profit_fiat = 0.0
|
2021-04-17 17:29:34 +00:00
|
|
|
else:
|
2022-12-15 06:04:59 +00:00
|
|
|
# Closed trade ...
|
2021-04-17 17:29:34 +00:00
|
|
|
current_rate = trade.close_rate
|
2022-12-15 06:04:59 +00:00
|
|
|
current_profit = trade.close_profit
|
|
|
|
current_profit_abs = trade.close_profit_abs
|
2023-02-28 19:31:02 +00:00
|
|
|
total_profit_abs = trade.realized_profit + current_profit_abs
|
2022-12-15 06:04:59 +00:00
|
|
|
|
|
|
|
# Calculate fiat profit
|
|
|
|
if not isnan(current_profit_abs) and self._fiat_converter:
|
|
|
|
current_profit_fiat = self._fiat_converter.convert_amount(
|
|
|
|
current_profit_abs,
|
|
|
|
self._freqtrade.config['stake_currency'],
|
|
|
|
self._freqtrade.config['fiat_display_currency']
|
|
|
|
)
|
2023-02-28 19:31:02 +00:00
|
|
|
total_profit_fiat = self._fiat_converter.convert_amount(
|
|
|
|
total_profit_abs,
|
2023-02-28 18:54:47 +00:00
|
|
|
self._freqtrade.config['stake_currency'],
|
|
|
|
self._freqtrade.config['fiat_display_currency']
|
|
|
|
)
|
2021-04-02 10:20:38 +00:00
|
|
|
|
2020-06-04 04:56:59 +00:00
|
|
|
# Calculate guaranteed profit (in case of trailing stop)
|
2020-06-04 05:04:32 +00:00
|
|
|
stoploss_entry_dist = trade.calc_profit(trade.stop_loss)
|
|
|
|
stoploss_entry_dist_ratio = trade.calc_profit_ratio(trade.stop_loss)
|
2020-06-04 04:56:59 +00:00
|
|
|
# calculate distance to stoploss
|
|
|
|
stoploss_current_dist = trade.stop_loss - current_rate
|
|
|
|
stoploss_current_dist_ratio = stoploss_current_dist / current_rate
|
|
|
|
|
2019-05-05 12:07:08 +00:00
|
|
|
trade_dict = trade.to_json()
|
|
|
|
trade_dict.update(dict(
|
2022-07-31 12:19:04 +00:00
|
|
|
close_profit=trade.close_profit if not trade.is_open else None,
|
2019-05-05 12:07:08 +00:00
|
|
|
current_rate=current_rate,
|
2020-11-03 06:34:21 +00:00
|
|
|
profit_ratio=current_profit,
|
|
|
|
profit_pct=round(current_profit * 100, 2),
|
|
|
|
profit_abs=current_profit_abs,
|
2021-04-02 10:20:38 +00:00
|
|
|
profit_fiat=current_profit_fiat,
|
2020-11-03 06:34:21 +00:00
|
|
|
|
2023-02-28 19:31:02 +00:00
|
|
|
total_profit_abs=total_profit_abs,
|
|
|
|
total_profit_fiat=total_profit_fiat,
|
2020-06-04 04:56:59 +00:00
|
|
|
stoploss_current_dist=stoploss_current_dist,
|
|
|
|
stoploss_current_dist_ratio=round(stoploss_current_dist_ratio, 8),
|
2020-07-14 18:16:18 +00:00
|
|
|
stoploss_current_dist_pct=round(stoploss_current_dist_ratio * 100, 2),
|
2020-06-04 05:04:32 +00:00
|
|
|
stoploss_entry_dist=stoploss_entry_dist,
|
|
|
|
stoploss_entry_dist_ratio=round(stoploss_entry_dist_ratio, 8),
|
2022-11-17 18:58:46 +00:00
|
|
|
open_order=(
|
|
|
|
f'({order.order_type} {order.side} rem={order.safe_remaining:.8f})' if
|
|
|
|
order else None
|
|
|
|
),
|
2018-06-22 01:54:10 +00:00
|
|
|
))
|
2019-05-05 12:07:08 +00:00
|
|
|
results.append(trade_dict)
|
2018-06-22 01:54:10 +00:00
|
|
|
return results
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2020-02-02 04:00:40 +00:00
|
|
|
def _rpc_status_table(self, stake_currency: str,
|
2021-05-17 12:59:03 +00:00
|
|
|
fiat_display_currency: str) -> Tuple[List, List, float]:
|
2022-03-24 18:58:53 +00:00
|
|
|
trades: List[Trade] = Trade.get_open_trades()
|
2022-04-09 15:09:04 +00:00
|
|
|
nonspot = self._config.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT
|
2018-10-10 18:58:21 +00:00
|
|
|
if not trades:
|
2019-12-29 18:51:47 +00:00
|
|
|
raise RPCException('no active trade')
|
2018-02-13 03:45:59 +00:00
|
|
|
else:
|
|
|
|
trades_list = []
|
2021-05-17 12:59:03 +00:00
|
|
|
fiat_profit_sum = NAN
|
2018-02-13 03:45:59 +00:00
|
|
|
for trade in trades:
|
|
|
|
# calculate profit and send message to user
|
2018-10-10 19:28:48 +00:00
|
|
|
try:
|
2021-07-18 03:58:54 +00:00
|
|
|
current_rate = self._freqtrade.exchange.get_rate(
|
2022-03-28 05:03:10 +00:00
|
|
|
trade.pair, side='exit', is_short=trade.is_short, refresh=False)
|
2020-06-28 14:01:40 +00:00
|
|
|
except (PricingError, ExchangeError):
|
2018-10-10 19:28:48 +00:00
|
|
|
current_rate = NAN
|
2022-08-11 15:02:52 +00:00
|
|
|
trade_profit = NAN
|
|
|
|
profit_str = f'{NAN:.2%}'
|
2022-05-07 18:56:22 +00:00
|
|
|
else:
|
2022-08-11 15:02:52 +00:00
|
|
|
if trade.nr_of_successful_entries > 0:
|
|
|
|
trade_profit = trade.calc_profit(current_rate)
|
|
|
|
profit_str = f'{trade.calc_profit_ratio(current_rate):.2%}'
|
|
|
|
else:
|
|
|
|
trade_profit = 0.0
|
|
|
|
profit_str = f'{0.0:.2f}'
|
2022-04-09 15:09:04 +00:00
|
|
|
direction_str = ('S' if trade.is_short else 'L') if nonspot else ''
|
2019-11-12 13:58:41 +00:00
|
|
|
if self._fiat_converter:
|
|
|
|
fiat_profit = self._fiat_converter.convert_amount(
|
2020-02-08 20:02:52 +00:00
|
|
|
trade_profit,
|
|
|
|
stake_currency,
|
|
|
|
fiat_display_currency
|
|
|
|
)
|
2022-05-07 18:56:22 +00:00
|
|
|
if not isnan(fiat_profit):
|
2019-11-12 13:58:41 +00:00
|
|
|
profit_str += f" ({fiat_profit:.2f})"
|
2021-05-17 13:22:48 +00:00
|
|
|
fiat_profit_sum = fiat_profit if isnan(fiat_profit_sum) \
|
|
|
|
else fiat_profit_sum + fiat_profit
|
2022-09-06 17:55:18 +00:00
|
|
|
open_order = (trade.select_order_by_order_id(
|
|
|
|
trade.open_order_id) if trade.open_order_id else None)
|
|
|
|
|
2022-01-19 07:14:21 +00:00
|
|
|
detail_trade = [
|
2021-12-30 12:05:17 +00:00
|
|
|
f'{trade.id} {direction_str}',
|
2022-09-06 17:55:18 +00:00
|
|
|
trade.pair + ('*' if (open_order
|
|
|
|
and open_order.ft_order_side == trade.entry_side) else '')
|
|
|
|
+ ('**' if (open_order and
|
|
|
|
open_order.ft_order_side == trade.exit_side is not None) else ''),
|
2018-02-13 03:45:59 +00:00
|
|
|
shorten_date(arrow.get(trade.open_date).humanize(only_distance=True)),
|
2019-11-12 13:58:41 +00:00
|
|
|
profit_str
|
2022-01-19 07:14:21 +00:00
|
|
|
]
|
|
|
|
if self._config.get('position_adjustment_enable', False):
|
2022-02-13 14:10:09 +00:00
|
|
|
max_entry_str = ''
|
2022-01-29 13:25:33 +00:00
|
|
|
if self._config.get('max_entry_position_adjustment', -1) > 0:
|
2022-02-13 14:10:09 +00:00
|
|
|
max_entry_str = f"/{self._config['max_entry_position_adjustment'] + 1}"
|
|
|
|
filled_entries = trade.nr_of_successful_entries
|
|
|
|
detail_trade.append(f"{filled_entries}{max_entry_str}")
|
2022-01-19 07:14:21 +00:00
|
|
|
trades_list.append(detail_trade)
|
2019-11-12 13:58:41 +00:00
|
|
|
profitcol = "Profit"
|
|
|
|
if self._fiat_converter:
|
|
|
|
profitcol += " (" + fiat_display_currency + ")"
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2022-04-09 15:09:04 +00:00
|
|
|
columns = [
|
|
|
|
'ID L/S' if nonspot else 'ID',
|
|
|
|
'Pair',
|
|
|
|
'Since',
|
|
|
|
profitcol]
|
2022-01-19 07:14:21 +00:00
|
|
|
if self._config.get('position_adjustment_enable', False):
|
2022-02-11 16:02:04 +00:00
|
|
|
columns.append('# Entries')
|
2021-05-17 12:59:03 +00:00
|
|
|
return trades_list, columns, fiat_profit_sum
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2022-06-08 17:52:05 +00:00
|
|
|
def _rpc_timeunit_profit(
|
2018-03-17 22:30:31 +00:00
|
|
|
self, timescale: int,
|
2022-06-08 05:08:01 +00:00
|
|
|
stake_currency: str, fiat_display_currency: str,
|
|
|
|
timeunit: str = 'days') -> Dict[str, Any]:
|
|
|
|
"""
|
|
|
|
:param timeunit: Valid entries are 'days', 'weeks', 'months'
|
|
|
|
"""
|
|
|
|
start_date = datetime.now(timezone.utc).date()
|
|
|
|
if timeunit == 'weeks':
|
|
|
|
# weekly
|
|
|
|
start_date = start_date - timedelta(days=start_date.weekday()) # Monday
|
|
|
|
if timeunit == 'months':
|
|
|
|
start_date = start_date.replace(day=1)
|
|
|
|
|
2022-06-08 17:52:05 +00:00
|
|
|
def time_offset(step: int):
|
|
|
|
if timeunit == 'months':
|
|
|
|
return relativedelta(months=step)
|
|
|
|
return timedelta(**{timeunit: step})
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
if not (isinstance(timescale, int) and timescale > 0):
|
2018-06-22 01:37:19 +00:00
|
|
|
raise RPCException('timescale must be an integer greater than 0')
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2022-06-11 09:18:21 +00:00
|
|
|
profit_units: Dict[date, Dict] = {}
|
|
|
|
daily_stake = self._freqtrade.wallets.get_total_stake_amount()
|
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
for day in range(0, timescale):
|
2022-06-08 17:52:05 +00:00
|
|
|
profitday = start_date - time_offset(day)
|
2022-06-10 05:26:53 +00:00
|
|
|
# Only query for necessary columns for performance reasons.
|
|
|
|
trades = Trade.query.session.query(Trade.close_profit_abs).filter(
|
2019-10-29 14:09:01 +00:00
|
|
|
Trade.is_open.is_(False),
|
|
|
|
Trade.close_date >= profitday,
|
2022-06-08 17:52:05 +00:00
|
|
|
Trade.close_date < (profitday + time_offset(1))
|
2022-06-10 05:26:53 +00:00
|
|
|
).order_by(Trade.close_date).all()
|
|
|
|
|
2020-09-03 17:29:48 +00:00
|
|
|
curdayprofit = sum(
|
|
|
|
trade.close_profit_abs for trade in trades if trade.close_profit_abs is not None)
|
2022-06-11 09:18:21 +00:00
|
|
|
# Calculate this periods starting balance
|
|
|
|
daily_stake = daily_stake - curdayprofit
|
2022-06-08 05:08:01 +00:00
|
|
|
profit_units[profitday] = {
|
2020-08-18 18:12:14 +00:00
|
|
|
'amount': curdayprofit,
|
2022-06-11 09:18:21 +00:00
|
|
|
'daily_stake': daily_stake,
|
|
|
|
'rel_profit': round(curdayprofit / daily_stake, 8) if daily_stake > 0 else 0,
|
2022-06-10 05:26:53 +00:00
|
|
|
'trades': len(trades),
|
2018-02-13 03:45:59 +00:00
|
|
|
}
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2020-05-17 18:12:01 +00:00
|
|
|
data = [
|
|
|
|
{
|
2022-06-08 17:52:05 +00:00
|
|
|
'date': f"{key.year}-{key.month:02d}" if timeunit == 'months' else key,
|
2020-08-18 18:12:14 +00:00
|
|
|
'abs_profit': value["amount"],
|
2022-06-11 09:18:21 +00:00
|
|
|
'starting_balance': value["daily_stake"],
|
|
|
|
'rel_profit': value["rel_profit"],
|
2020-08-18 18:12:14 +00:00
|
|
|
'fiat_value': self._fiat_converter.convert_amount(
|
2021-07-18 03:58:54 +00:00
|
|
|
value['amount'],
|
|
|
|
stake_currency,
|
|
|
|
fiat_display_currency
|
|
|
|
) if self._fiat_converter else 0,
|
2020-08-18 18:12:14 +00:00
|
|
|
'trade_count': value["trades"],
|
2020-05-17 18:12:01 +00:00
|
|
|
}
|
2022-06-08 05:08:01 +00:00
|
|
|
for key, value in profit_units.items()
|
2021-11-04 19:47:01 +00:00
|
|
|
]
|
|
|
|
return {
|
|
|
|
'stake_currency': stake_currency,
|
|
|
|
'fiat_display_currency': fiat_display_currency,
|
|
|
|
'data': data
|
|
|
|
}
|
|
|
|
|
2021-04-18 14:05:28 +00:00
|
|
|
def _rpc_trade_history(self, limit: int, offset: int = 0, order_by_id: bool = False) -> Dict:
|
2020-04-05 14:14:02 +00:00
|
|
|
""" Returns the X last trades """
|
2021-04-18 14:05:28 +00:00
|
|
|
order_by = Trade.id if order_by_id else Trade.close_date.desc()
|
|
|
|
if limit:
|
2020-07-23 05:50:45 +00:00
|
|
|
trades = Trade.get_trades([Trade.is_open.is_(False)]).order_by(
|
2021-04-18 14:05:28 +00:00
|
|
|
order_by).limit(limit).offset(offset)
|
2020-04-05 14:14:02 +00:00
|
|
|
else:
|
2021-03-08 21:21:56 +00:00
|
|
|
trades = Trade.get_trades([Trade.is_open.is_(False)]).order_by(
|
|
|
|
Trade.close_date.desc()).all()
|
2020-04-05 14:14:02 +00:00
|
|
|
|
2020-04-08 05:56:21 +00:00
|
|
|
output = [trade.to_json() for trade in trades]
|
2020-04-05 14:14:02 +00:00
|
|
|
|
|
|
|
return {
|
2020-04-06 09:00:31 +00:00
|
|
|
"trades": output,
|
2021-04-18 14:05:28 +00:00
|
|
|
"trades_count": len(output),
|
2022-06-18 15:44:15 +00:00
|
|
|
"offset": offset,
|
2021-04-18 14:05:28 +00:00
|
|
|
"total_trades": Trade.get_trades([Trade.is_open.is_(False)]).count(),
|
2020-04-05 14:14:02 +00:00
|
|
|
}
|
|
|
|
|
2020-12-07 13:54:39 +00:00
|
|
|
def _rpc_stats(self) -> Dict[str, Any]:
|
2020-12-05 13:38:42 +00:00
|
|
|
"""
|
|
|
|
Generate generic stats for trades in database
|
|
|
|
"""
|
|
|
|
def trade_win_loss(trade):
|
2020-12-05 13:48:56 +00:00
|
|
|
if trade.close_profit > 0:
|
2020-12-07 13:54:39 +00:00
|
|
|
return 'wins'
|
2020-12-05 13:48:56 +00:00
|
|
|
elif trade.close_profit < 0:
|
2020-12-07 13:54:39 +00:00
|
|
|
return 'losses'
|
2020-12-05 13:38:42 +00:00
|
|
|
else:
|
2020-12-07 13:54:39 +00:00
|
|
|
return 'draws'
|
2022-06-19 14:13:00 +00:00
|
|
|
trades: List[Trade] = Trade.get_trades([Trade.is_open.is_(False)], include_orders=False)
|
2020-12-05 13:38:42 +00:00
|
|
|
# Sell reason
|
2022-03-24 19:33:47 +00:00
|
|
|
exit_reasons = {}
|
2020-12-05 13:38:42 +00:00
|
|
|
for trade in trades:
|
2022-03-24 19:33:47 +00:00
|
|
|
if trade.exit_reason not in exit_reasons:
|
|
|
|
exit_reasons[trade.exit_reason] = {'wins': 0, 'losses': 0, 'draws': 0}
|
|
|
|
exit_reasons[trade.exit_reason][trade_win_loss(trade)] += 1
|
2020-12-05 13:38:42 +00:00
|
|
|
|
|
|
|
# Duration
|
2020-12-07 13:54:39 +00:00
|
|
|
dur: Dict[str, List[int]] = {'wins': [], 'draws': [], 'losses': []}
|
2020-12-05 13:38:42 +00:00
|
|
|
for trade in trades:
|
|
|
|
if trade.close_date is not None and trade.open_date is not None:
|
|
|
|
trade_dur = (trade.close_date - trade.open_date).total_seconds()
|
|
|
|
dur[trade_win_loss(trade)].append(trade_dur)
|
|
|
|
|
2022-02-10 06:03:19 +00:00
|
|
|
wins_dur = sum(dur['wins']) / len(dur['wins']) if len(dur['wins']) > 0 else None
|
|
|
|
draws_dur = sum(dur['draws']) / len(dur['draws']) if len(dur['draws']) > 0 else None
|
|
|
|
losses_dur = sum(dur['losses']) / len(dur['losses']) if len(dur['losses']) > 0 else None
|
2020-12-05 13:38:42 +00:00
|
|
|
|
|
|
|
durations = {'wins': wins_dur, 'draws': draws_dur, 'losses': losses_dur}
|
2022-03-24 19:33:47 +00:00
|
|
|
return {'exit_reasons': exit_reasons, 'durations': durations}
|
2020-12-05 13:06:46 +00:00
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
def _rpc_trade_statistics(
|
2021-05-19 21:33:33 +00:00
|
|
|
self, stake_currency: str, fiat_display_currency: str,
|
|
|
|
start_date: datetime = datetime.fromtimestamp(0)) -> Dict[str, Any]:
|
2018-06-08 02:52:50 +00:00
|
|
|
""" Returns cumulative profit statistics """
|
2021-06-22 09:22:19 +00:00
|
|
|
trade_filter = ((Trade.is_open.is_(False) & (Trade.close_date >= start_date)) |
|
|
|
|
Trade.is_open.is_(True))
|
2022-06-19 14:13:00 +00:00
|
|
|
trades: List[Trade] = Trade.get_trades(
|
|
|
|
trade_filter, include_orders=False).order_by(Trade.id).all()
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
profit_all_coin = []
|
2020-02-28 09:36:39 +00:00
|
|
|
profit_all_ratio = []
|
2018-02-13 03:45:59 +00:00
|
|
|
profit_closed_coin = []
|
2020-02-28 09:36:39 +00:00
|
|
|
profit_closed_ratio = []
|
2018-02-13 03:45:59 +00:00
|
|
|
durations = []
|
2020-06-24 04:43:19 +00:00
|
|
|
winning_trades = 0
|
|
|
|
losing_trades = 0
|
2022-06-18 09:14:28 +00:00
|
|
|
winning_profit = 0.0
|
|
|
|
losing_profit = 0.0
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
for trade in trades:
|
2018-06-02 11:43:51 +00:00
|
|
|
current_rate: float = 0.0
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
if trade.close_date:
|
|
|
|
durations.append((trade.close_date - trade.open_date).total_seconds())
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
if not trade.is_open:
|
2020-03-22 10:28:18 +00:00
|
|
|
profit_ratio = trade.close_profit
|
2022-08-05 05:26:41 +00:00
|
|
|
profit_abs = trade.close_profit_abs
|
|
|
|
profit_closed_coin.append(profit_abs)
|
2020-02-28 09:36:39 +00:00
|
|
|
profit_closed_ratio.append(profit_ratio)
|
2020-06-25 17:22:50 +00:00
|
|
|
if trade.close_profit >= 0:
|
2020-06-24 04:43:19 +00:00
|
|
|
winning_trades += 1
|
2022-08-05 05:26:41 +00:00
|
|
|
winning_profit += profit_abs
|
2020-06-24 04:43:19 +00:00
|
|
|
else:
|
|
|
|
losing_trades += 1
|
2022-08-05 05:26:41 +00:00
|
|
|
losing_profit += profit_abs
|
2018-02-13 03:45:59 +00:00
|
|
|
else:
|
|
|
|
# Get current rate
|
2018-10-10 19:28:48 +00:00
|
|
|
try:
|
2021-07-18 03:58:54 +00:00
|
|
|
current_rate = self._freqtrade.exchange.get_rate(
|
2022-03-28 05:03:10 +00:00
|
|
|
trade.pair, side='exit', is_short=trade.is_short, refresh=False)
|
2020-06-28 14:01:40 +00:00
|
|
|
except (PricingError, ExchangeError):
|
2018-10-10 19:28:48 +00:00
|
|
|
current_rate = NAN
|
2022-08-11 15:02:52 +00:00
|
|
|
if isnan(current_rate):
|
|
|
|
profit_ratio = NAN
|
|
|
|
profit_abs = NAN
|
|
|
|
else:
|
|
|
|
profit_ratio = trade.calc_profit_ratio(rate=current_rate)
|
|
|
|
profit_abs = trade.calc_profit(
|
|
|
|
rate=trade.close_rate or current_rate) + trade.realized_profit
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2022-08-05 05:26:41 +00:00
|
|
|
profit_all_coin.append(profit_abs)
|
2020-02-28 09:36:39 +00:00
|
|
|
profit_all_ratio.append(profit_ratio)
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2021-06-28 20:42:09 +00:00
|
|
|
best_pair = Trade.get_best_pair(start_date)
|
2022-06-18 09:40:32 +00:00
|
|
|
trading_volume = Trade.get_trading_volume(start_date)
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
# Prepare data to display
|
2018-07-14 05:02:39 +00:00
|
|
|
profit_closed_coin_sum = round(sum(profit_closed_coin), 8)
|
2021-01-31 10:21:23 +00:00
|
|
|
profit_closed_ratio_mean = float(mean(profit_closed_ratio) if profit_closed_ratio else 0.0)
|
2020-06-03 17:40:30 +00:00
|
|
|
profit_closed_ratio_sum = sum(profit_closed_ratio) if profit_closed_ratio else 0.0
|
|
|
|
|
2018-07-21 18:44:38 +00:00
|
|
|
profit_closed_fiat = self._fiat_converter.convert_amount(
|
2018-07-14 05:02:39 +00:00
|
|
|
profit_closed_coin_sum,
|
2018-02-13 03:45:59 +00:00
|
|
|
stake_currency,
|
|
|
|
fiat_display_currency
|
2018-07-21 18:44:38 +00:00
|
|
|
) if self._fiat_converter else 0
|
|
|
|
|
2018-07-14 05:02:39 +00:00
|
|
|
profit_all_coin_sum = round(sum(profit_all_coin), 8)
|
2021-01-31 10:21:23 +00:00
|
|
|
profit_all_ratio_mean = float(mean(profit_all_ratio) if profit_all_ratio else 0.0)
|
2021-07-14 18:55:11 +00:00
|
|
|
# Doing the sum is not right - overall profit needs to be based on initial capital
|
2020-06-03 17:40:30 +00:00
|
|
|
profit_all_ratio_sum = sum(profit_all_ratio) if profit_all_ratio else 0.0
|
2021-07-14 18:55:11 +00:00
|
|
|
starting_balance = self._freqtrade.wallets.get_starting_balance()
|
2021-09-06 17:53:32 +00:00
|
|
|
profit_closed_ratio_fromstart = 0
|
|
|
|
profit_all_ratio_fromstart = 0
|
|
|
|
if starting_balance:
|
|
|
|
profit_closed_ratio_fromstart = profit_closed_coin_sum / starting_balance
|
|
|
|
profit_all_ratio_fromstart = profit_all_coin_sum / starting_balance
|
2021-07-14 18:55:11 +00:00
|
|
|
|
2022-06-18 09:14:28 +00:00
|
|
|
profit_factor = winning_profit / abs(losing_profit) if losing_profit else float('inf')
|
|
|
|
|
|
|
|
trades_df = DataFrame([{'close_date': trade.close_date.strftime(DATETIME_PRINT_FORMAT),
|
|
|
|
'profit_abs': trade.close_profit_abs}
|
2023-02-16 08:40:34 +00:00
|
|
|
for trade in trades if not trade.is_open and trade.close_date])
|
2022-06-18 09:14:28 +00:00
|
|
|
max_drawdown_abs = 0.0
|
|
|
|
max_drawdown = 0.0
|
|
|
|
if len(trades_df) > 0:
|
|
|
|
try:
|
|
|
|
(max_drawdown_abs, _, _, _, _, max_drawdown) = calculate_max_drawdown(
|
|
|
|
trades_df, value_col='profit_abs', starting_balance=starting_balance)
|
|
|
|
except ValueError:
|
|
|
|
# ValueError if no losing trade.
|
|
|
|
pass
|
|
|
|
|
2018-07-21 18:44:38 +00:00
|
|
|
profit_all_fiat = self._fiat_converter.convert_amount(
|
2018-07-14 05:02:39 +00:00
|
|
|
profit_all_coin_sum,
|
2018-02-13 03:45:59 +00:00
|
|
|
stake_currency,
|
|
|
|
fiat_display_currency
|
2018-07-21 18:44:38 +00:00
|
|
|
) if self._fiat_converter else 0
|
|
|
|
|
2020-05-29 07:03:48 +00:00
|
|
|
first_date = trades[0].open_date if trades else None
|
|
|
|
last_date = trades[-1].open_date if trades else None
|
2018-02-13 03:45:59 +00:00
|
|
|
num = float(len(durations) or 1)
|
2018-06-08 02:52:50 +00:00
|
|
|
return {
|
2018-07-14 05:02:39 +00:00
|
|
|
'profit_closed_coin': profit_closed_coin_sum,
|
2020-06-03 17:40:30 +00:00
|
|
|
'profit_closed_percent_mean': round(profit_closed_ratio_mean * 100, 2),
|
|
|
|
'profit_closed_ratio_mean': profit_closed_ratio_mean,
|
2021-07-15 05:11:44 +00:00
|
|
|
'profit_closed_percent_sum': round(profit_closed_ratio_sum * 100, 2),
|
|
|
|
'profit_closed_ratio_sum': profit_closed_ratio_sum,
|
2021-07-14 18:55:11 +00:00
|
|
|
'profit_closed_ratio': profit_closed_ratio_fromstart,
|
|
|
|
'profit_closed_percent': round(profit_closed_ratio_fromstart * 100, 2),
|
2018-06-08 02:52:50 +00:00
|
|
|
'profit_closed_fiat': profit_closed_fiat,
|
2018-07-14 05:02:39 +00:00
|
|
|
'profit_all_coin': profit_all_coin_sum,
|
2020-06-03 17:40:30 +00:00
|
|
|
'profit_all_percent_mean': round(profit_all_ratio_mean * 100, 2),
|
|
|
|
'profit_all_ratio_mean': profit_all_ratio_mean,
|
2021-07-15 05:11:44 +00:00
|
|
|
'profit_all_percent_sum': round(profit_all_ratio_sum * 100, 2),
|
|
|
|
'profit_all_ratio_sum': profit_all_ratio_sum,
|
2021-07-14 18:55:11 +00:00
|
|
|
'profit_all_ratio': profit_all_ratio_fromstart,
|
|
|
|
'profit_all_percent': round(profit_all_ratio_fromstart * 100, 2),
|
2018-06-08 02:52:50 +00:00
|
|
|
'profit_all_fiat': profit_all_fiat,
|
|
|
|
'trade_count': len(trades),
|
2020-05-29 07:38:12 +00:00
|
|
|
'closed_trade_count': len([t for t in trades if not t.is_open]),
|
2020-05-29 07:03:48 +00:00
|
|
|
'first_trade_date': arrow.get(first_date).humanize() if first_date else '',
|
|
|
|
'first_trade_timestamp': int(first_date.timestamp() * 1000) if first_date else 0,
|
|
|
|
'latest_trade_date': arrow.get(last_date).humanize() if last_date else '',
|
|
|
|
'latest_trade_timestamp': int(last_date.timestamp() * 1000) if last_date else 0,
|
2018-06-08 02:52:50 +00:00
|
|
|
'avg_duration': str(timedelta(seconds=sum(durations) / num)).split('.')[0],
|
2020-05-29 07:03:48 +00:00
|
|
|
'best_pair': best_pair[0] if best_pair else '',
|
2021-11-11 11:58:38 +00:00
|
|
|
'best_rate': round(best_pair[1] * 100, 2) if best_pair else 0, # Deprecated
|
|
|
|
'best_pair_profit_ratio': best_pair[1] if best_pair else 0,
|
2020-06-24 04:43:19 +00:00
|
|
|
'winning_trades': winning_trades,
|
|
|
|
'losing_trades': losing_trades,
|
2022-06-18 09:14:28 +00:00
|
|
|
'profit_factor': profit_factor,
|
|
|
|
'max_drawdown': max_drawdown,
|
|
|
|
'max_drawdown_abs': max_drawdown_abs,
|
2022-06-18 09:40:32 +00:00
|
|
|
'trading_volume': trading_volume,
|
2018-06-08 02:52:50 +00:00
|
|
|
}
|
|
|
|
|
2019-11-15 05:33:07 +00:00
|
|
|
def _rpc_balance(self, stake_currency: str, fiat_display_currency: str) -> Dict:
|
2018-06-08 02:52:50 +00:00
|
|
|
""" Returns current account balance per crypto """
|
2022-06-15 18:03:36 +00:00
|
|
|
currencies: List[Dict] = []
|
2018-02-13 03:45:59 +00:00
|
|
|
total = 0.0
|
2019-11-14 19:12:41 +00:00
|
|
|
try:
|
2021-04-13 18:09:22 +00:00
|
|
|
tickers = self._freqtrade.exchange.get_tickers(cached=True)
|
2020-06-28 14:01:40 +00:00
|
|
|
except (ExchangeError):
|
2019-11-14 19:12:41 +00:00
|
|
|
raise RPCException('Error getting current tickers.')
|
|
|
|
|
2020-01-15 05:43:41 +00:00
|
|
|
self._freqtrade.wallets.update(require_update=False)
|
2021-09-19 11:16:30 +00:00
|
|
|
starting_capital = self._freqtrade.wallets.get_starting_balance()
|
2021-09-19 11:29:09 +00:00
|
|
|
starting_cap_fiat = self._fiat_converter.convert_amount(
|
2021-09-19 11:16:30 +00:00
|
|
|
starting_capital, stake_currency, fiat_display_currency) if self._fiat_converter else 0
|
2022-02-19 09:58:17 +00:00
|
|
|
coin: str
|
|
|
|
balance: Wallet
|
2019-11-24 18:41:51 +00:00
|
|
|
for coin, balance in self._freqtrade.wallets.get_all_balances().items():
|
|
|
|
if not balance.total:
|
2018-05-14 21:31:56 +00:00
|
|
|
continue
|
|
|
|
|
2019-11-15 05:33:07 +00:00
|
|
|
est_stake: float = 0
|
|
|
|
if coin == stake_currency:
|
2018-05-14 21:31:56 +00:00
|
|
|
rate = 1.0
|
2019-11-24 18:41:51 +00:00
|
|
|
est_stake = balance.total
|
2022-03-10 05:47:17 +00:00
|
|
|
if self._config.get('trading_mode', TradingMode.SPOT) != TradingMode.SPOT:
|
|
|
|
# in Futures, "total" includes the locked stake, and therefore all positions
|
|
|
|
est_stake = balance.free
|
2018-02-13 03:45:59 +00:00
|
|
|
else:
|
2018-08-08 19:55:48 +00:00
|
|
|
try:
|
2019-11-15 05:33:07 +00:00
|
|
|
pair = self._freqtrade.exchange.get_valid_pair_combination(coin, stake_currency)
|
2022-05-17 22:11:10 +00:00
|
|
|
rate = tickers.get(pair, {}).get('last')
|
2019-11-15 05:33:07 +00:00
|
|
|
if rate:
|
2021-02-04 18:58:44 +00:00
|
|
|
if pair.startswith(stake_currency) and not pair.endswith(stake_currency):
|
2019-11-15 05:33:07 +00:00
|
|
|
rate = 1.0 / rate
|
2019-11-24 18:41:51 +00:00
|
|
|
est_stake = rate * balance.total
|
2020-06-28 14:01:40 +00:00
|
|
|
except (ExchangeError):
|
2019-05-11 13:27:09 +00:00
|
|
|
logger.warning(f" Could not get rate for pair {coin}.")
|
2018-08-08 19:55:48 +00:00
|
|
|
continue
|
2022-06-15 18:03:36 +00:00
|
|
|
total = total + est_stake
|
2022-02-19 09:58:17 +00:00
|
|
|
currencies.append({
|
2018-06-22 02:08:51 +00:00
|
|
|
'currency': coin,
|
2022-06-15 18:03:36 +00:00
|
|
|
'free': balance.free,
|
|
|
|
'balance': balance.total,
|
|
|
|
'used': balance.used,
|
2019-11-15 05:33:07 +00:00
|
|
|
'est_stake': est_stake or 0,
|
|
|
|
'stake': stake_currency,
|
2022-02-19 15:28:51 +00:00
|
|
|
'side': 'long',
|
|
|
|
'leverage': 1,
|
|
|
|
'position': 0,
|
|
|
|
'is_position': False,
|
2018-06-22 02:08:51 +00:00
|
|
|
})
|
2022-02-19 09:58:17 +00:00
|
|
|
symbol: str
|
|
|
|
position: PositionWallet
|
|
|
|
for symbol, position in self._freqtrade.wallets.get_all_positions().items():
|
2022-03-10 05:47:17 +00:00
|
|
|
total += position.collateral
|
2022-02-19 09:58:17 +00:00
|
|
|
|
|
|
|
currencies.append({
|
|
|
|
'currency': symbol,
|
|
|
|
'free': 0,
|
2022-02-19 15:28:51 +00:00
|
|
|
'balance': 0,
|
2022-02-19 09:58:17 +00:00
|
|
|
'used': 0,
|
|
|
|
'position': position.position,
|
|
|
|
'est_stake': position.collateral,
|
|
|
|
'stake': stake_currency,
|
2022-02-19 15:28:51 +00:00
|
|
|
'leverage': position.leverage,
|
|
|
|
'side': position.side,
|
|
|
|
'is_position': True
|
2022-02-19 09:58:17 +00:00
|
|
|
})
|
2018-05-14 21:31:56 +00:00
|
|
|
|
2021-09-19 11:16:30 +00:00
|
|
|
value = self._fiat_converter.convert_amount(
|
|
|
|
total, stake_currency, fiat_display_currency) if self._fiat_converter else 0
|
|
|
|
|
2022-01-16 12:39:50 +00:00
|
|
|
trade_count = len(Trade.get_trades_proxy())
|
2021-09-19 11:29:09 +00:00
|
|
|
starting_capital_ratio = (total / starting_capital) - 1 if starting_capital else 0.0
|
|
|
|
starting_cap_fiat_ratio = (value / starting_cap_fiat) - 1 if starting_cap_fiat else 0.0
|
2021-09-19 11:16:30 +00:00
|
|
|
|
2018-06-22 02:08:51 +00:00
|
|
|
return {
|
2022-02-19 09:58:17 +00:00
|
|
|
'currencies': currencies,
|
2018-06-22 02:08:51 +00:00
|
|
|
'total': total,
|
2021-09-19 11:16:30 +00:00
|
|
|
'symbol': fiat_display_currency,
|
2018-06-22 02:08:51 +00:00
|
|
|
'value': value,
|
2019-12-24 05:58:30 +00:00
|
|
|
'stake': stake_currency,
|
2021-09-19 11:16:30 +00:00
|
|
|
'starting_capital': starting_capital,
|
|
|
|
'starting_capital_ratio': starting_capital_ratio,
|
|
|
|
'starting_capital_pct': round(starting_capital_ratio * 100, 2),
|
2021-09-19 11:29:09 +00:00
|
|
|
'starting_capital_fiat': starting_cap_fiat,
|
|
|
|
'starting_capital_fiat_ratio': starting_cap_fiat_ratio,
|
|
|
|
'starting_capital_fiat_pct': round(starting_cap_fiat_ratio * 100, 2),
|
2022-01-16 12:39:50 +00:00
|
|
|
'trade_count': trade_count,
|
2020-01-20 19:24:40 +00:00
|
|
|
'note': 'Simulated balances' if self._freqtrade.config['dry_run'] else ''
|
2018-06-22 02:08:51 +00:00
|
|
|
}
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2018-06-22 01:32:45 +00:00
|
|
|
def _rpc_start(self) -> Dict[str, str]:
|
2018-06-08 02:52:50 +00:00
|
|
|
""" Handler for start """
|
2018-06-08 22:20:10 +00:00
|
|
|
if self._freqtrade.state == State.RUNNING:
|
2018-06-22 01:32:45 +00:00
|
|
|
return {'status': 'already running'}
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-06-08 22:20:10 +00:00
|
|
|
self._freqtrade.state = State.RUNNING
|
2018-06-22 01:32:45 +00:00
|
|
|
return {'status': 'starting trader ...'}
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2018-06-22 01:32:45 +00:00
|
|
|
def _rpc_stop(self) -> Dict[str, str]:
|
2018-06-08 02:52:50 +00:00
|
|
|
""" Handler for stop """
|
2018-06-08 22:20:10 +00:00
|
|
|
if self._freqtrade.state == State.RUNNING:
|
|
|
|
self._freqtrade.state = State.STOPPED
|
2018-06-22 01:32:45 +00:00
|
|
|
return {'status': 'stopping trader ...'}
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-06-22 01:32:45 +00:00
|
|
|
return {'status': 'already stopped'}
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2020-06-09 21:03:55 +00:00
|
|
|
def _rpc_reload_config(self) -> Dict[str, str]:
|
|
|
|
""" Handler for reload_config. """
|
|
|
|
self._freqtrade.state = State.RELOAD_CONFIG
|
2020-09-05 14:44:23 +00:00
|
|
|
return {'status': 'Reloading config ...'}
|
2018-06-09 02:29:48 +00:00
|
|
|
|
2022-08-28 09:32:53 +00:00
|
|
|
def _rpc_stopentry(self) -> Dict[str, str]:
|
2019-03-17 18:35:25 +00:00
|
|
|
"""
|
|
|
|
Handler to stop buying, but handle open trades gracefully.
|
|
|
|
"""
|
|
|
|
if self._freqtrade.state == State.RUNNING:
|
|
|
|
# Set 'max_open_trades' to 0
|
|
|
|
self._freqtrade.config['max_open_trades'] = 0
|
2023-01-15 10:44:10 +00:00
|
|
|
self._freqtrade.strategy.max_open_trades = 0
|
2019-03-17 18:35:25 +00:00
|
|
|
|
2022-08-28 09:32:53 +00:00
|
|
|
return {'status': 'No more entries will occur from now. Run /reload_config to reset.'}
|
2019-03-17 18:35:25 +00:00
|
|
|
|
2022-08-02 17:54:37 +00:00
|
|
|
def __exec_force_exit(self, trade: Trade, ordertype: Optional[str],
|
2022-08-10 04:44:41 +00:00
|
|
|
amount: Optional[float] = None) -> None:
|
2022-08-02 17:54:37 +00:00
|
|
|
# Check if there is there is an open order
|
|
|
|
fully_canceled = False
|
|
|
|
if trade.open_order_id:
|
|
|
|
order = self._freqtrade.exchange.fetch_order(trade.open_order_id, trade.pair)
|
|
|
|
|
|
|
|
if order['side'] == trade.entry_side:
|
|
|
|
fully_canceled = self._freqtrade.handle_cancel_enter(
|
|
|
|
trade, order, CANCEL_REASON['FORCE_EXIT'])
|
|
|
|
|
|
|
|
if order['side'] == trade.exit_side:
|
|
|
|
# Cancel order - so it is placed anew with a fresh price.
|
|
|
|
self._freqtrade.handle_cancel_exit(trade, order, CANCEL_REASON['FORCE_EXIT'])
|
|
|
|
|
|
|
|
if not fully_canceled:
|
|
|
|
# Get current rate and execute sell
|
|
|
|
current_rate = self._freqtrade.exchange.get_rate(
|
|
|
|
trade.pair, side='exit', is_short=trade.is_short, refresh=True)
|
|
|
|
exit_check = ExitCheckTuple(exit_type=ExitType.FORCE_EXIT)
|
|
|
|
order_type = ordertype or self._freqtrade.strategy.order_types.get(
|
|
|
|
"force_exit", self._freqtrade.strategy.order_types["exit"])
|
2022-08-04 14:28:36 +00:00
|
|
|
sub_amount: Optional[float] = None
|
2022-08-10 04:44:41 +00:00
|
|
|
if amount and amount < trade.amount:
|
2022-08-02 17:54:37 +00:00
|
|
|
# Partial exit ...
|
|
|
|
min_exit_stake = self._freqtrade.exchange.get_min_pair_stake_amount(
|
|
|
|
trade.pair, current_rate, trade.stop_loss_pct)
|
2022-08-10 04:44:41 +00:00
|
|
|
remaining = (trade.amount - amount) * current_rate
|
2022-08-02 17:54:37 +00:00
|
|
|
if remaining < min_exit_stake:
|
|
|
|
raise RPCException(f'Remaining amount of {remaining} would be too small.')
|
2022-08-10 04:44:41 +00:00
|
|
|
sub_amount = amount
|
2022-08-02 17:54:37 +00:00
|
|
|
|
|
|
|
self._freqtrade.execute_trade_exit(
|
|
|
|
trade, current_rate, exit_check, ordertype=order_type,
|
|
|
|
sub_trade_amt=sub_amount)
|
|
|
|
|
2022-08-02 17:53:10 +00:00
|
|
|
def _rpc_force_exit(self, trade_id: str, ordertype: Optional[str] = None, *,
|
2022-08-02 18:16:01 +00:00
|
|
|
amount: Optional[float] = None) -> Dict[str, str]:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
2022-04-10 13:56:29 +00:00
|
|
|
Handler for forceexit <id>.
|
2018-02-13 03:45:59 +00:00
|
|
|
Sells the given trade at current price
|
|
|
|
"""
|
2022-08-02 17:53:10 +00:00
|
|
|
|
2018-06-08 22:20:10 +00:00
|
|
|
if self._freqtrade.state != State.RUNNING:
|
2018-06-22 01:37:19 +00:00
|
|
|
raise RPCException('trader is not running')
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2021-09-08 06:49:04 +00:00
|
|
|
with self._freqtrade._exit_lock:
|
2020-01-22 19:50:09 +00:00
|
|
|
if trade_id == 'all':
|
|
|
|
# Execute sell for all open orders
|
|
|
|
for trade in Trade.get_open_trades():
|
2022-08-02 18:16:01 +00:00
|
|
|
self.__exec_force_exit(trade, ordertype)
|
2021-04-15 05:57:52 +00:00
|
|
|
Trade.commit()
|
2020-01-22 19:50:09 +00:00
|
|
|
self._freqtrade.wallets.update()
|
|
|
|
return {'result': 'Created sell orders for all open trades.'}
|
|
|
|
|
|
|
|
# Query for trade
|
|
|
|
trade = Trade.get_trades(
|
|
|
|
trade_filter=[Trade.id == trade_id, Trade.is_open.is_(True), ]
|
|
|
|
).first()
|
|
|
|
if not trade:
|
2022-04-05 10:31:53 +00:00
|
|
|
logger.warning('force_exit: Invalid argument received')
|
2020-01-22 19:50:09 +00:00
|
|
|
raise RPCException('invalid argument')
|
|
|
|
|
2022-08-02 17:54:37 +00:00
|
|
|
self.__exec_force_exit(trade, ordertype, amount)
|
2021-04-15 05:57:52 +00:00
|
|
|
Trade.commit()
|
2020-01-22 18:54:55 +00:00
|
|
|
self._freqtrade.wallets.update()
|
2020-01-22 19:50:09 +00:00
|
|
|
return {'result': f'Created sell order for trade {trade_id}.'}
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2022-11-29 17:27:08 +00:00
|
|
|
def _force_entry_validations(self, pair: str, order_side: SignalDirection):
|
2022-04-08 11:39:41 +00:00
|
|
|
if not self._freqtrade.config.get('force_entry_enable', False):
|
2022-04-05 10:31:53 +00:00
|
|
|
raise RPCException('Force_entry not enabled.')
|
2018-10-09 17:25:43 +00:00
|
|
|
|
|
|
|
if self._freqtrade.state != State.RUNNING:
|
|
|
|
raise RPCException('trader is not running')
|
|
|
|
|
2022-01-26 18:53:46 +00:00
|
|
|
if order_side == SignalDirection.SHORT and self._freqtrade.trading_mode == TradingMode.SPOT:
|
2022-01-27 05:40:41 +00:00
|
|
|
raise RPCException("Can't go short on Spot markets.")
|
2022-01-26 18:53:46 +00:00
|
|
|
|
2022-11-29 17:27:08 +00:00
|
|
|
if pair not in self._freqtrade.exchange.get_markets(tradable_only=True):
|
|
|
|
raise RPCException('Symbol does not exist or market is not active.')
|
2020-02-26 06:00:08 +00:00
|
|
|
# Check if pair quote currency equals to the stake currency.
|
2018-10-09 17:25:43 +00:00
|
|
|
stake_currency = self._freqtrade.config.get('stake_currency')
|
2020-02-25 06:16:37 +00:00
|
|
|
if not self._freqtrade.exchange.get_pair_quote_currency(pair) == stake_currency:
|
2018-10-09 17:25:43 +00:00
|
|
|
raise RPCException(
|
2020-11-21 09:39:49 +00:00
|
|
|
f'Wrong pair selected. Only pairs with stake-currency {stake_currency} allowed.')
|
2022-11-29 17:27:08 +00:00
|
|
|
|
|
|
|
def _rpc_force_entry(self, pair: str, price: Optional[float], *,
|
|
|
|
order_type: Optional[str] = None,
|
|
|
|
order_side: SignalDirection = SignalDirection.LONG,
|
|
|
|
stake_amount: Optional[float] = None,
|
|
|
|
enter_tag: Optional[str] = 'force_entry',
|
|
|
|
leverage: Optional[float] = None) -> Optional[Trade]:
|
|
|
|
"""
|
|
|
|
Handler for forcebuy <asset> <price>
|
|
|
|
Buys a pair trade at the given or current price
|
|
|
|
"""
|
|
|
|
self._force_entry_validations(pair, order_side)
|
|
|
|
|
2018-10-09 17:25:43 +00:00
|
|
|
# check if valid pair
|
|
|
|
|
|
|
|
# check if pair already has an open pair
|
2022-02-13 15:28:49 +00:00
|
|
|
trade: Trade = Trade.get_trades([Trade.is_open.is_(True), Trade.pair == pair]).first()
|
|
|
|
is_short = (order_side == SignalDirection.SHORT)
|
2018-10-09 17:25:43 +00:00
|
|
|
if trade:
|
2022-02-13 15:28:49 +00:00
|
|
|
is_short = trade.is_short
|
2021-12-24 10:38:43 +00:00
|
|
|
if not self._freqtrade.strategy.position_adjustment_enable:
|
2021-12-23 09:57:53 +00:00
|
|
|
raise RPCException(f'position for {pair} already open - id: {trade.id}')
|
2022-11-20 08:28:14 +00:00
|
|
|
if trade.open_order_id is not None:
|
|
|
|
raise RPCException(f'position for {pair} already open - id: {trade.id} '
|
|
|
|
f'and has open order {trade.open_order_id}')
|
2022-09-28 09:32:07 +00:00
|
|
|
else:
|
|
|
|
if Trade.get_open_trade_count() >= self._config['max_open_trades']:
|
|
|
|
raise RPCException("Maximum number of trades is reached.")
|
2018-10-09 17:25:43 +00:00
|
|
|
|
2022-01-22 12:26:02 +00:00
|
|
|
if not stake_amount:
|
|
|
|
# gen stake amount
|
|
|
|
stake_amount = self._freqtrade.wallets.get_trade_stake_amount(pair)
|
2018-10-09 17:25:43 +00:00
|
|
|
|
|
|
|
# execute buy
|
2021-11-24 19:11:04 +00:00
|
|
|
if not order_type:
|
|
|
|
order_type = self._freqtrade.strategy.order_types.get(
|
2022-04-05 10:31:53 +00:00
|
|
|
'force_entry', self._freqtrade.strategy.order_types['entry'])
|
2022-11-25 13:50:48 +00:00
|
|
|
with self._freqtrade._exit_lock:
|
|
|
|
if self._freqtrade.execute_entry(pair, stake_amount, price,
|
|
|
|
ordertype=order_type, trade=trade,
|
|
|
|
is_short=is_short,
|
|
|
|
enter_tag=enter_tag,
|
|
|
|
leverage_=leverage,
|
|
|
|
):
|
|
|
|
Trade.commit()
|
|
|
|
trade = Trade.get_trades([Trade.is_open.is_(True), Trade.pair == pair]).first()
|
|
|
|
return trade
|
|
|
|
else:
|
|
|
|
raise RPCException(f'Failed to enter position for {pair}.')
|
2020-08-04 12:41:22 +00:00
|
|
|
|
2023-01-31 06:09:03 +00:00
|
|
|
def _rpc_cancel_open_order(self, trade_id: int):
|
|
|
|
if self._freqtrade.state != State.RUNNING:
|
|
|
|
raise RPCException('trader is not running')
|
|
|
|
with self._freqtrade._exit_lock:
|
|
|
|
# Query for trade
|
|
|
|
trade = Trade.get_trades(
|
|
|
|
trade_filter=[Trade.id == trade_id, Trade.is_open.is_(True), ]
|
|
|
|
).first()
|
|
|
|
if not trade:
|
|
|
|
logger.warning('cancel_open_order: Invalid trade_id received.')
|
2023-01-31 18:38:43 +00:00
|
|
|
raise RPCException('Invalid trade_id.')
|
2023-01-31 06:09:03 +00:00
|
|
|
if not trade.open_order_id:
|
|
|
|
logger.warning('cancel_open_order: No open order for trade_id.')
|
2023-01-31 18:38:43 +00:00
|
|
|
raise RPCException('No open order for trade_id.')
|
2023-01-31 06:09:03 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
order = self._freqtrade.exchange.fetch_order(trade.open_order_id, trade.pair)
|
|
|
|
except ExchangeError as e:
|
|
|
|
logger.info(f"Cannot query order for {trade} due to {e}.", exc_info=True)
|
|
|
|
raise RPCException("Order not found.")
|
|
|
|
self._freqtrade.handle_cancel_order(order, trade, CANCEL_REASON['USER_CANCEL'])
|
|
|
|
Trade.commit()
|
|
|
|
|
2020-12-01 18:55:20 +00:00
|
|
|
def _rpc_delete(self, trade_id: int) -> Dict[str, Union[str, int]]:
|
2020-07-20 04:08:18 +00:00
|
|
|
"""
|
|
|
|
Handler for delete <id>.
|
2020-08-04 17:43:22 +00:00
|
|
|
Delete the given trade and close eventually existing open orders.
|
2020-07-20 04:08:18 +00:00
|
|
|
"""
|
2021-09-08 06:49:04 +00:00
|
|
|
with self._freqtrade._exit_lock:
|
2020-08-04 17:43:22 +00:00
|
|
|
c_count = 0
|
|
|
|
trade = Trade.get_trades(trade_filter=[Trade.id == trade_id]).first()
|
2020-07-20 04:08:18 +00:00
|
|
|
if not trade:
|
2020-08-04 17:43:22 +00:00
|
|
|
logger.warning('delete trade: Invalid argument received')
|
2020-07-20 04:08:18 +00:00
|
|
|
raise RPCException('invalid argument')
|
|
|
|
|
2020-08-04 17:43:22 +00:00
|
|
|
# Try cancelling regular order if that exists
|
|
|
|
if trade.open_order_id:
|
|
|
|
try:
|
|
|
|
self._freqtrade.exchange.cancel_order(trade.open_order_id, trade.pair)
|
|
|
|
c_count += 1
|
2020-08-12 12:25:50 +00:00
|
|
|
except (ExchangeError):
|
2020-08-04 17:43:22 +00:00
|
|
|
pass
|
|
|
|
|
|
|
|
# cancel stoploss on exchange ...
|
|
|
|
if (self._freqtrade.strategy.order_types.get('stoploss_on_exchange')
|
|
|
|
and trade.stoploss_order_id):
|
|
|
|
try:
|
|
|
|
self._freqtrade.exchange.cancel_stoploss_order(trade.stoploss_order_id,
|
|
|
|
trade.pair)
|
|
|
|
c_count += 1
|
2020-08-12 12:25:50 +00:00
|
|
|
except (ExchangeError):
|
2020-08-04 17:43:22 +00:00
|
|
|
pass
|
|
|
|
|
2020-09-06 12:27:36 +00:00
|
|
|
trade.delete()
|
2020-07-20 04:08:18 +00:00
|
|
|
self._freqtrade.wallets.update()
|
2020-08-04 17:43:22 +00:00
|
|
|
return {
|
|
|
|
'result': 'success',
|
|
|
|
'trade_id': trade_id,
|
|
|
|
'result_msg': f'Deleted trade {trade_id}. Closed {c_count} open orders.',
|
|
|
|
'cancel_order_count': c_count,
|
|
|
|
}
|
2018-10-09 17:25:43 +00:00
|
|
|
|
2019-10-30 08:59:54 +00:00
|
|
|
def _rpc_performance(self) -> List[Dict[str, Any]]:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for performance.
|
|
|
|
Shows a performance statistic from finished trades
|
|
|
|
"""
|
2019-10-30 08:59:54 +00:00
|
|
|
pair_rates = Trade.get_overall_performance()
|
2021-10-25 20:43:22 +00:00
|
|
|
|
2019-10-30 08:59:54 +00:00
|
|
|
return pair_rates
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2021-11-21 08:51:16 +00:00
|
|
|
def _rpc_enter_tag_performance(self, pair: Optional[str]) -> List[Dict[str, Any]]:
|
2021-10-12 21:02:28 +00:00
|
|
|
"""
|
|
|
|
Handler for buy tag performance.
|
|
|
|
Shows a performance statistic from finished trades
|
|
|
|
"""
|
2021-11-21 09:05:56 +00:00
|
|
|
return Trade.get_enter_tag_performance(pair)
|
2021-10-12 21:02:28 +00:00
|
|
|
|
2022-04-03 08:39:35 +00:00
|
|
|
def _rpc_exit_reason_performance(self, pair: Optional[str]) -> List[Dict[str, Any]]:
|
2021-10-12 21:02:28 +00:00
|
|
|
"""
|
2022-04-03 17:39:13 +00:00
|
|
|
Handler for exit reason performance.
|
2021-10-12 21:02:28 +00:00
|
|
|
Shows a performance statistic from finished trades
|
|
|
|
"""
|
2022-04-03 08:39:35 +00:00
|
|
|
return Trade.get_exit_reason_performance(pair)
|
2021-10-12 21:02:28 +00:00
|
|
|
|
2021-10-24 13:18:29 +00:00
|
|
|
def _rpc_mix_tag_performance(self, pair: Optional[str]) -> List[Dict[str, Any]]:
|
2021-10-12 21:02:28 +00:00
|
|
|
"""
|
2022-04-03 08:41:35 +00:00
|
|
|
Handler for mix tag (enter_tag + exit_reason) performance.
|
2021-10-12 21:02:28 +00:00
|
|
|
Shows a performance statistic from finished trades
|
|
|
|
"""
|
|
|
|
mix_tags = Trade.get_mix_tag_performance(pair)
|
2021-10-25 20:43:22 +00:00
|
|
|
|
2021-10-12 21:02:28 +00:00
|
|
|
return mix_tags
|
|
|
|
|
2019-04-06 18:01:29 +00:00
|
|
|
def _rpc_count(self) -> Dict[str, float]:
|
2018-06-08 02:52:50 +00:00
|
|
|
""" Returns the number of trades running """
|
2018-06-08 22:20:10 +00:00
|
|
|
if self._freqtrade.state != State.RUNNING:
|
2018-06-22 01:37:19 +00:00
|
|
|
raise RPCException('trader is not running')
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2019-04-06 17:58:45 +00:00
|
|
|
trades = Trade.get_open_trades()
|
|
|
|
return {
|
|
|
|
'current': len(trades),
|
2021-01-12 18:24:37 +00:00
|
|
|
'max': (int(self._freqtrade.config['max_open_trades'])
|
|
|
|
if self._freqtrade.config['max_open_trades'] != float('inf') else -1),
|
2019-04-06 18:01:29 +00:00
|
|
|
'total_stake': sum((trade.open_rate * trade.amount) for trade in trades)
|
2019-04-06 17:58:45 +00:00
|
|
|
}
|
2018-11-10 19:07:09 +00:00
|
|
|
|
2020-10-17 13:15:35 +00:00
|
|
|
def _rpc_locks(self) -> Dict[str, Any]:
|
2021-03-01 06:51:33 +00:00
|
|
|
""" Returns the current locks """
|
2020-10-17 13:15:35 +00:00
|
|
|
|
2020-10-25 09:54:30 +00:00
|
|
|
locks = PairLocks.get_pair_locks(None)
|
2020-10-17 13:15:35 +00:00
|
|
|
return {
|
|
|
|
'lock_count': len(locks),
|
|
|
|
'locks': [lock.to_json() for lock in locks]
|
|
|
|
}
|
|
|
|
|
2021-03-01 06:51:33 +00:00
|
|
|
def _rpc_delete_lock(self, lockid: Optional[int] = None,
|
|
|
|
pair: Optional[str] = None) -> Dict[str, Any]:
|
|
|
|
""" Delete specific lock(s) """
|
|
|
|
locks = []
|
|
|
|
|
|
|
|
if pair:
|
|
|
|
locks = PairLocks.get_pair_locks(pair)
|
|
|
|
if lockid:
|
|
|
|
locks = PairLock.query.filter(PairLock.id == lockid).all()
|
|
|
|
|
|
|
|
for lock in locks:
|
|
|
|
lock.active = False
|
|
|
|
lock.lock_end_time = datetime.now(timezone.utc)
|
|
|
|
|
2022-08-06 13:08:13 +00:00
|
|
|
Trade.commit()
|
2021-03-01 06:51:33 +00:00
|
|
|
|
|
|
|
return self._rpc_locks()
|
|
|
|
|
2018-11-10 19:07:09 +00:00
|
|
|
def _rpc_whitelist(self) -> Dict:
|
|
|
|
""" Returns the currently active whitelist"""
|
2019-11-09 13:00:32 +00:00
|
|
|
res = {'method': self._freqtrade.pairlists.name_list,
|
2019-03-24 15:08:48 +00:00
|
|
|
'length': len(self._freqtrade.active_pair_whitelist),
|
2018-11-10 19:07:09 +00:00
|
|
|
'whitelist': self._freqtrade.active_pair_whitelist
|
|
|
|
}
|
|
|
|
return res
|
2019-03-24 15:08:48 +00:00
|
|
|
|
2021-12-11 14:53:44 +00:00
|
|
|
def _rpc_blacklist_delete(self, delete: List[str]) -> Dict:
|
|
|
|
""" Removes pairs from currently active blacklist """
|
|
|
|
errors = {}
|
|
|
|
for pair in delete:
|
|
|
|
if pair in self._freqtrade.pairlists.blacklist:
|
|
|
|
self._freqtrade.pairlists.blacklist.remove(pair)
|
|
|
|
else:
|
|
|
|
errors[pair] = {
|
|
|
|
'error_msg': f"Pair {pair} is not in the current blacklist."
|
2022-06-15 18:03:36 +00:00
|
|
|
}
|
2021-12-11 14:53:44 +00:00
|
|
|
resp = self._rpc_blacklist()
|
|
|
|
resp['errors'] = errors
|
|
|
|
return resp
|
|
|
|
|
2023-01-21 14:01:56 +00:00
|
|
|
def _rpc_blacklist(self, add: Optional[List[str]] = None) -> Dict:
|
2019-03-24 15:08:48 +00:00
|
|
|
""" Returns the currently active blacklist"""
|
2020-05-28 04:51:53 +00:00
|
|
|
errors = {}
|
2019-03-24 15:28:14 +00:00
|
|
|
if add:
|
2019-03-25 18:40:21 +00:00
|
|
|
for pair in add:
|
2020-12-30 08:57:31 +00:00
|
|
|
if pair not in self._freqtrade.pairlists.blacklist:
|
|
|
|
try:
|
|
|
|
expand_pairlist([pair], self._freqtrade.exchange.get_markets().keys())
|
2020-05-28 04:51:53 +00:00
|
|
|
self._freqtrade.pairlists.blacklist.append(pair)
|
|
|
|
|
2020-12-30 08:57:31 +00:00
|
|
|
except ValueError:
|
|
|
|
errors[pair] = {
|
|
|
|
'error_msg': f'Pair {pair} is not a valid wildcard.'}
|
2020-05-28 04:51:53 +00:00
|
|
|
else:
|
|
|
|
errors[pair] = {
|
2020-12-30 08:57:31 +00:00
|
|
|
'error_msg': f'Pair {pair} already in pairlist.'}
|
2019-03-24 15:28:14 +00:00
|
|
|
|
2019-11-09 13:00:32 +00:00
|
|
|
res = {'method': self._freqtrade.pairlists.name_list,
|
2019-03-24 15:08:48 +00:00
|
|
|
'length': len(self._freqtrade.pairlists.blacklist),
|
2019-03-25 18:40:21 +00:00
|
|
|
'blacklist': self._freqtrade.pairlists.blacklist,
|
2020-12-30 08:57:31 +00:00
|
|
|
'blacklist_expanded': self._freqtrade.pairlists.expanded_blacklist,
|
2020-05-28 04:51:53 +00:00
|
|
|
'errors': errors,
|
2019-03-24 15:08:48 +00:00
|
|
|
}
|
|
|
|
return res
|
2019-03-25 09:16:09 +00:00
|
|
|
|
2020-12-06 18:57:48 +00:00
|
|
|
@staticmethod
|
|
|
|
def _rpc_get_logs(limit: Optional[int]) -> Dict[str, Any]:
|
2020-08-14 13:44:36 +00:00
|
|
|
"""Returns the last X logs"""
|
|
|
|
if limit:
|
|
|
|
buffer = bufferHandler.buffer[-limit:]
|
|
|
|
else:
|
|
|
|
buffer = bufferHandler.buffer
|
2020-10-17 18:32:23 +00:00
|
|
|
records = [[datetime.fromtimestamp(r.created).strftime(DATETIME_PRINT_FORMAT),
|
2020-08-27 10:04:55 +00:00
|
|
|
r.created * 1000, r.name, r.levelname,
|
2020-08-15 18:15:02 +00:00
|
|
|
r.message + ('\n' + r.exc_text if r.exc_text else '')]
|
2020-08-14 17:36:12 +00:00
|
|
|
for r in buffer]
|
2020-08-14 13:44:36 +00:00
|
|
|
|
2020-08-27 12:41:31 +00:00
|
|
|
# Log format:
|
2020-08-27 10:04:55 +00:00
|
|
|
# [logtime-formatted, logepoch, logger-name, loglevel, message \n + exception]
|
|
|
|
# e.g. ["2020-08-27 11:35:01", 1598520901097.9397,
|
2020-08-27 12:41:31 +00:00
|
|
|
# "freqtrade.worker", "INFO", "Starting worker develop"]
|
2020-08-27 10:04:55 +00:00
|
|
|
|
2020-08-14 13:44:36 +00:00
|
|
|
return {'log_count': len(records), 'logs': records}
|
|
|
|
|
2019-03-25 09:16:09 +00:00
|
|
|
def _rpc_edge(self) -> List[Dict[str, Any]]:
|
2019-03-24 21:36:33 +00:00
|
|
|
""" Returns information related to Edge """
|
|
|
|
if not self._freqtrade.edge:
|
2020-05-18 09:40:25 +00:00
|
|
|
raise RPCException('Edge is not enabled.')
|
2019-04-03 12:14:47 +00:00
|
|
|
return self._freqtrade.edge.accepted_pairs()
|
2020-06-12 17:32:44 +00:00
|
|
|
|
2020-10-16 04:26:57 +00:00
|
|
|
@staticmethod
|
|
|
|
def _convert_dataframe_to_dict(strategy: str, pair: str, timeframe: str, dataframe: DataFrame,
|
|
|
|
last_analyzed: datetime) -> Dict[str, Any]:
|
2020-08-24 18:38:01 +00:00
|
|
|
has_content = len(dataframe) != 0
|
2021-11-20 19:09:37 +00:00
|
|
|
signals = {
|
|
|
|
'enter_long': 0,
|
|
|
|
'exit_long': 0,
|
|
|
|
'enter_short': 0,
|
|
|
|
'exit_short': 0,
|
|
|
|
}
|
2020-08-24 18:38:01 +00:00
|
|
|
if has_content:
|
|
|
|
|
2021-07-09 18:46:38 +00:00
|
|
|
dataframe.loc[:, '__date_ts'] = dataframe.loc[:, 'date'].view(int64) // 1000 // 1000
|
2021-11-14 08:50:04 +00:00
|
|
|
# Move signal close to separate column when signal for easy plotting
|
2021-11-20 19:09:37 +00:00
|
|
|
for sig_type in signals.keys():
|
|
|
|
if sig_type in dataframe.columns:
|
|
|
|
mask = (dataframe[sig_type] == 1)
|
|
|
|
signals[sig_type] = int(mask.sum())
|
|
|
|
dataframe.loc[mask, f'_{sig_type}_signal_close'] = dataframe.loc[mask, 'close']
|
2022-02-09 06:02:44 +00:00
|
|
|
|
|
|
|
# band-aid until this is fixed:
|
|
|
|
# https://github.com/pandas-dev/pandas/issues/45836
|
2022-02-08 15:42:39 +00:00
|
|
|
datetime_types = ['datetime', 'datetime64', 'datetime64[ns, UTC]']
|
|
|
|
date_columns = dataframe.select_dtypes(include=datetime_types)
|
|
|
|
for date_column in date_columns:
|
2022-02-09 08:32:53 +00:00
|
|
|
# replace NaT with `None`
|
2022-02-09 05:48:26 +00:00
|
|
|
dataframe[date_column] = dataframe[date_column].astype(object).replace({NaT: None})
|
2022-02-08 15:42:39 +00:00
|
|
|
|
2022-02-09 05:48:26 +00:00
|
|
|
dataframe = dataframe.replace({inf: None, -inf: None, NAN: None})
|
2020-08-24 18:38:01 +00:00
|
|
|
|
|
|
|
res = {
|
2020-07-02 05:10:56 +00:00
|
|
|
'pair': pair,
|
2020-09-14 05:59:47 +00:00
|
|
|
'timeframe': timeframe,
|
|
|
|
'timeframe_ms': timeframe_to_msecs(timeframe),
|
2020-07-31 05:32:27 +00:00
|
|
|
'strategy': strategy,
|
2020-07-02 05:10:56 +00:00
|
|
|
'columns': list(dataframe.columns),
|
|
|
|
'data': dataframe.values.tolist(),
|
|
|
|
'length': len(dataframe),
|
2021-11-20 19:09:37 +00:00
|
|
|
'buy_signals': signals['enter_long'], # Deprecated
|
|
|
|
'sell_signals': signals['exit_long'], # Deprecated
|
|
|
|
'enter_long_signals': signals['enter_long'],
|
|
|
|
'exit_long_signals': signals['exit_long'],
|
|
|
|
'enter_short_signals': signals['enter_short'],
|
|
|
|
'exit_short_signals': signals['exit_short'],
|
2020-07-02 05:10:56 +00:00
|
|
|
'last_analyzed': last_analyzed,
|
2020-07-11 13:20:50 +00:00
|
|
|
'last_analyzed_ts': int(last_analyzed.timestamp()),
|
2020-08-24 18:38:01 +00:00
|
|
|
'data_start': '',
|
|
|
|
'data_start_ts': 0,
|
|
|
|
'data_stop': '',
|
|
|
|
'data_stop_ts': 0,
|
2020-07-02 05:10:56 +00:00
|
|
|
}
|
2020-08-24 18:38:01 +00:00
|
|
|
if has_content:
|
|
|
|
res.update({
|
|
|
|
'data_start': str(dataframe.iloc[0]['date']),
|
|
|
|
'data_start_ts': int(dataframe.iloc[0]['__date_ts']),
|
|
|
|
'data_stop': str(dataframe.iloc[-1]['date']),
|
|
|
|
'data_stop_ts': int(dataframe.iloc[-1]['__date_ts']),
|
|
|
|
})
|
|
|
|
return res
|
2020-07-02 05:10:56 +00:00
|
|
|
|
2021-02-11 19:29:31 +00:00
|
|
|
def _rpc_analysed_dataframe(self, pair: str, timeframe: str,
|
|
|
|
limit: Optional[int]) -> Dict[str, Any]:
|
2022-09-02 02:06:36 +00:00
|
|
|
""" Analyzed dataframe in Dict form """
|
2020-06-12 17:32:44 +00:00
|
|
|
|
2022-09-02 02:06:36 +00:00
|
|
|
_data, last_analyzed = self.__rpc_analysed_dataframe_raw(pair, timeframe, limit)
|
|
|
|
return self._convert_dataframe_to_dict(self._freqtrade.config['strategy'],
|
|
|
|
pair, timeframe, _data, last_analyzed)
|
|
|
|
|
2022-11-26 01:09:47 +00:00
|
|
|
def __rpc_analysed_dataframe_raw(
|
|
|
|
self,
|
|
|
|
pair: str,
|
|
|
|
timeframe: str,
|
2022-12-05 20:11:07 +00:00
|
|
|
limit: Optional[int]
|
2022-11-26 01:09:47 +00:00
|
|
|
) -> Tuple[DataFrame, datetime]:
|
|
|
|
"""
|
|
|
|
Get the dataframe and last analyze from the dataprovider
|
|
|
|
|
|
|
|
:param pair: The pair to get
|
|
|
|
:param timeframe: The timeframe of data to get
|
2022-11-26 02:04:51 +00:00
|
|
|
:param limit: The amount of candles in the dataframe
|
2022-11-26 01:09:47 +00:00
|
|
|
"""
|
2020-08-24 18:38:01 +00:00
|
|
|
_data, last_analyzed = self._freqtrade.dataprovider.get_analyzed_dataframe(
|
|
|
|
pair, timeframe)
|
|
|
|
_data = _data.copy()
|
2022-09-02 02:06:36 +00:00
|
|
|
|
2020-06-15 05:53:23 +00:00
|
|
|
if limit:
|
2020-08-24 18:38:01 +00:00
|
|
|
_data = _data.iloc[-limit:]
|
2022-11-26 01:09:47 +00:00
|
|
|
|
2022-09-02 02:06:36 +00:00
|
|
|
return _data, last_analyzed
|
|
|
|
|
|
|
|
def _ws_all_analysed_dataframes(
|
|
|
|
self,
|
|
|
|
pairlist: List[str],
|
|
|
|
limit: Optional[int]
|
2022-11-14 06:25:52 +00:00
|
|
|
) -> Generator[Dict[str, Any], None, None]:
|
2022-11-26 01:09:47 +00:00
|
|
|
"""
|
|
|
|
Get the analysed dataframes of each pair in the pairlist.
|
2022-12-13 05:46:19 +00:00
|
|
|
If specified, only return the most recent `limit` candles for
|
|
|
|
each dataframe.
|
2022-11-26 01:09:47 +00:00
|
|
|
|
|
|
|
:param pairlist: A list of pairs to get
|
|
|
|
:param limit: If an integer, limits the size of dataframe
|
|
|
|
If a list of string date times, only returns those candles
|
|
|
|
:returns: A generator of dictionaries with the key, dataframe, and last analyzed timestamp
|
|
|
|
"""
|
2022-09-02 02:06:36 +00:00
|
|
|
timeframe = self._freqtrade.config['timeframe']
|
|
|
|
candle_type = self._freqtrade.config.get('candle_type_def', CandleType.SPOT)
|
|
|
|
|
|
|
|
for pair in pairlist:
|
|
|
|
dataframe, last_analyzed = self.__rpc_analysed_dataframe_raw(pair, timeframe, limit)
|
2022-09-07 21:08:01 +00:00
|
|
|
|
2022-11-14 06:25:52 +00:00
|
|
|
yield {
|
2022-09-07 21:08:01 +00:00
|
|
|
"key": (pair, timeframe, candle_type),
|
|
|
|
"df": dataframe,
|
|
|
|
"la": last_analyzed
|
|
|
|
}
|
2020-07-02 05:10:56 +00:00
|
|
|
|
2022-11-26 01:09:47 +00:00
|
|
|
def _ws_request_analyzed_df(
|
|
|
|
self,
|
2022-11-26 02:04:51 +00:00
|
|
|
limit: Optional[int] = None,
|
2022-11-27 19:18:41 +00:00
|
|
|
pair: Optional[str] = None
|
2022-11-26 01:09:47 +00:00
|
|
|
):
|
2022-09-02 05:52:13 +00:00
|
|
|
""" Historical Analyzed Dataframes for WebSocket """
|
2022-11-26 01:09:47 +00:00
|
|
|
pairlist = [pair] if pair else self._freqtrade.active_pair_whitelist
|
|
|
|
|
|
|
|
return self._ws_all_analysed_dataframes(pairlist, limit)
|
2022-09-02 02:06:36 +00:00
|
|
|
|
2022-09-02 05:52:13 +00:00
|
|
|
def _ws_request_whitelist(self):
|
|
|
|
""" Whitelist data for WebSocket """
|
|
|
|
return self._freqtrade.active_pair_whitelist
|
2022-09-02 02:06:36 +00:00
|
|
|
|
2022-09-09 05:13:05 +00:00
|
|
|
@staticmethod
|
2023-01-18 05:45:31 +00:00
|
|
|
def _rpc_analysed_history_full(config: Config, pair: str, timeframe: str,
|
2022-01-22 06:11:59 +00:00
|
|
|
timerange: str, exchange) -> Dict[str, Any]:
|
2020-10-02 04:41:28 +00:00
|
|
|
timerange_parsed = TimeRange.parse_timerange(timerange)
|
2020-07-02 05:10:56 +00:00
|
|
|
|
|
|
|
_data = load_data(
|
2023-01-18 05:45:31 +00:00
|
|
|
datadir=config["datadir"],
|
2020-07-02 05:10:56 +00:00
|
|
|
pairs=[pair],
|
2020-07-26 18:31:11 +00:00
|
|
|
timeframe=timeframe,
|
2020-10-02 04:41:28 +00:00
|
|
|
timerange=timerange_parsed,
|
2020-07-26 18:31:11 +00:00
|
|
|
data_format=config.get('dataformat_ohlcv', 'json'),
|
2022-04-01 06:57:58 +00:00
|
|
|
candle_type=config.get('candle_type_def', CandleType.SPOT)
|
2020-07-02 05:10:56 +00:00
|
|
|
)
|
2021-01-06 14:38:46 +00:00
|
|
|
if pair not in _data:
|
|
|
|
raise RPCException(f"No data for {pair}, {timeframe} in {timerange} found.")
|
2021-06-24 16:18:01 +00:00
|
|
|
from freqtrade.data.dataprovider import DataProvider
|
2021-06-24 16:44:59 +00:00
|
|
|
from freqtrade.resolvers.strategy_resolver import StrategyResolver
|
2020-07-26 18:31:11 +00:00
|
|
|
strategy = StrategyResolver.load_strategy(config)
|
2022-01-22 06:11:59 +00:00
|
|
|
strategy.dp = DataProvider(config, exchange=exchange, pairlists=None)
|
2021-06-24 16:18:01 +00:00
|
|
|
|
2020-07-02 06:39:07 +00:00
|
|
|
df_analyzed = strategy.analyze_ticker(_data[pair], {'pair': pair})
|
2020-07-02 05:10:56 +00:00
|
|
|
|
2020-10-16 04:26:57 +00:00
|
|
|
return RPC._convert_dataframe_to_dict(strategy.get_strategy_name(), pair, timeframe,
|
|
|
|
df_analyzed, arrow.Arrow.utcnow().datetime)
|
2020-06-23 04:49:53 +00:00
|
|
|
|
|
|
|
def _rpc_plot_config(self) -> Dict[str, Any]:
|
2021-05-14 04:36:18 +00:00
|
|
|
if (self._freqtrade.strategy.plot_config and
|
|
|
|
'subplots' not in self._freqtrade.strategy.plot_config):
|
|
|
|
self._freqtrade.strategy.plot_config['subplots'] = {}
|
2020-06-23 04:49:53 +00:00
|
|
|
return self._freqtrade.strategy.plot_config
|
2021-09-25 14:48:42 +00:00
|
|
|
|
2023-01-18 17:15:07 +00:00
|
|
|
@staticmethod
|
|
|
|
def _rpc_plot_config_with_strategy(config: Config) -> Dict[str, Any]:
|
|
|
|
|
|
|
|
from freqtrade.resolvers.strategy_resolver import StrategyResolver
|
|
|
|
strategy = StrategyResolver.load_strategy(config)
|
|
|
|
|
|
|
|
if (strategy.plot_config and 'subplots' not in strategy.plot_config):
|
|
|
|
strategy.plot_config['subplots'] = {}
|
|
|
|
return strategy.plot_config
|
|
|
|
|
2022-09-09 05:13:05 +00:00
|
|
|
@staticmethod
|
2021-10-04 23:10:39 +00:00
|
|
|
def _rpc_sysinfo() -> Dict[str, Any]:
|
2021-10-06 17:36:28 +00:00
|
|
|
return {
|
|
|
|
"cpu_pct": psutil.cpu_percent(interval=1, percpu=True),
|
|
|
|
"ram_pct": psutil.virtual_memory().percent
|
|
|
|
}
|
2022-01-23 19:58:46 +00:00
|
|
|
|
2023-02-27 10:14:38 +00:00
|
|
|
def health(self) -> Dict[str, Optional[Union[str, int]]]:
|
2022-01-28 06:57:43 +00:00
|
|
|
last_p = self._freqtrade.last_process
|
2023-02-27 10:14:38 +00:00
|
|
|
if last_p is None:
|
|
|
|
return {
|
|
|
|
"last_process": None,
|
|
|
|
"last_process_loc": None,
|
|
|
|
"last_process_ts": None,
|
|
|
|
}
|
|
|
|
|
2022-01-23 19:58:46 +00:00
|
|
|
return {
|
2023-02-27 10:14:38 +00:00
|
|
|
"last_process": str(last_p),
|
|
|
|
"last_process_loc": last_p.astimezone(tzlocal()).strftime(DATETIME_PRINT_FORMAT),
|
|
|
|
"last_process_ts": int(last_p.timestamp()),
|
2022-01-23 19:58:46 +00:00
|
|
|
}
|
2023-02-18 23:50:02 +00:00
|
|
|
|
2023-02-27 22:51:22 +00:00
|
|
|
def _update_market_direction(self, direction: MarketDirection) -> None:
|
2023-02-19 16:11:21 +00:00
|
|
|
self._freqtrade.strategy.market_direction = direction
|
2023-02-27 22:51:22 +00:00
|
|
|
|
|
|
|
def _get_market_direction(self) -> MarketDirection:
|
|
|
|
return self._freqtrade.strategy.market_direction
|