Merge pull request #1069 from freqtrade/feat/movefiatconverttorpc
Feat/movefiatconverttorpc
This commit is contained in:
@@ -6,13 +6,14 @@ from abc import abstractmethod
|
||||
from datetime import timedelta, datetime, date
|
||||
from decimal import Decimal
|
||||
from enum import Enum
|
||||
from typing import Dict, Any, List
|
||||
from typing import Dict, Any, List, Optional
|
||||
|
||||
import arrow
|
||||
import sqlalchemy as sql
|
||||
from numpy import mean, nan_to_num
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.fiat_convert import CryptoToFiatConverter
|
||||
from freqtrade.misc import shorten_date
|
||||
from freqtrade.persistence import Trade
|
||||
from freqtrade.state import State
|
||||
@@ -49,6 +50,9 @@ class RPC(object):
|
||||
"""
|
||||
RPC class can be used to have extra feature, like bot data, and access to DB data
|
||||
"""
|
||||
# Bind _fiat_converter if needed in each RPC handler
|
||||
_fiat_converter: Optional[CryptoToFiatConverter] = None
|
||||
|
||||
def __init__(self, freqtrade) -> None:
|
||||
"""
|
||||
Initializes all enabled rpc modules
|
||||
@@ -142,7 +146,6 @@ class RPC(object):
|
||||
if not (isinstance(timescale, int) and timescale > 0):
|
||||
raise RPCException('timescale must be an integer greater than 0')
|
||||
|
||||
fiat = self._freqtrade.fiat_converter
|
||||
for day in range(0, timescale):
|
||||
profitday = today - timedelta(days=day)
|
||||
trades = Trade.query \
|
||||
@@ -165,11 +168,11 @@ class RPC(object):
|
||||
symbol=stake_currency
|
||||
),
|
||||
'{value:.3f} {symbol}'.format(
|
||||
value=fiat.convert_amount(
|
||||
value=self._fiat_converter.convert_amount(
|
||||
value['amount'],
|
||||
stake_currency,
|
||||
fiat_display_currency
|
||||
),
|
||||
) if self._fiat_converter else 0,
|
||||
symbol=fiat_display_currency
|
||||
),
|
||||
'{value} trade{s}'.format(
|
||||
@@ -224,24 +227,23 @@ class RPC(object):
|
||||
|
||||
bp_pair, bp_rate = best_pair
|
||||
|
||||
# FIX: we want to keep fiatconverter in a state/environment,
|
||||
# doing this will utilize its caching functionallity, instead we reinitialize it here
|
||||
fiat = self._freqtrade.fiat_converter
|
||||
# Prepare data to display
|
||||
profit_closed_coin_sum = round(sum(profit_closed_coin), 8)
|
||||
profit_closed_percent = round(nan_to_num(mean(profit_closed_percent)) * 100, 2)
|
||||
profit_closed_fiat = fiat.convert_amount(
|
||||
profit_closed_fiat = self._fiat_converter.convert_amount(
|
||||
profit_closed_coin_sum,
|
||||
stake_currency,
|
||||
fiat_display_currency
|
||||
)
|
||||
) if self._fiat_converter else 0
|
||||
|
||||
profit_all_coin_sum = round(sum(profit_all_coin), 8)
|
||||
profit_all_percent = round(nan_to_num(mean(profit_all_percent)) * 100, 2)
|
||||
profit_all_fiat = fiat.convert_amount(
|
||||
profit_all_fiat = self._fiat_converter.convert_amount(
|
||||
profit_all_coin_sum,
|
||||
stake_currency,
|
||||
fiat_display_currency
|
||||
)
|
||||
) if self._fiat_converter else 0
|
||||
|
||||
num = float(len(durations) or 1)
|
||||
return {
|
||||
'profit_closed_coin': profit_closed_coin_sum,
|
||||
@@ -285,9 +287,9 @@ class RPC(object):
|
||||
if total == 0.0:
|
||||
raise RPCException('all balances are zero')
|
||||
|
||||
fiat = self._freqtrade.fiat_converter
|
||||
symbol = fiat_display_currency
|
||||
value = fiat.convert_amount(total, 'BTC', symbol)
|
||||
value = self._fiat_converter.convert_amount(total, 'BTC',
|
||||
symbol) if self._fiat_converter else 0
|
||||
return {
|
||||
'currencies': output,
|
||||
'total': total,
|
||||
|
@@ -12,6 +12,7 @@ from telegram.error import NetworkError, TelegramError
|
||||
from telegram.ext import CommandHandler, Updater
|
||||
|
||||
from freqtrade.__init__ import __version__
|
||||
from freqtrade.fiat_convert import CryptoToFiatConverter
|
||||
from freqtrade.rpc import RPC, RPCException, RPCMessageType
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -66,6 +67,8 @@ class Telegram(RPC):
|
||||
self._updater: Updater = None
|
||||
self._config = freqtrade.config
|
||||
self._init()
|
||||
if self._config.get('fiat_display_currency', None):
|
||||
self._fiat_converter = CryptoToFiatConverter()
|
||||
|
||||
def _init(self) -> None:
|
||||
"""
|
||||
@@ -114,11 +117,19 @@ class Telegram(RPC):
|
||||
""" Send a message to telegram channel """
|
||||
|
||||
if msg['type'] == RPCMessageType.BUY_NOTIFICATION:
|
||||
if self._fiat_converter:
|
||||
msg['stake_amount_fiat'] = self._fiat_converter.convert_amount(
|
||||
msg['stake_amount'], msg['stake_currency'], msg['fiat_currency'])
|
||||
else:
|
||||
msg['stake_amount_fiat'] = 0
|
||||
|
||||
message = "*{exchange}:* Buying [{pair}]({market_url})\n" \
|
||||
"with limit `{limit:.8f}\n" \
|
||||
"({stake_amount:.6f} {stake_currency}," \
|
||||
"{stake_amount_fiat:.3f} {fiat_currency})`" \
|
||||
.format(**msg)
|
||||
"({stake_amount:.6f} {stake_currency}".format(**msg)
|
||||
|
||||
if msg.get('fiat_currency', None):
|
||||
message += ",{stake_amount_fiat:.3f} {fiat_currency}".format(**msg)
|
||||
message += ")`"
|
||||
|
||||
elif msg['type'] == RPCMessageType.SELL_NOTIFICATION:
|
||||
msg['amount'] = round(msg['amount'], 8)
|
||||
@@ -133,8 +144,10 @@ class Telegram(RPC):
|
||||
|
||||
# Check if all sell properties are available.
|
||||
# This might not be the case if the message origin is triggered by /forcesell
|
||||
if all(prop in msg for prop in ['gain', 'profit_fiat',
|
||||
'fiat_currency', 'stake_currency']):
|
||||
if (all(prop in msg for prop in ['gain', 'fiat_currency', 'stake_currency'])
|
||||
and self._fiat_converter):
|
||||
msg['profit_fiat'] = self._fiat_converter.convert_amount(
|
||||
msg['profit_amount'], msg['stake_currency'], msg['fiat_currency'])
|
||||
message += '` ({gain}: {profit_amount:.8f} {stake_currency}`' \
|
||||
'` / {profit_fiat:.3f} {fiat_currency})`'.format(**msg)
|
||||
|
||||
@@ -213,7 +226,7 @@ class Telegram(RPC):
|
||||
:return: None
|
||||
"""
|
||||
stake_cur = self._config['stake_currency']
|
||||
fiat_disp_cur = self._config['fiat_display_currency']
|
||||
fiat_disp_cur = self._config.get('fiat_display_currency', '')
|
||||
try:
|
||||
timescale = int(update.message.text.replace('/daily', '').strip())
|
||||
except (TypeError, ValueError):
|
||||
@@ -246,7 +259,7 @@ class Telegram(RPC):
|
||||
:return: None
|
||||
"""
|
||||
stake_cur = self._config['stake_currency']
|
||||
fiat_disp_cur = self._config['fiat_display_currency']
|
||||
fiat_disp_cur = self._config.get('fiat_display_currency', '')
|
||||
|
||||
try:
|
||||
stats = self._rpc_trade_statistics(
|
||||
@@ -285,7 +298,7 @@ class Telegram(RPC):
|
||||
def _balance(self, bot: Bot, update: Update) -> None:
|
||||
""" Handler for /balance """
|
||||
try:
|
||||
result = self._rpc_balance(self._config['fiat_display_currency'])
|
||||
result = self._rpc_balance(self._config.get('fiat_display_currency', ''))
|
||||
output = ''
|
||||
for currency in result['currencies']:
|
||||
output += "*{currency}:*\n" \
|
||||
|
Reference in New Issue
Block a user