2018-11-17 20:16:32 +00:00
|
|
|
# pragma pylint: disable=W0603
|
|
|
|
""" Wallet """
|
2019-02-28 22:26:29 +00:00
|
|
|
|
2018-11-17 20:16:32 +00:00
|
|
|
import logging
|
2020-09-22 17:37:31 +00:00
|
|
|
from copy import deepcopy
|
2020-01-15 05:42:53 +00:00
|
|
|
from typing import Any, Dict, NamedTuple
|
|
|
|
|
|
|
|
import arrow
|
|
|
|
|
2021-02-03 19:00:33 +00:00
|
|
|
from freqtrade.constants import UNLIMITED_STAKE_AMOUNT
|
2021-06-08 19:20:35 +00:00
|
|
|
from freqtrade.enums import RunMode
|
2021-02-03 19:00:33 +00:00
|
|
|
from freqtrade.exceptions import DependencyException
|
2018-11-17 20:16:32 +00:00
|
|
|
from freqtrade.exchange import Exchange
|
2021-03-13 09:16:32 +00:00
|
|
|
from freqtrade.persistence import LocalTrade, Trade
|
2018-11-17 20:16:32 +00:00
|
|
|
|
2020-09-28 17:39:41 +00:00
|
|
|
|
2018-11-17 20:16:32 +00:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
|
|
2018-12-29 08:01:58 +00:00
|
|
|
# wallet data structure
|
2018-11-21 18:47:51 +00:00
|
|
|
class Wallet(NamedTuple):
|
2018-11-21 22:35:44 +00:00
|
|
|
currency: str
|
2018-11-21 18:47:51 +00:00
|
|
|
free: float = 0
|
|
|
|
used: float = 0
|
|
|
|
total: float = 0
|
|
|
|
|
|
|
|
|
2019-09-12 01:39:52 +00:00
|
|
|
class Wallets:
|
2018-11-17 20:16:32 +00:00
|
|
|
|
2021-02-27 09:31:21 +00:00
|
|
|
def __init__(self, config: dict, exchange: Exchange, log: bool = True) -> None:
|
2019-02-28 22:26:29 +00:00
|
|
|
self._config = config
|
2021-02-27 09:31:21 +00:00
|
|
|
self._log = log
|
2019-02-28 22:26:29 +00:00
|
|
|
self._exchange = exchange
|
|
|
|
self._wallets: Dict[str, Wallet] = {}
|
2019-12-15 08:48:35 +00:00
|
|
|
self.start_cap = config['dry_run_wallet']
|
2020-01-15 05:42:53 +00:00
|
|
|
self._last_wallet_refresh = 0
|
2021-02-27 09:31:21 +00:00
|
|
|
self.update()
|
2018-11-24 15:37:28 +00:00
|
|
|
|
2020-02-02 04:00:40 +00:00
|
|
|
def get_free(self, currency: str) -> float:
|
2019-02-28 22:26:29 +00:00
|
|
|
balance = self._wallets.get(currency)
|
2018-11-26 01:18:29 +00:00
|
|
|
if balance and balance.free:
|
|
|
|
return balance.free
|
2018-11-23 09:17:10 +00:00
|
|
|
else:
|
2018-11-24 15:37:28 +00:00
|
|
|
return 0
|
2018-11-17 20:16:32 +00:00
|
|
|
|
2020-02-02 04:00:40 +00:00
|
|
|
def get_used(self, currency: str) -> float:
|
2019-02-28 22:26:29 +00:00
|
|
|
balance = self._wallets.get(currency)
|
2018-11-28 14:36:32 +00:00
|
|
|
if balance and balance.used:
|
|
|
|
return balance.used
|
|
|
|
else:
|
|
|
|
return 0
|
|
|
|
|
2020-02-02 04:00:40 +00:00
|
|
|
def get_total(self, currency: str) -> float:
|
2019-02-28 22:26:29 +00:00
|
|
|
balance = self._wallets.get(currency)
|
2018-11-28 14:36:32 +00:00
|
|
|
if balance and balance.total:
|
|
|
|
return balance.total
|
|
|
|
else:
|
|
|
|
return 0
|
|
|
|
|
2019-12-15 08:48:35 +00:00
|
|
|
def _update_dry(self) -> None:
|
2019-12-15 10:03:40 +00:00
|
|
|
"""
|
|
|
|
Update from database in dry-run mode
|
|
|
|
- Apply apply profits of closed trades on top of stake amount
|
|
|
|
- Subtract currently tied up stake_amount in open trades
|
|
|
|
- update balances for currencies currently in trades
|
|
|
|
"""
|
2019-12-24 05:27:11 +00:00
|
|
|
# Recreate _wallets to reset closed trade balances
|
|
|
|
_wallets = {}
|
2021-01-28 05:37:42 +00:00
|
|
|
open_trades = Trade.get_trades_proxy(is_open=True)
|
2021-03-13 09:16:32 +00:00
|
|
|
# If not backtesting...
|
|
|
|
# TODO: potentially remove the ._log workaround to determine backtest mode.
|
|
|
|
if self._log:
|
|
|
|
closed_trades = Trade.get_trades_proxy(is_open=False)
|
2021-03-16 18:24:03 +00:00
|
|
|
tot_profit = sum(
|
|
|
|
[trade.close_profit_abs for trade in closed_trades if trade.close_profit_abs])
|
2021-03-13 09:16:32 +00:00
|
|
|
else:
|
|
|
|
tot_profit = LocalTrade.total_profit
|
2019-12-15 09:26:56 +00:00
|
|
|
tot_in_trades = sum([trade.stake_amount for trade in open_trades])
|
2019-12-15 08:48:35 +00:00
|
|
|
|
2019-12-15 09:26:56 +00:00
|
|
|
current_stake = self.start_cap + tot_profit - tot_in_trades
|
2019-12-24 05:27:11 +00:00
|
|
|
_wallets[self._config['stake_currency']] = Wallet(
|
2019-12-15 08:48:35 +00:00
|
|
|
self._config['stake_currency'],
|
|
|
|
current_stake,
|
|
|
|
0,
|
|
|
|
current_stake
|
|
|
|
)
|
|
|
|
|
|
|
|
for trade in open_trades:
|
2020-02-25 06:01:31 +00:00
|
|
|
curr = self._exchange.get_pair_base_currency(trade.pair)
|
2019-12-24 05:27:11 +00:00
|
|
|
_wallets[curr] = Wallet(
|
2019-12-15 08:48:35 +00:00
|
|
|
curr,
|
|
|
|
trade.amount,
|
|
|
|
0,
|
|
|
|
trade.amount
|
|
|
|
)
|
2019-12-24 05:27:11 +00:00
|
|
|
self._wallets = _wallets
|
2019-12-15 08:48:35 +00:00
|
|
|
|
|
|
|
def _update_live(self) -> None:
|
2019-02-28 22:26:29 +00:00
|
|
|
balances = self._exchange.get_balances()
|
2018-11-17 20:16:32 +00:00
|
|
|
|
|
|
|
for currency in balances:
|
2021-04-26 12:12:52 +00:00
|
|
|
if isinstance(balances[currency], dict):
|
|
|
|
self._wallets[currency] = Wallet(
|
|
|
|
currency,
|
|
|
|
balances[currency].get('free', None),
|
|
|
|
balances[currency].get('used', None),
|
|
|
|
balances[currency].get('total', None)
|
|
|
|
)
|
2020-09-22 17:37:31 +00:00
|
|
|
# Remove currencies no longer in get_balances output
|
|
|
|
for currency in deepcopy(self._wallets):
|
|
|
|
if currency not in balances:
|
|
|
|
del self._wallets[currency]
|
2018-11-17 20:16:32 +00:00
|
|
|
|
2021-02-10 18:23:11 +00:00
|
|
|
def update(self, require_update: bool = True) -> None:
|
2020-01-15 05:42:53 +00:00
|
|
|
"""
|
|
|
|
Updates wallets from the configured version.
|
|
|
|
By default, updates from the exchange.
|
|
|
|
Update-skipping should only be used for user-invoked /balance calls, since
|
|
|
|
for trading operations, the latest balance is needed.
|
|
|
|
:param require_update: Allow skipping an update if balances were recently refreshed
|
|
|
|
"""
|
2020-10-12 17:58:04 +00:00
|
|
|
if (require_update or (self._last_wallet_refresh + 3600 < arrow.utcnow().int_timestamp)):
|
2021-01-28 05:37:42 +00:00
|
|
|
if (not self._config['dry_run'] or self._config.get('runmode') == RunMode.LIVE):
|
2020-01-15 05:42:53 +00:00
|
|
|
self._update_live()
|
2021-01-28 05:37:42 +00:00
|
|
|
else:
|
|
|
|
self._update_dry()
|
2021-02-10 18:23:11 +00:00
|
|
|
if self._log:
|
2021-01-28 05:37:42 +00:00
|
|
|
logger.info('Wallets synced.')
|
2020-10-12 17:58:04 +00:00
|
|
|
self._last_wallet_refresh = arrow.utcnow().int_timestamp
|
2019-11-24 18:41:51 +00:00
|
|
|
|
|
|
|
def get_all_balances(self) -> Dict[str, Any]:
|
|
|
|
return self._wallets
|
2021-02-03 19:00:33 +00:00
|
|
|
|
2021-07-11 09:20:31 +00:00
|
|
|
def get_total_stake_amount(self):
|
|
|
|
"""
|
|
|
|
Return the total currently available balance in stake currency, including tied up stake and
|
|
|
|
respecting tradable_balance_ratio.
|
|
|
|
Calculated as
|
|
|
|
(<open_trade stakes> + free amount) * tradable_balance_ratio
|
|
|
|
"""
|
|
|
|
# Ensure <tradable_balance_ratio>% is used from the overall balance
|
|
|
|
# Otherwise we'd risk lowering stakes with each open trade.
|
|
|
|
# (tied up + current free) * ratio) - tied up
|
|
|
|
val_tied_up = Trade.total_open_trades_stakes()
|
|
|
|
available_amount = ((val_tied_up + self.get_free(self._config['stake_currency'])) *
|
|
|
|
self._config['tradable_balance_ratio'])
|
|
|
|
return available_amount
|
|
|
|
|
|
|
|
def get_available_stake_amount(self) -> float:
|
2021-02-03 19:00:33 +00:00
|
|
|
"""
|
|
|
|
Return the total currently available balance in stake currency,
|
|
|
|
respecting tradable_balance_ratio.
|
|
|
|
Calculated as
|
2021-04-20 13:55:48 +00:00
|
|
|
(<open_trade stakes> + free amount) * tradable_balance_ratio - <open_trade stakes>
|
2021-02-03 19:00:33 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
# Ensure <tradable_balance_ratio>% is used from the overall balance
|
|
|
|
# Otherwise we'd risk lowering stakes with each open trade.
|
|
|
|
# (tied up + current free) * ratio) - tied up
|
2021-07-11 09:20:31 +00:00
|
|
|
return self.get_total_stake_amount() - Trade.total_open_trades_stakes()
|
2021-02-03 19:00:33 +00:00
|
|
|
|
2021-04-21 18:01:10 +00:00
|
|
|
def _calculate_unlimited_stake_amount(self, available_amount: float,
|
2021-04-21 17:27:21 +00:00
|
|
|
val_tied_up: float) -> float:
|
2021-02-03 19:00:33 +00:00
|
|
|
"""
|
|
|
|
Calculate stake amount for "unlimited" stake amount
|
|
|
|
:return: 0 if max number of trades reached, else stake_amount to use.
|
|
|
|
"""
|
2021-04-21 18:01:10 +00:00
|
|
|
if self._config['max_open_trades'] == 0:
|
2021-02-03 19:00:33 +00:00
|
|
|
return 0
|
|
|
|
|
2021-04-21 17:27:21 +00:00
|
|
|
possible_stake = (available_amount + val_tied_up) / self._config['max_open_trades']
|
2021-04-21 15:22:16 +00:00
|
|
|
# Theoretical amount can be above available amount - therefore limit to available amount!
|
2021-04-21 17:27:21 +00:00
|
|
|
return min(possible_stake, available_amount)
|
2021-02-03 19:00:33 +00:00
|
|
|
|
2021-04-21 17:27:21 +00:00
|
|
|
def _check_available_stake_amount(self, stake_amount: float, available_amount: float) -> float:
|
2021-02-03 19:00:33 +00:00
|
|
|
"""
|
|
|
|
Check if stake amount can be fulfilled with the available balance
|
|
|
|
for the stake currency
|
|
|
|
:return: float: Stake amount
|
2021-02-10 18:45:59 +00:00
|
|
|
:raise: DependencyException if balance is lower than stake-amount
|
2021-02-03 19:00:33 +00:00
|
|
|
"""
|
|
|
|
|
|
|
|
if self._config['amend_last_stake_amount']:
|
|
|
|
# Remaining amount needs to be at least stake_amount * last_stake_amount_min_ratio
|
|
|
|
# Otherwise the remaining amount is too low to trade.
|
|
|
|
if available_amount > (stake_amount * self._config['last_stake_amount_min_ratio']):
|
|
|
|
stake_amount = min(stake_amount, available_amount)
|
|
|
|
else:
|
|
|
|
stake_amount = 0
|
|
|
|
|
|
|
|
if available_amount < stake_amount:
|
|
|
|
raise DependencyException(
|
|
|
|
f"Available balance ({available_amount} {self._config['stake_currency']}) is "
|
|
|
|
f"lower than stake amount ({stake_amount} {self._config['stake_currency']})"
|
|
|
|
)
|
|
|
|
|
|
|
|
return stake_amount
|
|
|
|
|
2021-04-21 18:01:10 +00:00
|
|
|
def get_trade_stake_amount(self, pair: str, edge=None) -> float:
|
2021-02-03 19:00:33 +00:00
|
|
|
"""
|
|
|
|
Calculate stake amount for the trade
|
|
|
|
:return: float: Stake amount
|
|
|
|
:raise: DependencyException if the available stake amount is too low
|
|
|
|
"""
|
|
|
|
stake_amount: float
|
|
|
|
# Ensure wallets are uptodate.
|
|
|
|
self.update()
|
2021-04-21 17:27:21 +00:00
|
|
|
val_tied_up = Trade.total_open_trades_stakes()
|
2021-07-11 09:20:31 +00:00
|
|
|
available_amount = self.get_available_stake_amount()
|
2021-02-03 19:00:33 +00:00
|
|
|
|
|
|
|
if edge:
|
|
|
|
stake_amount = edge.stake_amount(
|
|
|
|
pair,
|
|
|
|
self.get_free(self._config['stake_currency']),
|
|
|
|
self.get_total(self._config['stake_currency']),
|
2021-04-21 17:27:21 +00:00
|
|
|
val_tied_up
|
2021-02-03 19:00:33 +00:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
stake_amount = self._config['stake_amount']
|
|
|
|
if stake_amount == UNLIMITED_STAKE_AMOUNT:
|
2021-04-21 17:27:21 +00:00
|
|
|
stake_amount = self._calculate_unlimited_stake_amount(
|
2021-04-21 18:01:10 +00:00
|
|
|
available_amount, val_tied_up)
|
2021-02-03 19:00:33 +00:00
|
|
|
|
2021-04-21 17:27:21 +00:00
|
|
|
return self._check_available_stake_amount(stake_amount, available_amount)
|
2021-07-11 09:20:31 +00:00
|
|
|
|
|
|
|
def _validate_stake_amount(self, pair, stake_amount, min_stake_amount):
|
|
|
|
if not stake_amount:
|
|
|
|
logger.debug(f"Stake amount is {stake_amount}, ignoring possible trade for {pair}.")
|
|
|
|
return 0
|
|
|
|
|
|
|
|
max_stake_amount = self.get_available_stake_amount()
|
2021-07-11 19:01:12 +00:00
|
|
|
|
|
|
|
if min_stake_amount > max_stake_amount:
|
|
|
|
logger.warning("Minimum stake amount > available balance.")
|
|
|
|
return 0
|
2021-07-11 09:20:31 +00:00
|
|
|
if min_stake_amount is not None and stake_amount < min_stake_amount:
|
|
|
|
stake_amount = min_stake_amount
|
|
|
|
logger.info(
|
|
|
|
f"Stake amount for pair {pair} is too small ({stake_amount} < {min_stake_amount}), "
|
|
|
|
f"adjusting to {min_stake_amount}."
|
|
|
|
)
|
|
|
|
if stake_amount > max_stake_amount:
|
|
|
|
stake_amount = max_stake_amount
|
|
|
|
logger.info(
|
|
|
|
f"Stake amount for pair {pair} is too big ({stake_amount} > {max_stake_amount}), "
|
|
|
|
f"adjusting to {max_stake_amount}."
|
|
|
|
)
|
|
|
|
return stake_amount
|