stable/freqtrade/wallets.py

99 lines
2.6 KiB
Python
Raw Normal View History

# pragma pylint: disable=W0603
""" Wallet """
2019-02-28 22:26:29 +00:00
import logging
from typing import Dict, NamedTuple, Any
from freqtrade.exchange import Exchange
from freqtrade.persistence import Trade
logger = logging.getLogger(__name__)
# wallet data structure
class Wallet(NamedTuple):
2018-11-21 22:35:44 +00:00
currency: str
free: float = 0
used: float = 0
total: float = 0
2019-09-12 01:39:52 +00:00
class Wallets:
2019-02-28 22:26:29 +00:00
def __init__(self, config: dict, exchange: Exchange) -> None:
self._config = config
self._exchange = exchange
self._wallets: Dict[str, Wallet] = {}
self.start_cap = config['dry_run_wallet']
2019-02-28 22:26:29 +00:00
2018-11-24 15:37:28 +00:00
self.update()
def get_free(self, currency) -> float:
2019-02-28 22:26:29 +00:00
balance = self._wallets.get(currency)
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-28 14:36:32 +00:00
def get_used(self, currency) -> 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
def get_total(self, currency) -> 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
def _update_dry(self) -> None:
""" Update from database in dry-run mode"""
closed_trades = Trade.get_trades(Trade.is_open.is_(False)).all()
2019-12-15 09:26:56 +00:00
open_trades = Trade.get_trades(Trade.is_open.is_(True)).all()
tot_profit = sum([trade.calc_profit() for trade in closed_trades])
2019-12-15 09:26:56 +00:00
tot_in_trades = sum([trade.stake_amount for trade in open_trades])
2019-12-15 09:26:56 +00:00
current_stake = self.start_cap + tot_profit - tot_in_trades
self._wallets[self._config['stake_currency']] = Wallet(
self._config['stake_currency'],
current_stake,
0,
current_stake
)
for trade in open_trades:
curr = trade.pair.split('/')[0]
self._wallets[curr] = Wallet(
curr,
trade.amount,
0,
trade.amount
)
def _update_live(self) -> None:
2019-02-28 22:26:29 +00:00
balances = self._exchange.get_balances()
for currency in balances:
2019-02-28 22:26:29 +00:00
self._wallets[currency] = Wallet(
currency,
balances[currency].get('free', None),
balances[currency].get('used', None),
balances[currency].get('total', None)
)
def update(self) -> None:
if self._config['dry_run']:
self._update_dry()
else:
self._update_live()
2019-02-28 22:26:29 +00:00
logger.info('Wallets synced.')
def get_all_balances(self) -> Dict[str, Any]:
return self._wallets