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
|
2019-11-12 12:54:26 +00:00
|
|
|
from datetime import date, datetime, timedelta
|
2018-07-03 18:26:48 +00:00
|
|
|
from enum import Enum
|
2019-11-12 13:58:41 +00:00
|
|
|
from math import isnan
|
2019-11-12 12:54:26 +00:00
|
|
|
from typing import Any, Dict, List, Optional, Tuple
|
2018-03-17 21:44:47 +00:00
|
|
|
|
2018-03-02 15:22:00 +00:00
|
|
|
import arrow
|
2019-11-12 12:54:26 +00:00
|
|
|
from numpy import NAN, mean
|
2018-03-17 21:44:47 +00:00
|
|
|
|
2019-11-12 12:54:26 +00:00
|
|
|
from freqtrade import DependencyException, TemporaryError
|
2018-03-17 21:44:47 +00:00
|
|
|
from freqtrade.misc import shorten_date
|
2018-02-13 03:45:59 +00:00
|
|
|
from freqtrade.persistence import Trade
|
2018-12-11 19:27:30 +00:00
|
|
|
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
|
2018-02-13 03:45:59 +00:00
|
|
|
from freqtrade.state import State
|
2018-07-12 20:21:52 +00:00
|
|
|
from freqtrade.strategy.interface import SellType
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2018-03-25 19:37:14 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2018-07-03 18:26:48 +00:00
|
|
|
class RPCMessageType(Enum):
|
|
|
|
STATUS_NOTIFICATION = 'status'
|
2018-08-15 02:39:32 +00:00
|
|
|
WARNING_NOTIFICATION = 'warning'
|
|
|
|
CUSTOM_NOTIFICATION = 'custom'
|
2018-07-03 18:26:48 +00:00
|
|
|
BUY_NOTIFICATION = 'buy'
|
|
|
|
SELL_NOTIFICATION = 'sell'
|
|
|
|
|
|
|
|
def __repr__(self):
|
|
|
|
return self.value
|
|
|
|
|
|
|
|
|
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`')
|
|
|
|
"""
|
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
|
|
|
|
2019-09-12 01:39:52 +00:00
|
|
|
class RPC:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
RPC class can be used to have extra feature, like bot data, and access to DB data
|
|
|
|
"""
|
2018-07-24 22:08:40 +00:00
|
|
|
# Bind _fiat_converter if needed in each RPC handler
|
2018-07-22 12:35:29 +00:00
|
|
|
_fiat_converter: Optional[CryptoToFiatConverter] = None
|
2018-07-21 18:44:38 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
def __init__(self, freqtrade) -> None:
|
|
|
|
"""
|
|
|
|
Initializes all enabled rpc modules
|
|
|
|
:param freqtrade: Instance of a freqtrade bot
|
|
|
|
:return: None
|
|
|
|
"""
|
2018-06-08 22:20:10 +00:00
|
|
|
self._freqtrade = freqtrade
|
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 """
|
|
|
|
|
2019-11-17 14:12:53 +00:00
|
|
|
def _rpc_show_config(self) -> 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.
|
|
|
|
"""
|
|
|
|
config = self._freqtrade.config
|
|
|
|
val = {
|
|
|
|
'dry_run': config.get('dry_run', False),
|
|
|
|
'stake_currency': config['stake_currency'],
|
|
|
|
'stake_amount': config['stake_amount'],
|
|
|
|
'minimal_roi': config['minimal_roi'].copy(),
|
|
|
|
'stoploss': config['stoploss'],
|
|
|
|
'trailing_stop': config['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'),
|
2019-11-17 13:56:08 +00:00
|
|
|
'ticker_interval': config['ticker_interval'],
|
|
|
|
'exchange': config['exchange']['name'],
|
|
|
|
'strategy': config['strategy'],
|
|
|
|
}
|
|
|
|
return val
|
|
|
|
|
2018-07-12 15:27:40 +00:00
|
|
|
def _rpc_trade_status(self) -> 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
|
|
|
|
"""
|
|
|
|
# Fetch open trade
|
2019-02-25 19:00:17 +00:00
|
|
|
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:
|
|
|
|
order = None
|
|
|
|
if trade.open_order_id:
|
2018-06-17 19:24:36 +00:00
|
|
|
order = self._freqtrade.exchange.get_order(trade.open_order_id, trade.pair)
|
2018-02-13 03:45:59 +00:00
|
|
|
# calculate profit and send message to user
|
2018-10-10 19:28:48 +00:00
|
|
|
try:
|
2019-03-16 12:24:10 +00:00
|
|
|
current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
|
2018-10-10 19:28:48 +00:00
|
|
|
except DependencyException:
|
|
|
|
current_rate = NAN
|
2019-12-17 07:53:30 +00:00
|
|
|
current_profit = trade.calc_profit_ratio(current_rate)
|
2018-07-04 18:53:45 +00:00
|
|
|
fmt_close_profit = (f'{round(trade.close_profit * 100, 2):.2f}%'
|
|
|
|
if trade.close_profit else None)
|
2019-05-05 12:07:08 +00:00
|
|
|
trade_dict = trade.to_json()
|
|
|
|
trade_dict.update(dict(
|
2019-04-03 14:28:44 +00:00
|
|
|
base_currency=self._freqtrade.config['stake_currency'],
|
2018-06-22 01:54:10 +00:00
|
|
|
close_profit=fmt_close_profit,
|
2019-05-05 12:07:08 +00:00
|
|
|
current_rate=current_rate,
|
2018-06-22 01:54:10 +00:00
|
|
|
current_profit=round(current_profit * 100, 2),
|
|
|
|
open_order='({} {} rem={:.8f})'.format(
|
2019-04-03 18:28:03 +00:00
|
|
|
order['type'], order['side'], order['remaining']
|
2018-06-22 01:54:10 +00:00
|
|
|
) if order else None,
|
|
|
|
))
|
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
|
|
|
|
2019-11-12 13:58:41 +00:00
|
|
|
def _rpc_status_table(self, stake_currency, fiat_display_currency: str) -> Tuple[List, List]:
|
2019-02-25 19:00:17 +00:00
|
|
|
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 order')
|
2018-02-13 03:45:59 +00:00
|
|
|
else:
|
|
|
|
trades_list = []
|
|
|
|
for trade in trades:
|
|
|
|
# calculate profit and send message to user
|
2018-10-10 19:28:48 +00:00
|
|
|
try:
|
2019-03-16 12:24:10 +00:00
|
|
|
current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
|
2018-10-10 19:28:48 +00:00
|
|
|
except DependencyException:
|
|
|
|
current_rate = NAN
|
2019-12-17 07:53:30 +00:00
|
|
|
trade_perc = (100 * trade.calc_profit_ratio(current_rate))
|
2019-11-12 13:58:41 +00:00
|
|
|
trade_profit = trade.calc_profit(current_rate)
|
|
|
|
profit_str = f'{trade_perc:.2f}%'
|
|
|
|
if self._fiat_converter:
|
|
|
|
fiat_profit = self._fiat_converter.convert_amount(
|
|
|
|
trade_profit,
|
|
|
|
stake_currency,
|
|
|
|
fiat_display_currency
|
|
|
|
)
|
|
|
|
if fiat_profit and not isnan(fiat_profit):
|
|
|
|
profit_str += f" ({fiat_profit:.2f})"
|
2018-02-13 03:45:59 +00:00
|
|
|
trades_list.append([
|
|
|
|
trade.id,
|
|
|
|
trade.pair,
|
|
|
|
shorten_date(arrow.get(trade.open_date).humanize(only_distance=True)),
|
2019-11-12 13:58:41 +00:00
|
|
|
profit_str
|
2018-02-13 03:45:59 +00:00
|
|
|
])
|
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
|
|
|
|
2019-11-12 13:58:41 +00:00
|
|
|
columns = ['ID', 'Pair', 'Since', profitcol]
|
2019-11-12 12:54:26 +00:00
|
|
|
return trades_list, columns
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
def _rpc_daily_profit(
|
2018-03-17 22:30:31 +00:00
|
|
|
self, timescale: int,
|
2018-06-08 02:52:50 +00:00
|
|
|
stake_currency: str, fiat_display_currency: str) -> List[List[Any]]:
|
2018-02-13 03:45:59 +00:00
|
|
|
today = datetime.utcnow().date()
|
2018-06-02 11:43:51 +00:00
|
|
|
profit_days: Dict[date, Dict] = {}
|
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
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
for day in range(0, timescale):
|
|
|
|
profitday = today - timedelta(days=day)
|
2019-10-29 14:09:01 +00:00
|
|
|
trades = Trade.get_trades(trade_filter=[
|
|
|
|
Trade.is_open.is_(False),
|
|
|
|
Trade.close_date >= profitday,
|
|
|
|
Trade.close_date < (profitday + timedelta(days=1))
|
|
|
|
]).order_by(Trade.close_date).all()
|
2018-02-13 03:45:59 +00:00
|
|
|
curdayprofit = sum(trade.calc_profit() for trade in trades)
|
|
|
|
profit_days[profitday] = {
|
2018-07-04 18:53:45 +00:00
|
|
|
'amount': f'{curdayprofit:.8f}',
|
2018-02-13 03:45:59 +00:00
|
|
|
'trades': len(trades)
|
|
|
|
}
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
return [
|
2018-02-13 03:45:59 +00:00
|
|
|
[
|
|
|
|
key,
|
|
|
|
'{value:.8f} {symbol}'.format(
|
|
|
|
value=float(value['amount']),
|
|
|
|
symbol=stake_currency
|
|
|
|
),
|
|
|
|
'{value:.3f} {symbol}'.format(
|
2018-07-22 12:35:29 +00:00
|
|
|
value=self._fiat_converter.convert_amount(
|
2018-02-13 03:45:59 +00:00
|
|
|
value['amount'],
|
|
|
|
stake_currency,
|
|
|
|
fiat_display_currency
|
2018-07-21 18:44:38 +00:00
|
|
|
) if self._fiat_converter else 0,
|
2018-02-13 03:45:59 +00:00
|
|
|
symbol=fiat_display_currency
|
|
|
|
),
|
2018-03-02 15:22:00 +00:00
|
|
|
'{value} trade{s}'.format(
|
|
|
|
value=value['trades'],
|
|
|
|
s='' if value['trades'] < 2 else 's'
|
|
|
|
),
|
2018-02-13 03:45:59 +00:00
|
|
|
]
|
|
|
|
for key, value in profit_days.items()
|
|
|
|
]
|
|
|
|
|
2018-06-08 02:52:50 +00:00
|
|
|
def _rpc_trade_statistics(
|
|
|
|
self, stake_currency: str, fiat_display_currency: str) -> Dict[str, Any]:
|
|
|
|
""" Returns cumulative profit statistics """
|
2019-10-29 14:09:01 +00:00
|
|
|
trades = Trade.get_trades().order_by(Trade.id).all()
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
profit_all_coin = []
|
2019-08-11 11:46:32 +00:00
|
|
|
profit_all_perc = []
|
2018-02-13 03:45:59 +00:00
|
|
|
profit_closed_coin = []
|
2019-08-11 11:46:32 +00:00
|
|
|
profit_closed_perc = []
|
2018-02-13 03:45:59 +00:00
|
|
|
durations = []
|
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 not trade.open_rate:
|
|
|
|
continue
|
|
|
|
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:
|
2019-12-17 07:53:30 +00:00
|
|
|
profit_percent = trade.calc_profit_ratio()
|
2018-02-13 03:45:59 +00:00
|
|
|
profit_closed_coin.append(trade.calc_profit())
|
2019-08-11 11:46:32 +00:00
|
|
|
profit_closed_perc.append(profit_percent)
|
2018-02-13 03:45:59 +00:00
|
|
|
else:
|
|
|
|
# Get current rate
|
2018-10-10 19:28:48 +00:00
|
|
|
try:
|
2019-03-16 12:24:10 +00:00
|
|
|
current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
|
2018-10-10 19:28:48 +00:00
|
|
|
except DependencyException:
|
|
|
|
current_rate = NAN
|
2019-12-17 07:53:30 +00:00
|
|
|
profit_percent = trade.calc_profit_ratio(rate=current_rate)
|
2018-03-02 15:22:00 +00:00
|
|
|
|
|
|
|
profit_all_coin.append(
|
2019-11-12 14:11:31 +00:00
|
|
|
trade.calc_profit(rate=trade.close_rate or current_rate)
|
2018-03-02 15:22:00 +00:00
|
|
|
)
|
2019-08-11 11:46:32 +00:00
|
|
|
profit_all_perc.append(profit_percent)
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2019-10-29 10:15:33 +00:00
|
|
|
best_pair = Trade.get_best_pair()
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
if not best_pair:
|
2018-06-22 01:37:19 +00:00
|
|
|
raise RPCException('no closed trade')
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
bp_pair, bp_rate = best_pair
|
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)
|
2019-08-11 11:46:32 +00:00
|
|
|
profit_closed_percent = (round(mean(profit_closed_perc) * 100, 2) if profit_closed_perc
|
|
|
|
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)
|
2019-08-11 11:46:32 +00:00
|
|
|
profit_all_percent = round(mean(profit_all_perc) * 100, 2) if profit_all_perc else 0.0
|
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
|
|
|
|
|
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,
|
2018-06-08 02:52:50 +00:00
|
|
|
'profit_closed_percent': profit_closed_percent,
|
|
|
|
'profit_closed_fiat': profit_closed_fiat,
|
2018-07-14 05:02:39 +00:00
|
|
|
'profit_all_coin': profit_all_coin_sum,
|
2018-06-08 02:52:50 +00:00
|
|
|
'profit_all_percent': profit_all_percent,
|
|
|
|
'profit_all_fiat': profit_all_fiat,
|
|
|
|
'trade_count': len(trades),
|
|
|
|
'first_trade_date': arrow.get(trades[0].open_date).humanize(),
|
|
|
|
'latest_trade_date': arrow.get(trades[-1].open_date).humanize(),
|
|
|
|
'avg_duration': str(timedelta(seconds=sum(durations) / num)).split('.')[0],
|
|
|
|
'best_pair': bp_pair,
|
|
|
|
'best_rate': round(bp_rate * 100, 2),
|
|
|
|
}
|
|
|
|
|
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 """
|
2018-02-13 03:45:59 +00:00
|
|
|
output = []
|
|
|
|
total = 0.0
|
2019-11-14 19:12:41 +00:00
|
|
|
try:
|
|
|
|
tickers = self._freqtrade.exchange.get_tickers()
|
|
|
|
except (TemporaryError, DependencyException):
|
|
|
|
raise RPCException('Error getting current tickers.')
|
|
|
|
|
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
|
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)
|
|
|
|
rate = tickers.get(pair, {}).get('bid', None)
|
|
|
|
if rate:
|
|
|
|
if pair.startswith(stake_currency):
|
|
|
|
rate = 1.0 / rate
|
2019-11-24 18:41:51 +00:00
|
|
|
est_stake = rate * balance.total
|
2018-10-10 19:28:48 +00:00
|
|
|
except (TemporaryError, DependencyException):
|
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
|
2019-11-15 05:33:07 +00:00
|
|
|
total = total + (est_stake or 0)
|
2018-06-22 02:08:51 +00:00
|
|
|
output.append({
|
|
|
|
'currency': coin,
|
2019-11-24 18:41:51 +00:00
|
|
|
'free': balance.free if balance.free is not None else 0,
|
|
|
|
'balance': balance.total if balance.total is not None else 0,
|
|
|
|
'used': balance.used if balance.used is not None else 0,
|
2019-11-15 05:33:07 +00:00
|
|
|
'est_stake': est_stake or 0,
|
|
|
|
'stake': stake_currency,
|
2018-06-22 02:08:51 +00:00
|
|
|
})
|
2018-05-14 21:31:56 +00:00
|
|
|
if total == 0.0:
|
2019-06-27 05:06:11 +00:00
|
|
|
if self._freqtrade.config.get('dry_run', False):
|
|
|
|
raise RPCException('Running in Dry Run, balances are not available.')
|
|
|
|
else:
|
|
|
|
raise RPCException('All balances are zero.')
|
2018-05-14 21:31:56 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
symbol = fiat_display_currency
|
2019-12-24 05:58:30 +00:00
|
|
|
value = self._fiat_converter.convert_amount(total, stake_currency,
|
2018-07-21 18:44:38 +00:00
|
|
|
symbol) if self._fiat_converter else 0
|
2018-06-22 02:08:51 +00:00
|
|
|
return {
|
|
|
|
'currencies': output,
|
|
|
|
'total': total,
|
|
|
|
'symbol': symbol,
|
|
|
|
'value': value,
|
2019-12-24 05:58:30 +00:00
|
|
|
'stake': stake_currency,
|
2019-12-15 09:41:57 +00:00
|
|
|
'note': 'Simulated balances' if self._freqtrade.config.get('dry_run', False) 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
|
|
|
|
2018-06-22 01:32:45 +00:00
|
|
|
def _rpc_reload_conf(self) -> Dict[str, str]:
|
2018-06-09 02:29:48 +00:00
|
|
|
""" Handler for reload_conf. """
|
2018-06-13 13:29:27 +00:00
|
|
|
self._freqtrade.state = State.RELOAD_CONF
|
2018-06-22 01:32:45 +00:00
|
|
|
return {'status': 'reloading config ...'}
|
2018-06-09 02:29:48 +00:00
|
|
|
|
2019-03-17 18:35:25 +00:00
|
|
|
def _rpc_stopbuy(self) -> Dict[str, str]:
|
|
|
|
"""
|
|
|
|
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
|
|
|
|
|
2019-03-18 05:27:44 +00:00
|
|
|
return {'status': 'No more buy will occur from now. Run /reload_conf to reset.'}
|
2019-03-17 18:35:25 +00:00
|
|
|
|
2019-04-30 04:23:14 +00:00
|
|
|
def _rpc_forcesell(self, trade_id) -> Dict[str, str]:
|
2018-02-13 03:45:59 +00:00
|
|
|
"""
|
|
|
|
Handler for forcesell <id>.
|
|
|
|
Sells the given trade at current price
|
|
|
|
"""
|
2018-03-17 22:30:31 +00:00
|
|
|
def _exec_forcesell(trade: Trade) -> None:
|
2018-02-13 03:45:59 +00:00
|
|
|
# Check if there is there is an open order
|
|
|
|
if trade.open_order_id:
|
2018-06-17 19:24:36 +00:00
|
|
|
order = self._freqtrade.exchange.get_order(trade.open_order_id, trade.pair)
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
# Cancel open LIMIT_BUY orders and close trade
|
2018-03-25 20:25:26 +00:00
|
|
|
if order and order['status'] == 'open' \
|
|
|
|
and order['type'] == 'limit' \
|
|
|
|
and order['side'] == 'buy':
|
2018-06-17 19:24:36 +00:00
|
|
|
self._freqtrade.exchange.cancel_order(trade.open_order_id, trade.pair)
|
2018-03-25 20:25:26 +00:00
|
|
|
trade.close(order.get('price') or trade.open_rate)
|
2018-05-25 14:29:06 +00:00
|
|
|
# Do the best effort, if we don't know 'filled' amount, don't try selling
|
|
|
|
if order['filled'] is None:
|
|
|
|
return
|
|
|
|
trade.amount = order['filled']
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
# Ignore trades with an attached LIMIT_SELL order
|
2018-03-25 20:25:26 +00:00
|
|
|
if order and order['status'] == 'open' \
|
|
|
|
and order['type'] == 'limit' \
|
|
|
|
and order['side'] == 'sell':
|
2018-02-13 03:45:59 +00:00
|
|
|
return
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
# Get current rate and execute sell
|
2019-03-16 12:24:10 +00:00
|
|
|
current_rate = self._freqtrade.get_sell_rate(trade.pair, False)
|
2018-07-11 17:57:01 +00:00
|
|
|
self._freqtrade.execute_sell(trade, current_rate, SellType.FORCE_SELL)
|
2018-02-13 03:45:59 +00:00
|
|
|
# ---- EOF def _exec_forcesell ----
|
|
|
|
|
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
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
if trade_id == 'all':
|
|
|
|
# Execute sell for all open orders
|
2019-02-25 19:00:17 +00:00
|
|
|
for trade in Trade.get_open_trades():
|
2018-02-13 03:45:59 +00:00
|
|
|
_exec_forcesell(trade)
|
2018-10-09 19:08:56 +00:00
|
|
|
Trade.session.flush()
|
2019-04-30 04:23:14 +00:00
|
|
|
return {'result': 'Created sell orders for all open trades.'}
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
# Query for trade
|
2019-10-29 14:09:01 +00:00
|
|
|
trade = Trade.get_trades(
|
|
|
|
trade_filter=[Trade.id == trade_id, Trade.is_open.is_(True), ]
|
2018-02-13 03:45:59 +00:00
|
|
|
).first()
|
|
|
|
if not trade:
|
2018-03-25 19:37:14 +00:00
|
|
|
logger.warning('forcesell: Invalid argument received')
|
2018-06-22 01:37:19 +00:00
|
|
|
raise RPCException('invalid argument')
|
2018-03-02 15:22:00 +00:00
|
|
|
|
2018-02-13 03:45:59 +00:00
|
|
|
_exec_forcesell(trade)
|
2018-06-08 00:35:10 +00:00
|
|
|
Trade.session.flush()
|
2019-05-01 14:21:14 +00:00
|
|
|
return {'result': f'Created sell order for trade {trade_id}.'}
|
2018-02-13 03:45:59 +00:00
|
|
|
|
2018-10-09 17:25:43 +00:00
|
|
|
def _rpc_forcebuy(self, pair: str, price: Optional[float]) -> Optional[Trade]:
|
|
|
|
"""
|
|
|
|
Handler for forcebuy <asset> <price>
|
|
|
|
Buys a pair trade at the given or current price
|
|
|
|
"""
|
|
|
|
|
|
|
|
if not self._freqtrade.config.get('forcebuy_enable', False):
|
|
|
|
raise RPCException('Forcebuy not enabled.')
|
|
|
|
|
|
|
|
if self._freqtrade.state != State.RUNNING:
|
|
|
|
raise RPCException('trader is not running')
|
|
|
|
|
|
|
|
# Check pair is in stake currency
|
|
|
|
stake_currency = self._freqtrade.config.get('stake_currency')
|
|
|
|
if not pair.endswith(stake_currency):
|
|
|
|
raise RPCException(
|
|
|
|
f'Wrong pair selected. Please pairs with stake {stake_currency} pairs only')
|
|
|
|
# check if valid pair
|
|
|
|
|
|
|
|
# check if pair already has an open pair
|
2019-10-29 14:09:01 +00:00
|
|
|
trade = Trade.get_trades([Trade.is_open.is_(True), Trade.pair.is_(pair)]).first()
|
2018-10-09 17:25:43 +00:00
|
|
|
if trade:
|
|
|
|
raise RPCException(f'position for {pair} already open - id: {trade.id}')
|
|
|
|
|
|
|
|
# gen stake amount
|
2019-12-27 22:44:51 +00:00
|
|
|
stakeamount = self._freqtrade.get_trade_stake_amount(pair)
|
2018-10-09 17:25:43 +00:00
|
|
|
|
|
|
|
# execute buy
|
|
|
|
if self._freqtrade.execute_buy(pair, stakeamount, price):
|
2019-10-29 14:09:01 +00:00
|
|
|
trade = Trade.get_trades([Trade.is_open.is_(True), Trade.pair.is_(pair)]).first()
|
2018-10-09 17:25:43 +00:00
|
|
|
return trade
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
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()
|
|
|
|
# Round and convert to %
|
|
|
|
[x.update({'profit': round(x['profit'] * 100, 2)}) for x in pair_rates]
|
|
|
|
return pair_rates
|
2018-03-02 15:22:00 +00:00
|
|
|
|
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),
|
2019-04-06 18:01:29 +00:00
|
|
|
'max': float(self._freqtrade.config['max_open_trades']),
|
|
|
|
'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
|
|
|
|
|
|
|
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
|
|
|
|
2019-04-26 07:55:11 +00:00
|
|
|
def _rpc_blacklist(self, add: List[str] = None) -> Dict:
|
2019-03-24 15:08:48 +00:00
|
|
|
""" Returns the currently active blacklist"""
|
2019-03-24 15:28:14 +00:00
|
|
|
if add:
|
2019-03-25 18:40:21 +00:00
|
|
|
stake_currency = self._freqtrade.config.get('stake_currency')
|
|
|
|
for pair in add:
|
|
|
|
if (pair.endswith(stake_currency)
|
|
|
|
and pair not in self._freqtrade.pairlists.blacklist):
|
|
|
|
self._freqtrade.pairlists.blacklist.append(pair)
|
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,
|
2019-03-24 15:08:48 +00:00
|
|
|
}
|
|
|
|
return res
|
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:
|
|
|
|
raise RPCException(f'Edge is not enabled.')
|
2019-04-03 12:14:47 +00:00
|
|
|
return self._freqtrade.edge.accepted_pairs()
|