further refactoring of FreqtradeBot.process()

This commit is contained in:
hroff-1902 2019-03-23 00:20:20 +03:00
parent e35daf95c0
commit 158cb307f6
2 changed files with 49 additions and 44 deletions

View File

@ -4,7 +4,6 @@ Freqtrade is the main module of this bot. It contains the class Freqtrade()
import copy import copy
import logging import logging
import time
import traceback import traceback
from datetime import datetime from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple from typing import Any, Dict, List, Optional, Tuple
@ -13,7 +12,7 @@ import arrow
from requests.exceptions import RequestException from requests.exceptions import RequestException
from freqtrade import (DependencyException, OperationalException, from freqtrade import (DependencyException, OperationalException,
TemporaryError, __version__, constants, persistence) __version__, constants, persistence)
from freqtrade.data.converter import order_book_to_dataframe from freqtrade.data.converter import order_book_to_dataframe
from freqtrade.data.dataprovider import DataProvider from freqtrade.data.dataprovider import DataProvider
from freqtrade.edge import Edge from freqtrade.edge import Edge
@ -99,55 +98,43 @@ class FreqtradeBot(object):
:return: True if one or more trades has been created or closed, False otherwise :return: True if one or more trades has been created or closed, False otherwise
""" """
state_changed = False state_changed = False
try:
# Check whether markets have to be reloaded
self.exchange._reload_markets()
# Refresh whitelist # Check whether markets have to be reloaded
self.pairlists.refresh_pairlist() self.exchange._reload_markets()
self.active_pair_whitelist = self.pairlists.whitelist
# Calculating Edge positioning # Refresh whitelist
if self.edge: self.pairlists.refresh_pairlist()
self.edge.calculate() self.active_pair_whitelist = self.pairlists.whitelist
self.active_pair_whitelist = self.edge.adjust(self.active_pair_whitelist)
# Query trades from persistence layer # Calculating Edge positioning
trades = Trade.get_open_trades() if self.edge:
self.edge.calculate()
self.active_pair_whitelist = self.edge.adjust(self.active_pair_whitelist)
# Extend active-pair whitelist with pairs from open trades # Query trades from persistence layer
# It ensures that tickers are downloaded for open trades trades = Trade.get_open_trades()
self._extend_whitelist_with_trades(self.active_pair_whitelist, trades)
# Refreshing candles # Extend active-pair whitelist with pairs from open trades
self.dataprovider.refresh(self._create_pair_whitelist(self.active_pair_whitelist), # It ensures that tickers are downloaded for open trades
self.strategy.informative_pairs()) self._extend_whitelist_with_trades(self.active_pair_whitelist, trades)
# First process current opened trades # Refreshing candles
for trade in trades: self.dataprovider.refresh(self._create_pair_whitelist(self.active_pair_whitelist),
state_changed |= self.process_maybe_execute_sell(trade) self.strategy.informative_pairs())
# Then looking for buy opportunities # First process current opened trades
if len(trades) < self.config['max_open_trades']: for trade in trades:
state_changed = self.process_maybe_execute_buy() state_changed |= self.process_maybe_execute_sell(trade)
if 'unfilledtimeout' in self.config: # Then looking for buy opportunities
# Check and handle any timed out open orders if len(trades) < self.config['max_open_trades']:
self.check_handle_timedout() state_changed = self.process_maybe_execute_buy()
Trade.session.flush()
if 'unfilledtimeout' in self.config:
# Check and handle any timed out open orders
self.check_handle_timedout()
Trade.session.flush()
except TemporaryError as error:
logger.warning(f"Error: {error}, retrying in {constants.RETRY_TIMEOUT} seconds...")
time.sleep(constants.RETRY_TIMEOUT)
except OperationalException:
tb = traceback.format_exc()
hint = 'Issue `/start` if you think it is safe to restart.'
self.rpc.send_msg({
'type': RPCMessageType.STATUS_NOTIFICATION,
'status': f'OperationalException:\n```\n{tb}```{hint}'
})
logger.exception('OperationalException. Stopping trader ...')
self.state = State.STOPPED
return state_changed return state_changed
def _extend_whitelist_with_trades(self, whitelist: List[str], trades: List[Any]): def _extend_whitelist_with_trades(self, whitelist: List[str], trades: List[Any]):

View File

@ -6,11 +6,13 @@ Read the documentation to know what cli arguments you need.
import logging import logging
import sys import sys
import time import time
import traceback
from argparse import Namespace from argparse import Namespace
from typing import Any, Callable, List from typing import Any, Callable, List
import sdnotify import sdnotify
from freqtrade import (constants, OperationalException, __version__) from freqtrade import (constants, OperationalException, TemporaryError,
__version__)
from freqtrade.arguments import Arguments from freqtrade.arguments import Arguments
from freqtrade.configuration import Configuration, set_loggers from freqtrade.configuration import Configuration, set_loggers
from freqtrade.state import State from freqtrade.state import State
@ -173,7 +175,23 @@ class Worker(object):
return result return result
def _process(self) -> bool: def _process(self) -> bool:
return self.freqtrade.process() state_changed = False
try:
state_changed = self.freqtrade.process()
except TemporaryError as error:
logger.warning(f"Error: {error}, retrying in {constants.RETRY_TIMEOUT} seconds...")
time.sleep(constants.RETRY_TIMEOUT)
except OperationalException:
tb = traceback.format_exc()
hint = 'Issue `/start` if you think it is safe to restart.'
self.freqtrade.rpc.send_msg({
'type': RPCMessageType.STATUS_NOTIFICATION,
'status': f'OperationalException:\n```\n{tb}```{hint}'
})
logger.exception('OperationalException. Stopping trader ...')
self.state = State.STOPPED
return state_changed
def _reconfigure(self): def _reconfigure(self):
""" """