Update SellCheckTuple to new naming

This commit is contained in:
Matthias
2022-03-25 06:46:29 +01:00
parent 62e8c7b5b7
commit 8d111d357a
7 changed files with 87 additions and 87 deletions

View File

@@ -27,7 +27,7 @@ from freqtrade.plugins.pairlistmanager import PairListManager
from freqtrade.plugins.protectionmanager import ProtectionManager
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
from freqtrade.rpc import RPCManager
from freqtrade.strategy.interface import IStrategy, SellCheckTuple
from freqtrade.strategy.interface import IStrategy, ExitCheckTuple
from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper
from freqtrade.wallets import Wallets
@@ -976,8 +976,8 @@ class FreqtradeBot(LoggingMixin):
trade.stoploss_order_id = None
logger.error(f'Unable to place a stoploss order on exchange. {e}')
logger.warning('Exiting the trade forcefully')
self.execute_trade_exit(trade, trade.stop_loss, exit_check=SellCheckTuple(
sell_type=SellType.EMERGENCY_SELL))
self.execute_trade_exit(trade, trade.stop_loss, exit_check=ExitCheckTuple(
exit_type=SellType.EMERGENCY_SELL))
except ExchangeError:
trade.stoploss_order_id = None
@@ -1101,7 +1101,7 @@ class FreqtradeBot(LoggingMixin):
"""
Check and execute trade exit
"""
should_exit: SellCheckTuple = self.strategy.should_exit(
should_exit: ExitCheckTuple = self.strategy.should_exit(
trade,
exit_rate,
datetime.now(timezone.utc),
@@ -1110,8 +1110,8 @@ class FreqtradeBot(LoggingMixin):
force_stoploss=self.edge.stoploss(trade.pair) if self.edge else 0
)
if should_exit.sell_flag:
logger.info(f'Exit for {trade.pair} detected. Reason: {should_exit.sell_type}'
if should_exit.exit_flag:
logger.info(f'Exit for {trade.pair} detected. Reason: {should_exit.exit_type}'
f'Tag: {exit_tag if exit_tag is not None else "None"}')
self.execute_trade_exit(trade, exit_rate, should_exit, exit_tag=exit_tag)
return True
@@ -1158,7 +1158,7 @@ class FreqtradeBot(LoggingMixin):
try:
self.execute_trade_exit(
trade, order.get('price'),
exit_check=SellCheckTuple(sell_type=SellType.EMERGENCY_SELL))
exit_check=ExitCheckTuple(exit_type=SellType.EMERGENCY_SELL))
except DependencyException as exception:
logger.warning(
f'Unable to emergency sell trade {trade.pair}: {exception}')
@@ -1333,7 +1333,7 @@ class FreqtradeBot(LoggingMixin):
self,
trade: Trade,
limit: float,
exit_check: SellCheckTuple,
exit_check: ExitCheckTuple,
*,
exit_tag: Optional[str] = None,
ordertype: Optional[str] = None,
@@ -1352,7 +1352,7 @@ class FreqtradeBot(LoggingMixin):
open_date=trade.open_date,
)
exit_type = 'exit'
if exit_check.sell_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
if exit_check.exit_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
exit_type = 'stoploss'
# if stoploss is on exchange and we are on dry_run mode,
@@ -1376,7 +1376,7 @@ class FreqtradeBot(LoggingMixin):
trade = self.cancel_stoploss_on_exchange(trade)
order_type = ordertype or self.strategy.order_types[exit_type]
if exit_check.sell_type == SellType.EMERGENCY_SELL:
if exit_check.exit_type == SellType.EMERGENCY_SELL:
# Emergency sells (default to market!)
order_type = self.strategy.order_types.get("emergencyexit", "market")
@@ -1385,8 +1385,8 @@ class FreqtradeBot(LoggingMixin):
if not strategy_safe_wrapper(self.strategy.confirm_trade_exit, default_retval=True)(
pair=trade.pair, trade=trade, order_type=order_type, amount=amount, rate=limit,
time_in_force=time_in_force, exit_reason=exit_check.sell_reason,
sell_reason=exit_check.sell_reason, # sellreason -> compatibility
time_in_force=time_in_force, exit_reason=exit_check.exit_reason,
sell_reason=exit_check.exit_reason, # sellreason -> compatibility
current_time=datetime.now(timezone.utc)):
logger.info(f"User requested abortion of exiting {trade.pair}")
return False
@@ -1415,7 +1415,7 @@ class FreqtradeBot(LoggingMixin):
trade.open_order_id = order['id']
trade.sell_order_status = ''
trade.close_rate_requested = limit
trade.sell_reason = exit_tag or exit_check.sell_reason
trade.sell_reason = exit_tag or exit_check.exit_reason
# Lock pair for one candle to prevent immediate re-trading
self.strategy.lock_pair(trade.pair, datetime.now(timezone.utc),

View File

@@ -31,7 +31,7 @@ from freqtrade.persistence import LocalTrade, Order, PairLocks, Trade
from freqtrade.plugins.pairlistmanager import PairListManager
from freqtrade.plugins.protectionmanager import ProtectionManager
from freqtrade.resolvers import ExchangeResolver, StrategyResolver
from freqtrade.strategy.interface import IStrategy, SellCheckTuple
from freqtrade.strategy.interface import IStrategy, ExitCheckTuple
from freqtrade.strategy.strategy_wrapper import strategy_safe_wrapper
from freqtrade.wallets import Wallets
@@ -352,20 +352,20 @@ class Backtesting:
data[pair] = df_analyzed[headers].values.tolist()
return data
def _get_close_rate(self, sell_row: Tuple, trade: LocalTrade, sell: SellCheckTuple,
def _get_close_rate(self, sell_row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
trade_dur: int) -> float:
"""
Get close rate for backtesting result
"""
# Special handling if high or low hit STOP_LOSS or ROI
if sell.sell_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
if sell.exit_type in (SellType.STOP_LOSS, SellType.TRAILING_STOP_LOSS):
return self._get_close_rate_for_stoploss(sell_row, trade, sell, trade_dur)
elif sell.sell_type == (SellType.ROI):
elif sell.exit_type == (SellType.ROI):
return self._get_close_rate_for_roi(sell_row, trade, sell, trade_dur)
else:
return sell_row[OPEN_IDX]
def _get_close_rate_for_stoploss(self, sell_row: Tuple, trade: LocalTrade, sell: SellCheckTuple,
def _get_close_rate_for_stoploss(self, sell_row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
trade_dur: int) -> float:
# our stoploss was already lower than candle high,
# possibly due to a cancelled trade exit.
@@ -383,7 +383,7 @@ class Backtesting:
# Special case: trailing triggers within same candle as trade opened. Assume most
# pessimistic price movement, which is moving just enough to arm stoploss and
# immediately going down to stop price.
if sell.sell_type == SellType.TRAILING_STOP_LOSS and trade_dur == 0:
if sell.exit_type == SellType.TRAILING_STOP_LOSS and trade_dur == 0:
if (
not self.strategy.use_custom_stoploss and self.strategy.trailing_stop
and self.strategy.trailing_only_offset_is_reached
@@ -413,7 +413,7 @@ class Backtesting:
# Set close_rate to stoploss
return trade.stop_loss
def _get_close_rate_for_roi(self, sell_row: Tuple, trade: LocalTrade, sell: SellCheckTuple,
def _get_close_rate_for_roi(self, sell_row: Tuple, trade: LocalTrade, sell: ExitCheckTuple,
trade_dur: int) -> float:
is_short = trade.is_short or False
leverage = trade.leverage or 1.0
@@ -521,7 +521,7 @@ class Backtesting:
low=sell_row[LOW_IDX], high=sell_row[HIGH_IDX]
)
if sell.sell_flag:
if sell.exit_flag:
trade.close_date = sell_candle_time
trade_dur = int((trade.close_date_utc - trade.open_date_utc).total_seconds() // 60)
@@ -532,7 +532,7 @@ class Backtesting:
# call the custom exit price,with default value as previous closerate
current_profit = trade.calc_profit_ratio(closerate)
order_type = self.strategy.order_types['exit']
if sell.sell_type in (SellType.SELL_SIGNAL, SellType.CUSTOM_SELL):
if sell.exit_type in (SellType.SELL_SIGNAL, SellType.CUSTOM_SELL):
# Custom exit pricing only for sell-signals
if order_type == 'limit':
closerate = strategy_safe_wrapper(self.strategy.custom_exit_price,
@@ -553,12 +553,12 @@ class Backtesting:
pair=trade.pair, trade=trade, order_type='limit', amount=trade.amount,
rate=closerate,
time_in_force=time_in_force,
sell_reason=sell.sell_reason, # deprecated
exit_reason=sell.sell_reason,
sell_reason=sell.exit_reason, # deprecated
exit_reason=sell.exit_reason,
current_time=sell_candle_time):
return None
trade.sell_reason = sell.sell_reason
trade.sell_reason = sell.exit_reason
# Checks and adds an exit tag, after checking that the length of the
# sell_row has the length for an exit tag column

View File

@@ -27,7 +27,7 @@ from freqtrade.persistence import PairLocks, Trade
from freqtrade.persistence.models import PairLock
from freqtrade.plugins.pairlist.pairlist_helpers import expand_pairlist
from freqtrade.rpc.fiat_convert import CryptoToFiatConverter
from freqtrade.strategy.interface import SellCheckTuple
from freqtrade.strategy.interface import ExitCheckTuple
from freqtrade.wallets import PositionWallet, Wallet
@@ -707,7 +707,7 @@ class RPC:
# Get current rate and execute sell
current_rate = self._freqtrade.exchange.get_rate(
trade.pair, refresh=False, side=trade.exit_side)
exit_check = SellCheckTuple(sell_type=SellType.FORCE_SELL)
exit_check = ExitCheckTuple(exit_type=SellType.FORCE_SELL)
order_type = ordertype or self._freqtrade.strategy.order_types.get(
"forceexit", self._freqtrade.strategy.order_types["exit"])

View File

@@ -32,20 +32,20 @@ logger = logging.getLogger(__name__)
CUSTOM_EXIT_MAX_LENGTH = 64
class SellCheckTuple:
class ExitCheckTuple:
"""
NamedTuple for Sell type + reason
NamedTuple for Exit type + reason
"""
sell_type: SellType
sell_reason: str = ''
exit_type: SellType
exit_reason: str = ''
def __init__(self, sell_type: SellType, sell_reason: str = ''):
self.sell_type = sell_type
self.sell_reason = sell_reason or sell_type.value
def __init__(self, exit_type: SellType, exit_reason: str = ''):
self.exit_type = exit_type
self.exit_reason = exit_reason or exit_type.value
@property
def sell_flag(self):
return self.sell_type != SellType.NONE
def exit_flag(self):
return self.exit_type != SellType.NONE
class IStrategy(ABC, HyperStrategyMixin):
@@ -848,7 +848,7 @@ class IStrategy(ABC, HyperStrategyMixin):
def should_exit(self, trade: Trade, rate: float, current_time: datetime, *,
enter: bool, exit_: bool,
low: float = None, high: float = None,
force_stoploss: float = 0) -> SellCheckTuple:
force_stoploss: float = 0) -> ExitCheckTuple:
"""
This function evaluates if one of the conditions required to trigger an exit order
has been reached, which can either be a stop-loss, ROI or exit-signal.
@@ -908,29 +908,29 @@ class IStrategy(ABC, HyperStrategyMixin):
logger.debug(f"{trade.pair} - Sell signal received. "
f"sell_type=SellType.{sell_signal.name}" +
(f", custom_reason={custom_reason}" if custom_reason else ""))
return SellCheckTuple(sell_type=sell_signal, sell_reason=custom_reason)
return ExitCheckTuple(exit_type=sell_signal, exit_reason=custom_reason)
# Sequence:
# Exit-signal
# ROI (if not stoploss)
# Stoploss
if roi_reached and stoplossflag.sell_type != SellType.STOP_LOSS:
if roi_reached and stoplossflag.exit_type != SellType.STOP_LOSS:
logger.debug(f"{trade.pair} - Required profit reached. sell_type=SellType.ROI")
return SellCheckTuple(sell_type=SellType.ROI)
return ExitCheckTuple(exit_type=SellType.ROI)
if stoplossflag.sell_flag:
if stoplossflag.exit_flag:
logger.debug(f"{trade.pair} - Stoploss hit. sell_type={stoplossflag.sell_type}")
logger.debug(f"{trade.pair} - Stoploss hit. sell_type={stoplossflag.exit_type}")
return stoplossflag
# This one is noisy, commented out...
# logger.debug(f"{trade.pair} - No exit signal.")
return SellCheckTuple(sell_type=SellType.NONE)
return ExitCheckTuple(exit_type=SellType.NONE)
def stop_loss_reached(self, current_rate: float, trade: Trade,
current_time: datetime, current_profit: float,
force_stoploss: float, low: float = None,
high: float = None) -> SellCheckTuple:
high: float = None) -> ExitCheckTuple:
"""
Based on current profit of the trade and configured (trailing) stoploss,
decides to exit or not
@@ -1008,9 +1008,9 @@ class IStrategy(ABC, HyperStrategyMixin):
logger.debug(f"{trade.pair} - Trailing stop saved "
f"{new_stoploss:.6f}")
return SellCheckTuple(sell_type=sell_type)
return ExitCheckTuple(exit_type=sell_type)
return SellCheckTuple(sell_type=SellType.NONE)
return ExitCheckTuple(exit_type=SellType.NONE)
def min_roi_reached_entry(self, trade_dur: int) -> Tuple[Optional[int], Optional[float]]:
"""