Change some types

Fix types of new model object
This commit is contained in:
Matthias 2021-02-20 20:22:00 +01:00
parent 03eb23a4ce
commit 53a57f2c81
8 changed files with 17 additions and 17 deletions

View File

@ -10,7 +10,7 @@ import pandas as pd
from freqtrade.constants import LAST_BT_RESULT_FN from freqtrade.constants import LAST_BT_RESULT_FN
from freqtrade.misc import json_load from freqtrade.misc import json_load
from freqtrade.persistence import Trade, init_db from freqtrade.persistence import LocalTrade, Trade, init_db
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -224,7 +224,7 @@ def evaluate_result_multi(results: pd.DataFrame, timeframe: str,
return df_final[df_final['open_trades'] > max_open_trades] return df_final[df_final['open_trades'] > max_open_trades]
def trade_list_to_dataframe(trades: List[Trade]) -> pd.DataFrame: def trade_list_to_dataframe(trades: List[LocalTrade]) -> pd.DataFrame:
""" """
Convert list of Trade objects to pandas Dataframe Convert list of Trade objects to pandas Dataframe
:param trades: List of trade objects :param trades: List of trade objects

View File

@ -211,7 +211,7 @@ class Backtesting:
data[pair] = [x for x in df_analyzed.itertuples(index=False, name=None)] data[pair] = [x for x in df_analyzed.itertuples(index=False, name=None)]
return data return data
def _get_close_rate(self, sell_row: Tuple, trade: Trade, sell: SellCheckTuple, def _get_close_rate(self, sell_row: Tuple, trade: LocalTrade, sell: SellCheckTuple,
trade_dur: int) -> float: trade_dur: int) -> float:
""" """
Get close rate for backtesting result Get close rate for backtesting result
@ -251,10 +251,10 @@ class Backtesting:
else: else:
return sell_row[OPEN_IDX] return sell_row[OPEN_IDX]
def _get_sell_trade_entry(self, trade: Trade, sell_row: Tuple) -> Optional[Trade]: def _get_sell_trade_entry(self, trade: LocalTrade, sell_row: Tuple) -> Optional[LocalTrade]:
sell = self.strategy.should_sell(trade, sell_row[OPEN_IDX], sell_row[DATE_IDX], sell = self.strategy.should_sell(trade, sell_row[OPEN_IDX], # type: ignore
sell_row[BUY_IDX], sell_row[SELL_IDX], sell_row[DATE_IDX], sell_row[BUY_IDX], sell_row[SELL_IDX],
low=sell_row[LOW_IDX], high=sell_row[HIGH_IDX]) low=sell_row[LOW_IDX], high=sell_row[HIGH_IDX])
if sell.sell_flag: if sell.sell_flag:
@ -331,7 +331,7 @@ class Backtesting:
:param enable_protections: Should protections be enabled? :param enable_protections: Should protections be enabled?
:return: DataFrame with trades (results of backtesting) :return: DataFrame with trades (results of backtesting)
""" """
trades: List[Trade] = [] trades: List[LocalTrade] = []
self.prepare_backtest(enable_protections) self.prepare_backtest(enable_protections)
# Use dict of lists with data for performance # Use dict of lists with data for performance
@ -342,7 +342,7 @@ class Backtesting:
indexes: Dict = {} indexes: Dict = {}
tmp = start_date + timedelta(minutes=self.timeframe_min) tmp = start_date + timedelta(minutes=self.timeframe_min)
open_trades: Dict[str, List[Trade]] = defaultdict(list) open_trades: Dict[str, List[LocalTrade]] = defaultdict(list)
open_trade_count = 0 open_trade_count = 0
# Loop timerange and get candle for each pair at that point in time # Loop timerange and get candle for each pair at that point in time

View File

@ -44,7 +44,8 @@ class CooldownPeriod(IProtection):
trades = Trade.get_trades_proxy(pair=pair, is_open=False, close_date=look_back_until) trades = Trade.get_trades_proxy(pair=pair, is_open=False, close_date=look_back_until)
if trades: if trades:
# Get latest trade # Get latest trade
trade = sorted(trades, key=lambda t: t.close_date)[-1] # Ignore type error as we know we only get closed trades.
trade = sorted(trades, key=lambda t: t.close_date)[-1] # type: ignore
self.log_once(f"Cooldown for {pair} for {self.stop_duration_str}.", logger.info) self.log_once(f"Cooldown for {pair} for {self.stop_duration_str}.", logger.info)
until = self.calculate_lock_end([trade], self._stop_duration) until = self.calculate_lock_end([trade], self._stop_duration)

View File

@ -7,7 +7,7 @@ from typing import Any, Dict, List, Optional, Tuple
from freqtrade.exchange import timeframe_to_minutes from freqtrade.exchange import timeframe_to_minutes
from freqtrade.misc import plural from freqtrade.misc import plural
from freqtrade.mixins import LoggingMixin from freqtrade.mixins import LoggingMixin
from freqtrade.persistence import Trade from freqtrade.persistence import LocalTrade
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -93,11 +93,11 @@ class IProtection(LoggingMixin, ABC):
""" """
@staticmethod @staticmethod
def calculate_lock_end(trades: List[Trade], stop_minutes: int) -> datetime: def calculate_lock_end(trades: List[LocalTrade], stop_minutes: int) -> datetime:
""" """
Get lock end time Get lock end time
""" """
max_date: datetime = max([trade.close_date for trade in trades]) max_date: datetime = max([trade.close_date for trade in trades if trade.close_date])
# comming from Database, tzinfo is not set. # comming from Database, tzinfo is not set.
if max_date.tzinfo is None: if max_date.tzinfo is None:
max_date = max_date.replace(tzinfo=timezone.utc) max_date = max_date.replace(tzinfo=timezone.utc)

View File

@ -53,7 +53,7 @@ class LowProfitPairs(IProtection):
# Not enough trades in the relevant period # Not enough trades in the relevant period
return False, None, None return False, None, None
profit = sum(trade.close_profit for trade in trades) profit = sum(trade.close_profit for trade in trades if trade.close_profit)
if profit < self._required_profit: if profit < self._required_profit:
self.log_once( self.log_once(
f"Trading for {pair} stopped due to {profit:.2f} < {self._required_profit} " f"Trading for {pair} stopped due to {profit:.2f} < {self._required_profit} "

View File

@ -56,7 +56,7 @@ class StoplossGuard(IProtection):
trades = [trade for trade in trades1 if (str(trade.sell_reason) in ( trades = [trade for trade in trades1 if (str(trade.sell_reason) in (
SellType.TRAILING_STOP_LOSS.value, SellType.STOP_LOSS.value, SellType.TRAILING_STOP_LOSS.value, SellType.STOP_LOSS.value,
SellType.STOPLOSS_ON_EXCHANGE.value) SellType.STOPLOSS_ON_EXCHANGE.value)
and trade.close_profit < 0)] and trade.close_profit and trade.close_profit < 0)]
if len(trades) < self._trade_limit: if len(trades) < self._trade_limit:
return False, None, None return False, None, None

View File

@ -19,7 +19,7 @@ from freqtrade.data.converter import ohlcv_to_dataframe
from freqtrade.edge import Edge, PairInfo from freqtrade.edge import Edge, PairInfo
from freqtrade.exchange import Exchange from freqtrade.exchange import Exchange
from freqtrade.freqtradebot import FreqtradeBot from freqtrade.freqtradebot import FreqtradeBot
from freqtrade.persistence import Trade, init_db from freqtrade.persistence import LocalTrade, Trade, init_db
from freqtrade.resolvers import ExchangeResolver from freqtrade.resolvers import ExchangeResolver
from freqtrade.worker import Worker from freqtrade.worker import Worker
from tests.conftest_trades import (mock_trade_1, mock_trade_2, mock_trade_3, mock_trade_4, from tests.conftest_trades import (mock_trade_1, mock_trade_2, mock_trade_3, mock_trade_4,
@ -191,7 +191,7 @@ def create_mock_trades(fee, use_db: bool = True):
if use_db: if use_db:
Trade.session.add(trade) Trade.session.add(trade)
else: else:
Trade.trades.append(trade) LocalTrade.trades.append(trade)
# Simulate dry_run entries # Simulate dry_run entries
trade = mock_trade_1(fee) trade = mock_trade_1(fee)

View File

@ -1,6 +1,5 @@
# pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, C0330, unused-argument # pragma pylint: disable=missing-docstring, W0212, line-too-long, C0103, C0330, unused-argument
import logging import logging
from unittest.mock import MagicMock
import pytest import pytest