refactor: conversation rate retrieval to exchange class

for better reusability across the bot.
This commit is contained in:
Matthias
2024-12-08 15:44:46 +01:00
parent 0276e65f39
commit 2ff0abc6e7
2 changed files with 36 additions and 20 deletions

View File

@@ -1855,7 +1855,36 @@ class Exchange:
except ccxt.BaseError as e:
raise OperationalException(e) from e
# Pricing info
def get_conversion_rate(self, coin: str, currency: str) -> float:
"""
Quick and cached way to get conversion rate one currency to the other.
Can then be used as "rate * amount" to convert between currencies.
:param coin: Coin to convert
:param currency: Currency to convert to
:returns: Conversion rate from coin to currency
:raises: ExchangeErrors
"""
if coin == currency:
return 1.0
tickers = self.get_tickers(cached=True)
pair = self.get_valid_pair_combination(coin, currency)
ticker: Ticker | None = tickers.get(pair, None)
if not ticker:
tickers_other: Tickers = self.get_tickers(
cached=True,
market_type=(
TradingMode.SPOT
if self.trading_mode != TradingMode.SPOT
else TradingMode.FUTURES
),
)
ticker = tickers_other.get(pair, None)
if ticker:
rate: float | None = ticker.get("last", None)
if rate and pair.startswith(currency) and not pair.endswith(currency):
rate = 1.0 / rate
return rate
return None
@retrier
def fetch_ticker(self, pair: str) -> Ticker:

View File

@@ -687,25 +687,12 @@ class RPC:
est_bot_stake = amount
else:
try:
tickers: Tickers = self._freqtrade.exchange.get_tickers(cached=True)
pair = self._freqtrade.exchange.get_valid_pair_combination(coin, stake_currency)
ticker: Ticker | None = tickers.get(pair, None)
if not ticker:
tickers_spot: Tickers = self._freqtrade.exchange.get_tickers(
cached=True,
market_type=TradingMode.SPOT
if self._config.get("trading_mode", TradingMode.SPOT) != TradingMode.SPOT
else TradingMode.FUTURES,
)
ticker = tickers_spot.get(pair, None)
if ticker:
rate: float | None = ticker.get("last", None)
if rate:
if pair.startswith(stake_currency) and not pair.endswith(stake_currency):
rate = 1.0 / rate
est_stake = rate * balance.total
est_bot_stake = rate * amount
rate: float | None = self._freqtrade.exchange.get_conversion_rate(
coin, stake_currency
)
if rate:
est_stake = rate * balance.total
est_bot_stake = rate * amount
return est_stake, est_bot_stake
except (ExchangeError, PricingError) as e: