Merge pull request #9522 from freqtrade/bt/improve_futures_speed

Improve funding fee calculation
This commit is contained in:
Matthias
2023-12-12 06:33:57 +01:00
committed by GitHub
3 changed files with 41 additions and 20 deletions

View File

@@ -283,11 +283,13 @@ class Backtesting:
else:
self.detail_data = {}
if self.trading_mode == TradingMode.FUTURES:
self.funding_fee_timeframe: str = self.exchange.get_option('mark_ohlcv_timeframe')
self.funding_fee_timeframe_secs: int = timeframe_to_seconds(self.funding_fee_timeframe)
# Load additional futures data.
funding_rates_dict = history.load_data(
datadir=self.config['datadir'],
pairs=self.pairlists.whitelist,
timeframe=self.exchange.get_option('mark_ohlcv_timeframe'),
timeframe=self.funding_fee_timeframe,
timerange=self.timerange,
startup_candles=0,
fail_without_data=True,
@@ -299,7 +301,7 @@ class Backtesting:
mark_rates_dict = history.load_data(
datadir=self.config['datadir'],
pairs=self.pairlists.whitelist,
timeframe=self.exchange.get_option('mark_ohlcv_timeframe'),
timeframe=self.funding_fee_timeframe,
timerange=self.timerange,
startup_candles=0,
fail_without_data=True,
@@ -604,6 +606,8 @@ class Backtesting:
"""
if order and self._get_order_filled(order.ft_price, row):
order.close_bt_order(current_date, trade)
self._run_funding_fees(trade, current_date, force=True)
if not (order.ft_order_side == trade.exit_side and order.safe_amount == trade.amount):
# trade is still open
trade.set_liquidation_price(self.exchange.get_liquidation_price(
@@ -725,16 +729,7 @@ class Backtesting:
self, trade: LocalTrade, row: Tuple, current_time: datetime
) -> Optional[LocalTrade]:
if self.trading_mode == TradingMode.FUTURES:
trade.set_funding_fees(
self.exchange.calculate_funding_fees(
self.futures_data[trade.pair],
amount=trade.amount,
is_short=trade.is_short,
open_date=trade.date_last_filled_utc,
close_date=current_time
)
)
self._run_funding_fees(trade, current_time)
# Check if we need to adjust our current positions
if self.strategy.position_adjustment_enable:
@@ -753,6 +748,27 @@ class Backtesting:
return t
return None
def _run_funding_fees(self, trade: LocalTrade, current_time: datetime, force: bool = False):
"""
Calculate funding fees if necessary and add them to the trade.
"""
if self.trading_mode == TradingMode.FUTURES:
if (
force
or (current_time.timestamp() % self.funding_fee_timeframe_secs) == 0
):
# Funding fee interval.
trade.set_funding_fees(
self.exchange.calculate_funding_fees(
self.futures_data[trade.pair],
amount=trade.amount,
is_short=trade.is_short,
open_date=trade.date_last_filled_utc,
close_date=current_time
)
)
def get_valid_price_and_stake(
self, pair: str, row: Tuple, propose_rate: float, stake_amount: float,
direction: LongShort, current_time: datetime, entry_tag: Optional[str],