Merge branch 'feat/short' into funding-fee
This commit is contained in:
@@ -31,6 +31,7 @@ BT_DATA_COLUMNS = ['pair', 'stake_amount', 'amount', 'open_date', 'close_date',
|
||||
'profit_ratio', 'profit_abs', 'sell_reason',
|
||||
'initial_stop_loss_abs', 'initial_stop_loss_ratio', 'stop_loss_abs',
|
||||
'stop_loss_ratio', 'min_rate', 'max_rate', 'is_open', 'buy_tag']
|
||||
# TODO-lev: usage of the above might need compatibility code (buy_tag, is_short?, ...?)
|
||||
|
||||
|
||||
def get_latest_optimize_filename(directory: Union[Path, str], variant: str) -> str:
|
||||
|
@@ -159,7 +159,8 @@ class Edge:
|
||||
logger.info(f'Measuring data from {min_date.strftime(DATETIME_PRINT_FORMAT)} '
|
||||
f'up to {max_date.strftime(DATETIME_PRINT_FORMAT)} '
|
||||
f'({(max_date - min_date).days} days)..')
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'high', 'low']
|
||||
# TODO-lev: Should edge support shorts? needs to be investigated further...
|
||||
headers = ['date', 'open', 'high', 'low', 'close', 'enter_long', 'exit_long']
|
||||
|
||||
trades: list = []
|
||||
for pair, pair_data in preprocessed.items():
|
||||
@@ -167,8 +168,13 @@ class Edge:
|
||||
pair_data = pair_data.sort_values(by=['date'])
|
||||
pair_data = pair_data.reset_index(drop=True)
|
||||
|
||||
df_analyzed = self.strategy.advise_sell(
|
||||
self.strategy.advise_buy(pair_data, {'pair': pair}), {'pair': pair})[headers].copy()
|
||||
df_analyzed = self.strategy.advise_exit(
|
||||
dataframe=self.strategy.advise_entry(
|
||||
dataframe=pair_data,
|
||||
metadata={'pair': pair}
|
||||
),
|
||||
metadata={'pair': pair}
|
||||
)[headers].copy()
|
||||
|
||||
trades += self._find_trades_for_stoploss_range(df_analyzed, pair, self._stoploss_range)
|
||||
|
||||
@@ -382,8 +388,8 @@ class Edge:
|
||||
return final
|
||||
|
||||
def _find_trades_for_stoploss_range(self, df, pair, stoploss_range):
|
||||
buy_column = df['buy'].values
|
||||
sell_column = df['sell'].values
|
||||
buy_column = df['enter_long'].values
|
||||
sell_column = df['exit_long'].values
|
||||
date_column = df['date'].values
|
||||
ohlc_columns = df[['open', 'high', 'low', 'close']].values
|
||||
|
||||
|
@@ -4,6 +4,6 @@ from freqtrade.enums.collateral import Collateral
|
||||
from freqtrade.enums.rpcmessagetype import RPCMessageType
|
||||
from freqtrade.enums.runmode import NON_UTIL_MODES, OPTIMIZE_MODES, TRADING_MODES, RunMode
|
||||
from freqtrade.enums.selltype import SellType
|
||||
from freqtrade.enums.signaltype import SignalTagType, SignalType
|
||||
from freqtrade.enums.signaltype import SignalDirection, SignalTagType, SignalType
|
||||
from freqtrade.enums.state import State
|
||||
from freqtrade.enums.tradingmode import TradingMode
|
||||
|
@@ -5,12 +5,19 @@ class SignalType(Enum):
|
||||
"""
|
||||
Enum to distinguish between enter and exit signals
|
||||
"""
|
||||
BUY = "buy"
|
||||
SELL = "sell"
|
||||
ENTER_LONG = "enter_long"
|
||||
EXIT_LONG = "exit_long"
|
||||
ENTER_SHORT = "enter_short"
|
||||
EXIT_SHORT = "exit_short"
|
||||
|
||||
|
||||
class SignalTagType(Enum):
|
||||
"""
|
||||
Enum for signal columns
|
||||
"""
|
||||
BUY_TAG = "buy_tag"
|
||||
ENTER_TAG = "enter_tag"
|
||||
|
||||
|
||||
class SignalDirection(Enum):
|
||||
LONG = 'long'
|
||||
SHORT = 'short'
|
||||
|
@@ -445,24 +445,25 @@ class FreqtradeBot(LoggingMixin):
|
||||
return False
|
||||
|
||||
# running get_signal on historical data fetched
|
||||
(buy, sell, buy_tag) = self.strategy.get_signal(
|
||||
pair,
|
||||
self.strategy.timeframe,
|
||||
analyzed_df
|
||||
(signal, enter_tag) = self.strategy.get_entry_signal(
|
||||
pair, self.strategy.timeframe, analyzed_df
|
||||
)
|
||||
|
||||
if buy and not sell:
|
||||
if signal:
|
||||
stake_amount = self.wallets.get_trade_stake_amount(pair, self.edge)
|
||||
|
||||
bid_check_dom = self.config.get('bid_strategy', {}).get('check_depth_of_market', {})
|
||||
if ((bid_check_dom.get('enabled', False)) and
|
||||
(bid_check_dom.get('bids_to_ask_delta', 0) > 0)):
|
||||
# TODO-lev: Does the below need to be adjusted for shorts?
|
||||
if self._check_depth_of_market_buy(pair, bid_check_dom):
|
||||
return self.execute_entry(pair, stake_amount, buy_tag=buy_tag)
|
||||
# TODO-lev: pass in "enter" as side.
|
||||
|
||||
return self.execute_entry(pair, stake_amount, enter_tag=enter_tag)
|
||||
else:
|
||||
return False
|
||||
|
||||
return self.execute_entry(pair, stake_amount, buy_tag=buy_tag)
|
||||
return self.execute_entry(pair, stake_amount, enter_tag=enter_tag)
|
||||
else:
|
||||
return False
|
||||
|
||||
@@ -491,7 +492,7 @@ class FreqtradeBot(LoggingMixin):
|
||||
return False
|
||||
|
||||
def execute_entry(self, pair: str, stake_amount: float, price: Optional[float] = None,
|
||||
forcebuy: bool = False, buy_tag: Optional[str] = None) -> bool:
|
||||
forcebuy: bool = False, enter_tag: Optional[str] = None) -> bool:
|
||||
"""
|
||||
Executes a limit buy for the given pair
|
||||
:param pair: pair for which we want to create a LIMIT_BUY
|
||||
@@ -524,7 +525,9 @@ class FreqtradeBot(LoggingMixin):
|
||||
default_retval=stake_amount)(
|
||||
pair=pair, current_time=datetime.now(timezone.utc),
|
||||
current_rate=enter_limit_requested, proposed_stake=stake_amount,
|
||||
min_stake=min_stake_amount, max_stake=max_stake_amount)
|
||||
min_stake=min_stake_amount, max_stake=max_stake_amount, side='long')
|
||||
# TODO-lev: Add non-hardcoded "side" parameter
|
||||
|
||||
stake_amount = self.wallets._validate_stake_amount(pair, stake_amount, min_stake_amount)
|
||||
|
||||
if not stake_amount:
|
||||
@@ -541,9 +544,12 @@ class FreqtradeBot(LoggingMixin):
|
||||
order_type = self.strategy.order_types.get('forcebuy', order_type)
|
||||
# TODO-lev: Will this work for shorting?
|
||||
|
||||
# TODO-lev: Add non-hardcoded "side" parameter
|
||||
if not strategy_safe_wrapper(self.strategy.confirm_trade_entry, default_retval=True)(
|
||||
pair=pair, order_type=order_type, amount=amount, rate=enter_limit_requested,
|
||||
time_in_force=time_in_force, current_time=datetime.now(timezone.utc)):
|
||||
time_in_force=time_in_force, current_time=datetime.now(timezone.utc),
|
||||
side='long'
|
||||
):
|
||||
logger.info(f"User requested abortion of buying {pair}")
|
||||
return False
|
||||
amount = self.exchange.amount_to_precision(pair, amount)
|
||||
@@ -608,7 +614,8 @@ class FreqtradeBot(LoggingMixin):
|
||||
exchange=self.exchange.id,
|
||||
open_order_id=order_id,
|
||||
strategy=self.strategy.get_strategy_name(),
|
||||
buy_tag=buy_tag,
|
||||
# TODO-lev: compatibility layer for buy_tag (!)
|
||||
buy_tag=enter_tag,
|
||||
timeframe=timeframe_to_minutes(self.config['timeframe']),
|
||||
trading_mode=self.trading_mode,
|
||||
funding_fees=funding_fees
|
||||
@@ -734,22 +741,23 @@ class FreqtradeBot(LoggingMixin):
|
||||
|
||||
logger.debug('Handling %s ...', trade)
|
||||
|
||||
(buy, sell) = (False, False)
|
||||
(enter, exit_) = (False, False)
|
||||
|
||||
# TODO-lev: change to use_exit_signal, ignore_roi_if_enter_signal
|
||||
if (self.config.get('use_sell_signal', True) or
|
||||
self.config.get('ignore_roi_if_buy_signal', False)):
|
||||
analyzed_df, _ = self.dataprovider.get_analyzed_dataframe(trade.pair,
|
||||
self.strategy.timeframe)
|
||||
|
||||
(buy, sell, _) = self.strategy.get_signal(
|
||||
(enter, exit_) = self.strategy.get_exit_signal(
|
||||
trade.pair,
|
||||
self.strategy.timeframe,
|
||||
analyzed_df
|
||||
analyzed_df, is_short=trade.is_short
|
||||
)
|
||||
|
||||
logger.debug('checking sell')
|
||||
# TODO-lev: side should depend on trade side.
|
||||
exit_rate = self.exchange.get_rate(trade.pair, refresh=True, side="sell")
|
||||
if self._check_and_execute_exit(trade, exit_rate, buy, sell):
|
||||
if self._check_and_execute_exit(trade, exit_rate, enter, exit_):
|
||||
return True
|
||||
|
||||
logger.debug('Found no sell signal for %s.', trade)
|
||||
@@ -895,18 +903,18 @@ class FreqtradeBot(LoggingMixin):
|
||||
f"for pair {trade.pair}.")
|
||||
|
||||
def _check_and_execute_exit(self, trade: Trade, exit_rate: float,
|
||||
buy: bool, sell: bool) -> bool:
|
||||
enter: bool, exit_: bool) -> bool:
|
||||
"""
|
||||
Check and execute exit
|
||||
Check and execute trade exit
|
||||
"""
|
||||
should_sell = self.strategy.should_sell(
|
||||
trade, exit_rate, datetime.now(timezone.utc), buy, sell,
|
||||
should_exit: SellCheckTuple = self.strategy.should_exit(
|
||||
trade, exit_rate, datetime.now(timezone.utc), enter=enter, exit_=exit_,
|
||||
force_stoploss=self.edge.stoploss(trade.pair) if self.edge else 0
|
||||
)
|
||||
|
||||
if should_sell.sell_flag:
|
||||
logger.info(f'Executing Sell for {trade.pair}. Reason: {should_sell.sell_type}')
|
||||
self.execute_trade_exit(trade, exit_rate, should_sell)
|
||||
if should_exit.sell_flag:
|
||||
logger.info(f'Exit for {trade.pair} detected. Reason: {should_exit.sell_type}')
|
||||
self.execute_trade_exit(trade, exit_rate, should_exit)
|
||||
return True
|
||||
return False
|
||||
|
||||
|
@@ -37,13 +37,15 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
# Indexes for backtest tuples
|
||||
DATE_IDX = 0
|
||||
BUY_IDX = 1
|
||||
OPEN_IDX = 2
|
||||
CLOSE_IDX = 3
|
||||
SELL_IDX = 4
|
||||
LOW_IDX = 5
|
||||
HIGH_IDX = 6
|
||||
BUY_TAG_IDX = 7
|
||||
OPEN_IDX = 1
|
||||
HIGH_IDX = 2
|
||||
LOW_IDX = 3
|
||||
CLOSE_IDX = 4
|
||||
LONG_IDX = 5
|
||||
ELONG_IDX = 6 # Exit long
|
||||
SHORT_IDX = 7
|
||||
ESHORT_IDX = 8 # Exit short
|
||||
ENTER_TAG_IDX = 9
|
||||
|
||||
|
||||
class Backtesting:
|
||||
@@ -64,8 +66,8 @@ class Backtesting:
|
||||
config['dry_run'] = True
|
||||
self.strategylist: List[IStrategy] = []
|
||||
self.all_results: Dict[str, Dict] = {}
|
||||
|
||||
self.exchange = ExchangeResolver.load_exchange(self.config['exchange']['name'], self.config)
|
||||
self._exchange_name = self.config['exchange']['name']
|
||||
self.exchange = ExchangeResolver.load_exchange(self._exchange_name, self.config)
|
||||
self.dataprovider = DataProvider(self.config, None)
|
||||
|
||||
if self.config.get('strategy_list', None):
|
||||
@@ -136,6 +138,10 @@ class Backtesting:
|
||||
self.config['startup_candle_count'] = self.required_startup
|
||||
self.exchange.validate_required_startup_candles(self.required_startup, self.timeframe)
|
||||
|
||||
# TODO-lev: This should come from the configuration setting or better a
|
||||
# TODO-lev: combination of config/strategy "use_shorts"(?) and "can_short" from the exchange
|
||||
self._can_short = False
|
||||
|
||||
self.progress = BTProgress()
|
||||
self.abort = False
|
||||
|
||||
@@ -245,7 +251,8 @@ class Backtesting:
|
||||
"""
|
||||
# Every change to this headers list must evaluate further usages of the resulting tuple
|
||||
# and eventually change the constants for indexes at the top
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'low', 'high', 'buy_tag']
|
||||
headers = ['date', 'open', 'high', 'low', 'close', 'enter_long', 'exit_long',
|
||||
'enter_short', 'exit_short', 'enter_tag']
|
||||
data: Dict = {}
|
||||
self.progress.init_step(BacktestState.CONVERT, len(processed))
|
||||
|
||||
@@ -253,13 +260,13 @@ class Backtesting:
|
||||
for pair, pair_data in processed.items():
|
||||
self.check_abort()
|
||||
self.progress.increment()
|
||||
if not pair_data.empty:
|
||||
pair_data.loc[:, 'buy'] = 0 # cleanup if buy_signal is exist
|
||||
pair_data.loc[:, 'sell'] = 0 # cleanup if sell_signal is exist
|
||||
pair_data.loc[:, 'buy_tag'] = None # cleanup if buy_tag is exist
|
||||
|
||||
df_analyzed = self.strategy.advise_sell(
|
||||
self.strategy.advise_buy(pair_data, {'pair': pair}),
|
||||
if not pair_data.empty:
|
||||
# Cleanup from prior runs
|
||||
pair_data.drop(headers[5:] + ['buy', 'sell'], axis=1, errors='ignore')
|
||||
|
||||
df_analyzed = self.strategy.advise_exit(
|
||||
self.strategy.advise_entry(pair_data, {'pair': pair}),
|
||||
{'pair': pair}
|
||||
).copy()
|
||||
# Trim startup period from analyzed dataframe
|
||||
@@ -267,9 +274,11 @@ class Backtesting:
|
||||
startup_candles=self.required_startup)
|
||||
# To avoid using data from future, we use buy/sell signals shifted
|
||||
# from the previous candle
|
||||
df_analyzed.loc[:, 'buy'] = df_analyzed.loc[:, 'buy'].shift(1)
|
||||
df_analyzed.loc[:, 'sell'] = df_analyzed.loc[:, 'sell'].shift(1)
|
||||
df_analyzed.loc[:, 'buy_tag'] = df_analyzed.loc[:, 'buy_tag'].shift(1)
|
||||
for col in headers[5:]:
|
||||
if col in df_analyzed.columns:
|
||||
df_analyzed.loc[:, col] = df_analyzed.loc[:, col].shift(1)
|
||||
else:
|
||||
df_analyzed.loc[:, col] = 0 if col != 'enter_tag' else None
|
||||
|
||||
# Update dataprovider cache
|
||||
self.dataprovider._set_cached_df(pair, self.timeframe, df_analyzed)
|
||||
@@ -350,10 +359,13 @@ class Backtesting:
|
||||
def _get_sell_trade_entry_for_candle(self, trade: LocalTrade,
|
||||
sell_row: Tuple) -> Optional[LocalTrade]:
|
||||
sell_candle_time = sell_row[DATE_IDX].to_pydatetime()
|
||||
sell = self.strategy.should_sell(trade, sell_row[OPEN_IDX], # type: ignore
|
||||
sell_candle_time, sell_row[BUY_IDX],
|
||||
sell_row[SELL_IDX],
|
||||
low=sell_row[LOW_IDX], high=sell_row[HIGH_IDX])
|
||||
enter = sell_row[SHORT_IDX] if trade.is_short else sell_row[LONG_IDX]
|
||||
exit_ = sell_row[ESHORT_IDX] if trade.is_short else sell_row[ELONG_IDX]
|
||||
sell = self.strategy.should_exit(
|
||||
trade, sell_row[OPEN_IDX], sell_candle_time, # type: ignore
|
||||
enter=enter, exit_=exit_,
|
||||
low=sell_row[LOW_IDX], high=sell_row[HIGH_IDX]
|
||||
)
|
||||
|
||||
if sell.sell_flag:
|
||||
trade.close_date = sell_candle_time
|
||||
@@ -389,9 +401,12 @@ class Backtesting:
|
||||
if len(detail_data) == 0:
|
||||
# Fall back to "regular" data if no detail data was found for this candle
|
||||
return self._get_sell_trade_entry_for_candle(trade, sell_row)
|
||||
detail_data['buy'] = sell_row[BUY_IDX]
|
||||
detail_data['sell'] = sell_row[SELL_IDX]
|
||||
headers = ['date', 'buy', 'open', 'close', 'sell', 'low', 'high']
|
||||
detail_data['enter_long'] = sell_row[LONG_IDX]
|
||||
detail_data['exit_long'] = sell_row[ELONG_IDX]
|
||||
detail_data['enter_short'] = sell_row[SHORT_IDX]
|
||||
detail_data['exit_short'] = sell_row[ESHORT_IDX]
|
||||
headers = ['date', 'open', 'high', 'low', 'close', 'enter_long', 'exit_long',
|
||||
'enter_short', 'exit_short']
|
||||
for det_row in detail_data[headers].values.tolist():
|
||||
res = self._get_sell_trade_entry_for_candle(trade, det_row)
|
||||
if res:
|
||||
@@ -402,7 +417,7 @@ class Backtesting:
|
||||
else:
|
||||
return self._get_sell_trade_entry_for_candle(trade, sell_row)
|
||||
|
||||
def _enter_trade(self, pair: str, row: List) -> Optional[LocalTrade]:
|
||||
def _enter_trade(self, pair: str, row: List, direction: str) -> Optional[LocalTrade]:
|
||||
try:
|
||||
stake_amount = self.wallets.get_trade_stake_amount(pair, None)
|
||||
except DependencyException:
|
||||
@@ -414,7 +429,8 @@ class Backtesting:
|
||||
stake_amount = strategy_safe_wrapper(self.strategy.custom_stake_amount,
|
||||
default_retval=stake_amount)(
|
||||
pair=pair, current_time=row[DATE_IDX].to_pydatetime(), current_rate=row[OPEN_IDX],
|
||||
proposed_stake=stake_amount, min_stake=min_stake_amount, max_stake=max_stake_amount)
|
||||
proposed_stake=stake_amount, min_stake=min_stake_amount, max_stake=max_stake_amount,
|
||||
side=direction)
|
||||
stake_amount = self.wallets._validate_stake_amount(pair, stake_amount, min_stake_amount)
|
||||
|
||||
if not stake_amount:
|
||||
@@ -425,12 +441,13 @@ class Backtesting:
|
||||
# Confirm trade entry:
|
||||
if not strategy_safe_wrapper(self.strategy.confirm_trade_entry, default_retval=True)(
|
||||
pair=pair, order_type=order_type, amount=stake_amount, rate=row[OPEN_IDX],
|
||||
time_in_force=time_in_force, current_time=row[DATE_IDX].to_pydatetime()):
|
||||
time_in_force=time_in_force, current_time=row[DATE_IDX].to_pydatetime(),
|
||||
side=direction):
|
||||
return None
|
||||
|
||||
if stake_amount and (not min_stake_amount or stake_amount > min_stake_amount):
|
||||
# Enter trade
|
||||
has_buy_tag = len(row) >= BUY_TAG_IDX + 1
|
||||
has_enter_tag = len(row) >= ENTER_TAG_IDX + 1
|
||||
trade = LocalTrade(
|
||||
pair=pair,
|
||||
open_rate=row[OPEN_IDX],
|
||||
@@ -440,8 +457,9 @@ class Backtesting:
|
||||
fee_open=self.fee,
|
||||
fee_close=self.fee,
|
||||
is_open=True,
|
||||
buy_tag=row[BUY_TAG_IDX] if has_buy_tag else None,
|
||||
exchange='backtesting',
|
||||
buy_tag=row[ENTER_TAG_IDX] if has_enter_tag else None,
|
||||
exchange=self._exchange_name,
|
||||
is_short=(direction == 'short'),
|
||||
)
|
||||
return trade
|
||||
return None
|
||||
@@ -475,6 +493,20 @@ class Backtesting:
|
||||
self.rejected_trades += 1
|
||||
return False
|
||||
|
||||
def check_for_trade_entry(self, row) -> Optional[str]:
|
||||
enter_long = row[LONG_IDX] == 1
|
||||
exit_long = row[ELONG_IDX] == 1
|
||||
enter_short = self._can_short and row[SHORT_IDX] == 1
|
||||
exit_short = self._can_short and row[ESHORT_IDX] == 1
|
||||
|
||||
if enter_long == 1 and not any([exit_long, enter_short]):
|
||||
# Long
|
||||
return 'long'
|
||||
if enter_short == 1 and not any([exit_short, enter_long]):
|
||||
# Short
|
||||
return 'short'
|
||||
return None
|
||||
|
||||
def backtest(self, processed: Dict,
|
||||
start_date: datetime, end_date: datetime,
|
||||
max_open_trades: int = 0, position_stacking: bool = False,
|
||||
@@ -537,15 +569,15 @@ class Backtesting:
|
||||
# without positionstacking, we can only have one open trade per pair.
|
||||
# max_open_trades must be respected
|
||||
# don't open on the last row
|
||||
trade_dir = self.check_for_trade_entry(row)
|
||||
if (
|
||||
(position_stacking or len(open_trades[pair]) == 0)
|
||||
and self.trade_slot_available(max_open_trades, open_trade_count_start)
|
||||
and tmp != end_date
|
||||
and row[BUY_IDX] == 1
|
||||
and row[SELL_IDX] != 1
|
||||
and trade_dir is not None
|
||||
and not PairLocks.is_pair_locked(pair, row[DATE_IDX])
|
||||
):
|
||||
trade = self._enter_trade(pair, row)
|
||||
trade = self._enter_trade(pair, row, trade_dir)
|
||||
if trade:
|
||||
# TODO: hacky workaround to avoid opening > max_open_trades
|
||||
# This emulates previous behaviour - not sure if this is correct
|
||||
|
@@ -386,8 +386,9 @@ def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFra
|
||||
)
|
||||
fig.add_trace(candles, 1, 1)
|
||||
|
||||
if 'buy' in data.columns:
|
||||
df_buy = data[data['buy'] == 1]
|
||||
# TODO-lev: Needs short equivalent
|
||||
if 'enter_long' in data.columns:
|
||||
df_buy = data[data['enter_long'] == 1]
|
||||
if len(df_buy) > 0:
|
||||
buys = go.Scatter(
|
||||
x=df_buy.date,
|
||||
@@ -405,8 +406,8 @@ def generate_candlestick_graph(pair: str, data: pd.DataFrame, trades: pd.DataFra
|
||||
else:
|
||||
logger.warning("No buy-signals found.")
|
||||
|
||||
if 'sell' in data.columns:
|
||||
df_sell = data[data['sell'] == 1]
|
||||
if 'exit_long' in data.columns:
|
||||
df_sell = data[data['exit_long'] == 1]
|
||||
if len(df_sell) > 0:
|
||||
sells = go.Scatter(
|
||||
x=df_sell.date,
|
||||
|
@@ -13,7 +13,7 @@ from pandas import DataFrame
|
||||
|
||||
from freqtrade.constants import ListPairsWithTimeframes
|
||||
from freqtrade.data.dataprovider import DataProvider
|
||||
from freqtrade.enums import SellType, SignalTagType, SignalType
|
||||
from freqtrade.enums import SellType, SignalDirection, SignalTagType, SignalType
|
||||
from freqtrade.exceptions import OperationalException, StrategyError
|
||||
from freqtrade.exchange import timeframe_to_minutes, timeframe_to_seconds
|
||||
from freqtrade.exchange.exchange import timeframe_to_next_date
|
||||
@@ -187,7 +187,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
|
||||
def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool:
|
||||
"""
|
||||
Check buy enter timeout function callback.
|
||||
Check buy timeout function callback.
|
||||
This method can be used to override the enter-timeout.
|
||||
It is called whenever a limit entry order has been created,
|
||||
and is not yet fully filled.
|
||||
@@ -231,7 +231,8 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
pass
|
||||
|
||||
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
|
||||
time_in_force: str, current_time: datetime, **kwargs) -> bool:
|
||||
time_in_force: str, current_time: datetime,
|
||||
side: str, **kwargs) -> bool:
|
||||
"""
|
||||
Called right before placing a entry order.
|
||||
Timing for this function is critical, so avoid doing heavy computations or
|
||||
@@ -247,6 +248,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
:param rate: Rate that's going to be used when using limit orders
|
||||
:param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
|
||||
:param current_time: datetime object, containing the current datetime
|
||||
:param side: 'long' or 'short' - indicating the direction of the proposed trade
|
||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||
:return bool: When True is returned, then the buy-order is placed on the exchange.
|
||||
False aborts the process
|
||||
@@ -366,10 +368,9 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
|
||||
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
||||
proposed_stake: float, min_stake: float, max_stake: float,
|
||||
**kwargs) -> float:
|
||||
side: str, **kwargs) -> float:
|
||||
"""
|
||||
Customize stake size for each new trade. This method is not called when edge module is
|
||||
enabled.
|
||||
Customize stake size for each new trade.
|
||||
|
||||
:param pair: Pair that's currently analyzed
|
||||
:param current_time: datetime object, containing the current datetime
|
||||
@@ -377,10 +378,28 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
:param proposed_stake: A stake amount proposed by the bot.
|
||||
:param min_stake: Minimal stake size allowed by exchange.
|
||||
:param max_stake: Balance available for trading.
|
||||
:param side: 'long' or 'short' - indicating the direction of the proposed trade
|
||||
:return: A stake size, which is between min_stake and max_stake.
|
||||
"""
|
||||
return proposed_stake
|
||||
|
||||
def leverage(self, pair: str, current_time: datetime, current_rate: float,
|
||||
proposed_leverage: float, max_leverage: float, side: str,
|
||||
**kwargs) -> float:
|
||||
"""
|
||||
Customize leverage for each new trade. This method is not called when edge module is
|
||||
enabled.
|
||||
|
||||
:param pair: Pair that's currently analyzed
|
||||
:param current_time: datetime object, containing the current datetime
|
||||
:param current_rate: Rate, calculated based on pricing settings in ask_strategy.
|
||||
:param proposed_leverage: A leverage proposed by the bot.
|
||||
:param max_leverage: Max leverage allowed on this pair
|
||||
:param side: 'long' or 'short' - indicating the direction of the proposed trade
|
||||
:return: A leverage amount, which is between 1.0 and max_leverage.
|
||||
"""
|
||||
return 1.0
|
||||
|
||||
def informative_pairs(self) -> ListPairsWithTimeframes:
|
||||
"""
|
||||
Define additional, informative pair/interval combinations to be cached from the exchange.
|
||||
@@ -471,8 +490,8 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
"""
|
||||
logger.debug("TA Analysis Launched")
|
||||
dataframe = self.advise_indicators(dataframe, metadata)
|
||||
dataframe = self.advise_buy(dataframe, metadata)
|
||||
dataframe = self.advise_sell(dataframe, metadata)
|
||||
dataframe = self.advise_entry(dataframe, metadata)
|
||||
dataframe = self.advise_exit(dataframe, metadata)
|
||||
return dataframe
|
||||
|
||||
def _analyze_ticker_internal(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
@@ -497,9 +516,11 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
self.dp._set_cached_df(pair, self.timeframe, dataframe)
|
||||
else:
|
||||
logger.debug("Skipping TA Analysis for already analyzed candle")
|
||||
dataframe['buy'] = 0
|
||||
dataframe['sell'] = 0
|
||||
dataframe['buy_tag'] = None
|
||||
dataframe[SignalType.ENTER_LONG.value] = 0
|
||||
dataframe[SignalType.EXIT_LONG.value] = 0
|
||||
dataframe[SignalType.ENTER_SHORT.value] = 0
|
||||
dataframe[SignalType.EXIT_SHORT.value] = 0
|
||||
dataframe[SignalTagType.ENTER_TAG.value] = None
|
||||
|
||||
# Other Defs in strategy that want to be called every loop here
|
||||
# twitter_sell = self.watch_twitter_feed(dataframe, metadata)
|
||||
@@ -558,8 +579,8 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
message = ""
|
||||
if dataframe is None:
|
||||
message = "No dataframe returned (return statement missing?)."
|
||||
elif 'buy' not in dataframe:
|
||||
message = "Buy column not set."
|
||||
elif 'enter_long' not in dataframe:
|
||||
message = "enter_long/buy column not set."
|
||||
elif df_len != len(dataframe):
|
||||
message = message_template.format("length")
|
||||
elif df_close != dataframe["close"].iloc[-1]:
|
||||
@@ -572,12 +593,12 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
else:
|
||||
raise StrategyError(message)
|
||||
|
||||
def get_signal(
|
||||
def get_latest_candle(
|
||||
self,
|
||||
pair: str,
|
||||
timeframe: str,
|
||||
dataframe: DataFrame
|
||||
) -> Tuple[bool, bool, Optional[str]]:
|
||||
dataframe: DataFrame,
|
||||
) -> Tuple[Optional[DataFrame], Optional[arrow.Arrow]]:
|
||||
"""
|
||||
Calculates current signal based based on the entry order or exit order
|
||||
columns of the dataframe.
|
||||
@@ -585,12 +606,11 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
:param pair: pair in format ANT/BTC
|
||||
:param timeframe: timeframe to use
|
||||
:param dataframe: Analyzed dataframe to get signal from.
|
||||
:return: (Buy, Sell)/(Short, Exit_short) A bool-tuple indicating
|
||||
(buy/sell)/(short/exit_short) signal
|
||||
:return: (None, None) or (Dataframe, latest_date) - corresponding to the last candle
|
||||
"""
|
||||
if not isinstance(dataframe, DataFrame) or dataframe.empty:
|
||||
logger.warning(f'Empty candle (OHLCV) data for pair {pair}')
|
||||
return False, False, None
|
||||
return None, None
|
||||
|
||||
latest_date = dataframe['date'].max()
|
||||
latest = dataframe.loc[dataframe['date'] == latest_date].iloc[-1]
|
||||
@@ -605,27 +625,89 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
'Outdated history for pair %s. Last tick is %s minutes old',
|
||||
pair, int((arrow.utcnow() - latest_date).total_seconds() // 60)
|
||||
)
|
||||
return False, False, None
|
||||
return None, None
|
||||
return latest, latest_date
|
||||
|
||||
enter = latest[SignalType.BUY.value] == 1
|
||||
def get_exit_signal(
|
||||
self,
|
||||
pair: str,
|
||||
timeframe: str,
|
||||
dataframe: DataFrame,
|
||||
is_short: bool = None
|
||||
) -> Tuple[bool, bool]:
|
||||
"""
|
||||
Calculates current exit signal based based on the buy/short or sell/exit_short
|
||||
columns of the dataframe.
|
||||
Used by Bot to get the signal to exit.
|
||||
depending on is_short, looks at "short" or "long" columns.
|
||||
:param pair: pair in format ANT/BTC
|
||||
:param timeframe: timeframe to use
|
||||
:param dataframe: Analyzed dataframe to get signal from.
|
||||
:param is_short: Indicating existing trade direction.
|
||||
:return: (enter, exit) A bool-tuple with enter / exit values.
|
||||
"""
|
||||
latest, latest_date = self.get_latest_candle(pair, timeframe, dataframe)
|
||||
if latest is None:
|
||||
return False, False
|
||||
|
||||
exit = False
|
||||
if SignalType.SELL.value in latest:
|
||||
exit = latest[SignalType.SELL.value] == 1
|
||||
if is_short:
|
||||
enter = latest.get(SignalType.ENTER_SHORT.value, 0) == 1
|
||||
exit_ = latest.get(SignalType.EXIT_SHORT.value, 0) == 1
|
||||
else:
|
||||
enter = latest[SignalType.ENTER_LONG.value] == 1
|
||||
exit_ = latest.get(SignalType.EXIT_LONG.value, 0) == 1
|
||||
|
||||
buy_tag = latest.get(SignalTagType.BUY_TAG.value, None)
|
||||
logger.debug(f"exit-trigger: {latest['date']} (pair={pair}) "
|
||||
f"enter={enter} exit={exit_}")
|
||||
|
||||
return enter, exit_
|
||||
|
||||
def get_entry_signal(
|
||||
self,
|
||||
pair: str,
|
||||
timeframe: str,
|
||||
dataframe: DataFrame,
|
||||
) -> Tuple[Optional[SignalDirection], Optional[str]]:
|
||||
"""
|
||||
Calculates current entry signal based based on the buy/short or sell/exit_short
|
||||
columns of the dataframe.
|
||||
Used by Bot to get the signal to buy, sell, short, or exit_short
|
||||
:param pair: pair in format ANT/BTC
|
||||
:param timeframe: timeframe to use
|
||||
:param dataframe: Analyzed dataframe to get signal from.
|
||||
:return: (SignalDirection, entry_tag)
|
||||
"""
|
||||
latest, latest_date = self.get_latest_candle(pair, timeframe, dataframe)
|
||||
if latest is None or latest_date is None:
|
||||
return None, None
|
||||
|
||||
enter_long = latest[SignalType.ENTER_LONG.value] == 1
|
||||
exit_long = latest.get(SignalType.EXIT_LONG.value, 0) == 1
|
||||
enter_short = latest.get(SignalType.ENTER_SHORT.value, 0) == 1
|
||||
exit_short = latest.get(SignalType.EXIT_SHORT.value, 0) == 1
|
||||
|
||||
enter_signal: Optional[SignalDirection] = None
|
||||
enter_tag_value: Optional[str] = None
|
||||
if enter_long == 1 and not any([exit_long, enter_short]):
|
||||
enter_signal = SignalDirection.LONG
|
||||
enter_tag_value = latest.get(SignalTagType.ENTER_TAG.value, None)
|
||||
if enter_short == 1 and not any([exit_short, enter_long]):
|
||||
enter_signal = SignalDirection.SHORT
|
||||
enter_tag_value = latest.get(SignalTagType.ENTER_TAG.value, None)
|
||||
|
||||
logger.debug('trigger: %s (pair=%s) buy=%s sell=%s',
|
||||
latest['date'], pair, str(enter), str(exit))
|
||||
timeframe_seconds = timeframe_to_seconds(timeframe)
|
||||
|
||||
if self.ignore_expired_candle(
|
||||
latest_date=latest_date,
|
||||
latest_date=latest_date.datetime,
|
||||
current_time=datetime.now(timezone.utc),
|
||||
timeframe_seconds=timeframe_seconds,
|
||||
enter=enter
|
||||
enter=bool(enter_signal)
|
||||
):
|
||||
return False, exit, buy_tag
|
||||
return enter, exit, buy_tag
|
||||
return None, enter_tag_value
|
||||
|
||||
logger.debug(f"entry trigger: {latest['date']} (pair={pair}) "
|
||||
f"enter={enter_long} enter_tag_value={enter_tag_value}")
|
||||
return enter_signal, enter_tag_value
|
||||
|
||||
def ignore_expired_candle(
|
||||
self,
|
||||
@@ -640,8 +722,9 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
else:
|
||||
return False
|
||||
|
||||
def should_sell(self, trade: Trade, rate: float, date: datetime, buy: bool,
|
||||
sell: bool, low: float = None, high: float = None,
|
||||
def should_exit(self, trade: Trade, rate: float, date: datetime, *,
|
||||
enter: bool, exit_: bool,
|
||||
low: float = None, high: float = None,
|
||||
force_stoploss: float = 0) -> SellCheckTuple:
|
||||
"""
|
||||
This function evaluates if one of the conditions required to trigger an exit order
|
||||
@@ -651,6 +734,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
:param force_stoploss: Externally provided stoploss
|
||||
:return: True if trade should be exited, False otherwise
|
||||
"""
|
||||
|
||||
current_rate = rate
|
||||
current_profit = trade.calc_profit_ratio(current_rate)
|
||||
|
||||
@@ -665,7 +749,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
current_profit = trade.calc_profit_ratio(current_rate)
|
||||
|
||||
# if enter signal and ignore_roi is set, we don't need to evaluate min_roi.
|
||||
roi_reached = (not (buy and self.ignore_roi_if_buy_signal)
|
||||
roi_reached = (not (enter and self.ignore_roi_if_buy_signal)
|
||||
and self.min_roi_reached(trade=trade, current_profit=current_profit,
|
||||
current_time=date))
|
||||
|
||||
@@ -678,10 +762,11 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
if (self.sell_profit_only and current_profit <= self.sell_profit_offset):
|
||||
# sell_profit_only and profit doesn't reach the offset - ignore sell signal
|
||||
pass
|
||||
elif self.use_sell_signal and not buy:
|
||||
if sell:
|
||||
elif self.use_sell_signal and not enter:
|
||||
if exit_:
|
||||
sell_signal = SellType.SELL_SIGNAL
|
||||
else:
|
||||
trade_type = "exit_short" if trade.is_short else "sell"
|
||||
custom_reason = strategy_safe_wrapper(self.custom_sell, default_retval=False)(
|
||||
pair=trade.pair, trade=trade, current_time=date, current_rate=current_rate,
|
||||
current_profit=current_profit)
|
||||
@@ -689,9 +774,9 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
sell_signal = SellType.CUSTOM_SELL
|
||||
if isinstance(custom_reason, str):
|
||||
if len(custom_reason) > CUSTOM_SELL_MAX_LENGTH:
|
||||
logger.warning(f'Custom sell reason returned from custom_sell is too '
|
||||
f'long and was trimmed to {CUSTOM_SELL_MAX_LENGTH} '
|
||||
f'characters.')
|
||||
logger.warning(f'Custom {trade_type} reason returned from '
|
||||
f'custom_{trade_type} is too long and was trimmed'
|
||||
f'to {CUSTOM_SELL_MAX_LENGTH} characters.')
|
||||
custom_reason = custom_reason[:CUSTOM_SELL_MAX_LENGTH]
|
||||
else:
|
||||
custom_reason = None
|
||||
@@ -737,7 +822,12 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
# Initiate stoploss with open_rate. Does nothing if stoploss is already set.
|
||||
trade.adjust_stop_loss(trade.open_rate, stop_loss_value, initial=True)
|
||||
|
||||
if self.use_custom_stoploss and trade.stop_loss < (low or current_rate):
|
||||
dir_correct = (trade.stop_loss < (low or current_rate)
|
||||
if not trade.is_short else
|
||||
trade.stop_loss > (high or current_rate)
|
||||
)
|
||||
|
||||
if self.use_custom_stoploss and dir_correct:
|
||||
stop_loss_value = strategy_safe_wrapper(self.custom_stoploss, default_retval=None
|
||||
)(pair=trade.pair, trade=trade,
|
||||
current_time=current_time,
|
||||
@@ -755,6 +845,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
sl_offset = self.trailing_stop_positive_offset
|
||||
|
||||
# Make sure current_profit is calculated using high for backtesting.
|
||||
# TODO-lev: Check this function - high / low usage must be inversed for short trades!
|
||||
high_profit = current_profit if not high else trade.calc_profit_ratio(high)
|
||||
|
||||
# Don't update stoploss if trailing_only_offset_is_reached is true.
|
||||
@@ -821,7 +912,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
def advise_all_indicators(self, data: Dict[str, DataFrame]) -> Dict[str, DataFrame]:
|
||||
"""
|
||||
Populates indicators for given candle (OHLCV) data (for multiple pairs)
|
||||
Does not run advise_buy or advise_sell!
|
||||
Does not run advise_entry or advise_exit!
|
||||
Used by optimize operations only, not during dry / live runs.
|
||||
Using .copy() to get a fresh copy of the dataframe for every strategy run.
|
||||
Also copy on output to avoid PerformanceWarnings pandas 1.3.0 started to show.
|
||||
@@ -853,7 +944,7 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
else:
|
||||
return self.populate_indicators(dataframe, metadata)
|
||||
|
||||
def advise_buy(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
def advise_entry(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the entry order signal for the given dataframe
|
||||
This method should not be overridden.
|
||||
@@ -868,11 +959,15 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
if self._buy_fun_len == 2:
|
||||
warnings.warn("deprecated - check out the Sample strategy to see "
|
||||
"the current function headers!", DeprecationWarning)
|
||||
return self.populate_buy_trend(dataframe) # type: ignore
|
||||
df = self.populate_buy_trend(dataframe) # type: ignore
|
||||
else:
|
||||
return self.populate_buy_trend(dataframe, metadata)
|
||||
df = self.populate_buy_trend(dataframe, metadata)
|
||||
if 'enter_long' not in df.columns:
|
||||
df = df.rename({'buy': 'enter_long', 'buy_tag': 'enter_tag'}, axis='columns')
|
||||
|
||||
def advise_sell(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
return df
|
||||
|
||||
def advise_exit(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the exit order signal for the given dataframe
|
||||
This method should not be overridden.
|
||||
@@ -886,6 +981,9 @@ class IStrategy(ABC, HyperStrategyMixin):
|
||||
if self._sell_fun_len == 2:
|
||||
warnings.warn("deprecated - check out the Sample strategy to see "
|
||||
"the current function headers!", DeprecationWarning)
|
||||
return self.populate_sell_trend(dataframe) # type: ignore
|
||||
df = self.populate_sell_trend(dataframe) # type: ignore
|
||||
else:
|
||||
return self.populate_sell_trend(dataframe, metadata)
|
||||
df = self.populate_sell_trend(dataframe, metadata)
|
||||
if 'exit_long' not in df.columns:
|
||||
df = df.rename({'sell': 'exit_long'}, axis='columns')
|
||||
return df
|
||||
|
@@ -1,5 +1,6 @@
|
||||
import pandas as pd
|
||||
|
||||
from freqtrade.exceptions import OperationalException
|
||||
from freqtrade.exchange import timeframe_to_minutes
|
||||
|
||||
|
||||
@@ -66,7 +67,11 @@ def merge_informative_pair(dataframe: pd.DataFrame, informative: pd.DataFrame,
|
||||
return dataframe
|
||||
|
||||
|
||||
def stoploss_from_open(open_relative_stop: float, current_profit: float) -> float:
|
||||
def stoploss_from_open(
|
||||
open_relative_stop: float,
|
||||
current_profit: float,
|
||||
for_short: bool = False
|
||||
) -> float:
|
||||
"""
|
||||
|
||||
Given the current profit, and a desired stop loss value relative to the open price,
|
||||
@@ -87,10 +92,19 @@ def stoploss_from_open(open_relative_stop: float, current_profit: float) -> floa
|
||||
if current_profit == -1:
|
||||
return 1
|
||||
|
||||
stoploss = 1-((1+open_relative_stop)/(1+current_profit))
|
||||
if for_short is True:
|
||||
# TODO-lev: How would this be calculated for short
|
||||
raise OperationalException(
|
||||
"Freqtrade hasn't figured out how to calculated stoploss on shorts")
|
||||
# stoploss = 1-((1+open_relative_stop)/(1+current_profit))
|
||||
else:
|
||||
stoploss = 1-((1+open_relative_stop)/(1+current_profit))
|
||||
|
||||
# negative stoploss values indicate the requested stop price is higher than the current price
|
||||
return max(stoploss, 0.0)
|
||||
if for_short:
|
||||
return min(stoploss, 0.0)
|
||||
else:
|
||||
return max(stoploss, 0.0)
|
||||
|
||||
|
||||
def stoploss_from_absolute(stop_rate: float, current_rate: float) -> float:
|
||||
|
@@ -122,7 +122,7 @@ class {{ strategy }}(IStrategy):
|
||||
{{ buy_trend | indent(16) }}
|
||||
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||
),
|
||||
'buy'] = 1
|
||||
'enter_long'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
@@ -138,6 +138,6 @@ class {{ strategy }}(IStrategy):
|
||||
{{ sell_trend | indent(16) }}
|
||||
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||
),
|
||||
'sell'] = 1
|
||||
'exit_long'] = 1
|
||||
return dataframe
|
||||
{{ additional_methods | indent(4) }}
|
||||
|
380
freqtrade/templates/sample_short_strategy.py
Normal file
380
freqtrade/templates/sample_short_strategy.py
Normal file
@@ -0,0 +1,380 @@
|
||||
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
|
||||
# flake8: noqa: F401
|
||||
# isort: skip_file
|
||||
# --- Do not remove these libs ---
|
||||
import numpy as np # noqa
|
||||
import pandas as pd # noqa
|
||||
from pandas import DataFrame
|
||||
|
||||
from freqtrade.strategy import (BooleanParameter, CategoricalParameter, DecimalParameter,
|
||||
IStrategy, IntParameter)
|
||||
|
||||
# --------------------------------
|
||||
# Add your lib to import here
|
||||
import talib.abstract as ta
|
||||
import freqtrade.vendor.qtpylib.indicators as qtpylib
|
||||
|
||||
|
||||
# TODO-lev: Create a meaningfull short strategy (not just revresed signs).
|
||||
# This class is a sample. Feel free to customize it.
|
||||
class SampleShortStrategy(IStrategy):
|
||||
"""
|
||||
This is a sample strategy to inspire you.
|
||||
More information in https://www.freqtrade.io/en/latest/strategy-customization/
|
||||
|
||||
You can:
|
||||
:return: a Dataframe with all mandatory indicators for the strategies
|
||||
- Rename the class name (Do not forget to update class_name)
|
||||
- Add any methods you want to build your strategy
|
||||
- Add any lib you need to build your strategy
|
||||
|
||||
You must keep:
|
||||
- the lib in the section "Do not remove these libs"
|
||||
- the methods: populate_indicators, populate_buy_trend, populate_sell_trend
|
||||
You should keep:
|
||||
- timeframe, minimal_roi, stoploss, trailing_*
|
||||
"""
|
||||
# Strategy interface version - allow new iterations of the strategy interface.
|
||||
# Check the documentation or the Sample strategy to get the latest version.
|
||||
INTERFACE_VERSION = 2
|
||||
|
||||
# Minimal ROI designed for the strategy.
|
||||
# This attribute will be overridden if the config file contains "minimal_roi".
|
||||
minimal_roi = {
|
||||
"60": 0.01,
|
||||
"30": 0.02,
|
||||
"0": 0.04
|
||||
}
|
||||
|
||||
# Optimal stoploss designed for the strategy.
|
||||
# This attribute will be overridden if the config file contains "stoploss".
|
||||
stoploss = -0.10
|
||||
|
||||
# Trailing stoploss
|
||||
trailing_stop = False
|
||||
# trailing_only_offset_is_reached = False
|
||||
# trailing_stop_positive = 0.01
|
||||
# trailing_stop_positive_offset = 0.0 # Disabled / not configured
|
||||
|
||||
# Hyperoptable parameters
|
||||
short_rsi = IntParameter(low=51, high=100, default=70, space='sell', optimize=True, load=True)
|
||||
exit_short_rsi = IntParameter(low=1, high=50, default=30, space='buy', optimize=True, load=True)
|
||||
|
||||
# Optimal timeframe for the strategy.
|
||||
timeframe = '5m'
|
||||
|
||||
# Run "populate_indicators()" only for new candle.
|
||||
process_only_new_candles = False
|
||||
|
||||
# These values can be overridden in the "ask_strategy" section in the config.
|
||||
use_sell_signal = True
|
||||
sell_profit_only = False
|
||||
ignore_roi_if_buy_signal = False
|
||||
|
||||
# Number of candles the strategy requires before producing valid signals
|
||||
startup_candle_count: int = 30
|
||||
|
||||
# Optional order type mapping.
|
||||
order_types = {
|
||||
'buy': 'limit',
|
||||
'sell': 'limit',
|
||||
'stoploss': 'market',
|
||||
'stoploss_on_exchange': False
|
||||
}
|
||||
|
||||
# Optional order time in force.
|
||||
order_time_in_force = {
|
||||
'buy': 'gtc',
|
||||
'sell': 'gtc'
|
||||
}
|
||||
|
||||
plot_config = {
|
||||
'main_plot': {
|
||||
'tema': {},
|
||||
'sar': {'color': 'white'},
|
||||
},
|
||||
'subplots': {
|
||||
"MACD": {
|
||||
'macd': {'color': 'blue'},
|
||||
'macdsignal': {'color': 'orange'},
|
||||
},
|
||||
"RSI": {
|
||||
'rsi': {'color': 'red'},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
def informative_pairs(self):
|
||||
"""
|
||||
Define additional, informative pair/interval combinations to be cached from the exchange.
|
||||
These pair/interval combinations are non-tradeable, unless they are part
|
||||
of the whitelist as well.
|
||||
For more information, please consult the documentation
|
||||
:return: List of tuples in the format (pair, interval)
|
||||
Sample: return [("ETH/USDT", "5m"),
|
||||
("BTC/USDT", "15m"),
|
||||
]
|
||||
"""
|
||||
return []
|
||||
|
||||
def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Adds several different TA indicators to the given DataFrame
|
||||
|
||||
Performance Note: For the best performance be frugal on the number of indicators
|
||||
you are using. Let uncomment only the indicator you are using in your strategies
|
||||
or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
|
||||
:param dataframe: Dataframe with data from the exchange
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: a Dataframe with all mandatory indicators for the strategies
|
||||
"""
|
||||
|
||||
# Momentum Indicators
|
||||
# ------------------------------------
|
||||
|
||||
# ADX
|
||||
dataframe['adx'] = ta.ADX(dataframe)
|
||||
|
||||
# # Plus Directional Indicator / Movement
|
||||
# dataframe['plus_dm'] = ta.PLUS_DM(dataframe)
|
||||
# dataframe['plus_di'] = ta.PLUS_DI(dataframe)
|
||||
|
||||
# # Minus Directional Indicator / Movement
|
||||
# dataframe['minus_dm'] = ta.MINUS_DM(dataframe)
|
||||
# dataframe['minus_di'] = ta.MINUS_DI(dataframe)
|
||||
|
||||
# # Aroon, Aroon Oscillator
|
||||
# aroon = ta.AROON(dataframe)
|
||||
# dataframe['aroonup'] = aroon['aroonup']
|
||||
# dataframe['aroondown'] = aroon['aroondown']
|
||||
# dataframe['aroonosc'] = ta.AROONOSC(dataframe)
|
||||
|
||||
# # Awesome Oscillator
|
||||
# dataframe['ao'] = qtpylib.awesome_oscillator(dataframe)
|
||||
|
||||
# # Keltner Channel
|
||||
# keltner = qtpylib.keltner_channel(dataframe)
|
||||
# dataframe["kc_upperband"] = keltner["upper"]
|
||||
# dataframe["kc_lowerband"] = keltner["lower"]
|
||||
# dataframe["kc_middleband"] = keltner["mid"]
|
||||
# dataframe["kc_percent"] = (
|
||||
# (dataframe["close"] - dataframe["kc_lowerband"]) /
|
||||
# (dataframe["kc_upperband"] - dataframe["kc_lowerband"])
|
||||
# )
|
||||
# dataframe["kc_width"] = (
|
||||
# (dataframe["kc_upperband"] - dataframe["kc_lowerband"]) / dataframe["kc_middleband"]
|
||||
# )
|
||||
|
||||
# # Ultimate Oscillator
|
||||
# dataframe['uo'] = ta.ULTOSC(dataframe)
|
||||
|
||||
# # Commodity Channel Index: values [Oversold:-100, Overbought:100]
|
||||
# dataframe['cci'] = ta.CCI(dataframe)
|
||||
|
||||
# RSI
|
||||
dataframe['rsi'] = ta.RSI(dataframe)
|
||||
|
||||
# # Inverse Fisher transform on RSI: values [-1.0, 1.0] (https://goo.gl/2JGGoy)
|
||||
# rsi = 0.1 * (dataframe['rsi'] - 50)
|
||||
# dataframe['fisher_rsi'] = (np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1)
|
||||
|
||||
# # Inverse Fisher transform on RSI normalized: values [0.0, 100.0] (https://goo.gl/2JGGoy)
|
||||
# dataframe['fisher_rsi_norma'] = 50 * (dataframe['fisher_rsi'] + 1)
|
||||
|
||||
# # Stochastic Slow
|
||||
# stoch = ta.STOCH(dataframe)
|
||||
# dataframe['slowd'] = stoch['slowd']
|
||||
# dataframe['slowk'] = stoch['slowk']
|
||||
|
||||
# Stochastic Fast
|
||||
stoch_fast = ta.STOCHF(dataframe)
|
||||
dataframe['fastd'] = stoch_fast['fastd']
|
||||
dataframe['fastk'] = stoch_fast['fastk']
|
||||
|
||||
# # Stochastic RSI
|
||||
# Please read https://github.com/freqtrade/freqtrade/issues/2961 before using this.
|
||||
# STOCHRSI is NOT aligned with tradingview, which may result in non-expected results.
|
||||
# stoch_rsi = ta.STOCHRSI(dataframe)
|
||||
# dataframe['fastd_rsi'] = stoch_rsi['fastd']
|
||||
# dataframe['fastk_rsi'] = stoch_rsi['fastk']
|
||||
|
||||
# MACD
|
||||
macd = ta.MACD(dataframe)
|
||||
dataframe['macd'] = macd['macd']
|
||||
dataframe['macdsignal'] = macd['macdsignal']
|
||||
dataframe['macdhist'] = macd['macdhist']
|
||||
|
||||
# MFI
|
||||
dataframe['mfi'] = ta.MFI(dataframe)
|
||||
|
||||
# # ROC
|
||||
# dataframe['roc'] = ta.ROC(dataframe)
|
||||
|
||||
# Overlap Studies
|
||||
# ------------------------------------
|
||||
|
||||
# Bollinger Bands
|
||||
bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=2)
|
||||
dataframe['bb_lowerband'] = bollinger['lower']
|
||||
dataframe['bb_middleband'] = bollinger['mid']
|
||||
dataframe['bb_upperband'] = bollinger['upper']
|
||||
dataframe["bb_percent"] = (
|
||||
(dataframe["close"] - dataframe["bb_lowerband"]) /
|
||||
(dataframe["bb_upperband"] - dataframe["bb_lowerband"])
|
||||
)
|
||||
dataframe["bb_width"] = (
|
||||
(dataframe["bb_upperband"] - dataframe["bb_lowerband"]) / dataframe["bb_middleband"]
|
||||
)
|
||||
|
||||
# Bollinger Bands - Weighted (EMA based instead of SMA)
|
||||
# weighted_bollinger = qtpylib.weighted_bollinger_bands(
|
||||
# qtpylib.typical_price(dataframe), window=20, stds=2
|
||||
# )
|
||||
# dataframe["wbb_upperband"] = weighted_bollinger["upper"]
|
||||
# dataframe["wbb_lowerband"] = weighted_bollinger["lower"]
|
||||
# dataframe["wbb_middleband"] = weighted_bollinger["mid"]
|
||||
# dataframe["wbb_percent"] = (
|
||||
# (dataframe["close"] - dataframe["wbb_lowerband"]) /
|
||||
# (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"])
|
||||
# )
|
||||
# dataframe["wbb_width"] = (
|
||||
# (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) /
|
||||
# dataframe["wbb_middleband"]
|
||||
# )
|
||||
|
||||
# # EMA - Exponential Moving Average
|
||||
# dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3)
|
||||
# dataframe['ema5'] = ta.EMA(dataframe, timeperiod=5)
|
||||
# dataframe['ema10'] = ta.EMA(dataframe, timeperiod=10)
|
||||
# dataframe['ema21'] = ta.EMA(dataframe, timeperiod=21)
|
||||
# dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
|
||||
# dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)
|
||||
|
||||
# # SMA - Simple Moving Average
|
||||
# dataframe['sma3'] = ta.SMA(dataframe, timeperiod=3)
|
||||
# dataframe['sma5'] = ta.SMA(dataframe, timeperiod=5)
|
||||
# dataframe['sma10'] = ta.SMA(dataframe, timeperiod=10)
|
||||
# dataframe['sma21'] = ta.SMA(dataframe, timeperiod=21)
|
||||
# dataframe['sma50'] = ta.SMA(dataframe, timeperiod=50)
|
||||
# dataframe['sma100'] = ta.SMA(dataframe, timeperiod=100)
|
||||
|
||||
# Parabolic SAR
|
||||
dataframe['sar'] = ta.SAR(dataframe)
|
||||
|
||||
# TEMA - Triple Exponential Moving Average
|
||||
dataframe['tema'] = ta.TEMA(dataframe, timeperiod=9)
|
||||
|
||||
# Cycle Indicator
|
||||
# ------------------------------------
|
||||
# Hilbert Transform Indicator - SineWave
|
||||
hilbert = ta.HT_SINE(dataframe)
|
||||
dataframe['htsine'] = hilbert['sine']
|
||||
dataframe['htleadsine'] = hilbert['leadsine']
|
||||
|
||||
# Pattern Recognition - Bullish candlestick patterns
|
||||
# ------------------------------------
|
||||
# # Hammer: values [0, 100]
|
||||
# dataframe['CDLHAMMER'] = ta.CDLHAMMER(dataframe)
|
||||
# # Inverted Hammer: values [0, 100]
|
||||
# dataframe['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(dataframe)
|
||||
# # Dragonfly Doji: values [0, 100]
|
||||
# dataframe['CDLDRAGONFLYDOJI'] = ta.CDLDRAGONFLYDOJI(dataframe)
|
||||
# # Piercing Line: values [0, 100]
|
||||
# dataframe['CDLPIERCING'] = ta.CDLPIERCING(dataframe) # values [0, 100]
|
||||
# # Morningstar: values [0, 100]
|
||||
# dataframe['CDLMORNINGSTAR'] = ta.CDLMORNINGSTAR(dataframe) # values [0, 100]
|
||||
# # Three White Soldiers: values [0, 100]
|
||||
# dataframe['CDL3WHITESOLDIERS'] = ta.CDL3WHITESOLDIERS(dataframe) # values [0, 100]
|
||||
|
||||
# Pattern Recognition - Bearish candlestick patterns
|
||||
# ------------------------------------
|
||||
# # Hanging Man: values [0, 100]
|
||||
# dataframe['CDLHANGINGMAN'] = ta.CDLHANGINGMAN(dataframe)
|
||||
# # Shooting Star: values [0, 100]
|
||||
# dataframe['CDLSHOOTINGSTAR'] = ta.CDLSHOOTINGSTAR(dataframe)
|
||||
# # Gravestone Doji: values [0, 100]
|
||||
# dataframe['CDLGRAVESTONEDOJI'] = ta.CDLGRAVESTONEDOJI(dataframe)
|
||||
# # Dark Cloud Cover: values [0, 100]
|
||||
# dataframe['CDLDARKCLOUDCOVER'] = ta.CDLDARKCLOUDCOVER(dataframe)
|
||||
# # Evening Doji Star: values [0, 100]
|
||||
# dataframe['CDLEVENINGDOJISTAR'] = ta.CDLEVENINGDOJISTAR(dataframe)
|
||||
# # Evening Star: values [0, 100]
|
||||
# dataframe['CDLEVENINGSTAR'] = ta.CDLEVENINGSTAR(dataframe)
|
||||
|
||||
# Pattern Recognition - Bullish/Bearish candlestick patterns
|
||||
# ------------------------------------
|
||||
# # Three Line Strike: values [0, -100, 100]
|
||||
# dataframe['CDL3LINESTRIKE'] = ta.CDL3LINESTRIKE(dataframe)
|
||||
# # Spinning Top: values [0, -100, 100]
|
||||
# dataframe['CDLSPINNINGTOP'] = ta.CDLSPINNINGTOP(dataframe) # values [0, -100, 100]
|
||||
# # Engulfing: values [0, -100, 100]
|
||||
# dataframe['CDLENGULFING'] = ta.CDLENGULFING(dataframe) # values [0, -100, 100]
|
||||
# # Harami: values [0, -100, 100]
|
||||
# dataframe['CDLHARAMI'] = ta.CDLHARAMI(dataframe) # values [0, -100, 100]
|
||||
# # Three Outside Up/Down: values [0, -100, 100]
|
||||
# dataframe['CDL3OUTSIDE'] = ta.CDL3OUTSIDE(dataframe) # values [0, -100, 100]
|
||||
# # Three Inside Up/Down: values [0, -100, 100]
|
||||
# dataframe['CDL3INSIDE'] = ta.CDL3INSIDE(dataframe) # values [0, -100, 100]
|
||||
|
||||
# # Chart type
|
||||
# # ------------------------------------
|
||||
# # Heikin Ashi Strategy
|
||||
# heikinashi = qtpylib.heikinashi(dataframe)
|
||||
# dataframe['ha_open'] = heikinashi['open']
|
||||
# dataframe['ha_close'] = heikinashi['close']
|
||||
# dataframe['ha_high'] = heikinashi['high']
|
||||
# dataframe['ha_low'] = heikinashi['low']
|
||||
|
||||
# Retrieve best bid and best ask from the orderbook
|
||||
# ------------------------------------
|
||||
"""
|
||||
# first check if dataprovider is available
|
||||
if self.dp:
|
||||
if self.dp.runmode.value in ('live', 'dry_run'):
|
||||
ob = self.dp.orderbook(metadata['pair'], 1)
|
||||
dataframe['best_bid'] = ob['bids'][0][0]
|
||||
dataframe['best_ask'] = ob['asks'][0][0]
|
||||
"""
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the buy signal for the given dataframe
|
||||
:param dataframe: DataFrame populated with indicators
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: DataFrame with buy column
|
||||
"""
|
||||
|
||||
dataframe.loc[
|
||||
(
|
||||
# Signal: RSI crosses above 70
|
||||
(qtpylib.crossed_above(dataframe['rsi'], self.short_rsi.value)) &
|
||||
(dataframe['tema'] > dataframe['bb_middleband']) & # Guard: tema above BB middle
|
||||
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard: tema is falling
|
||||
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||
),
|
||||
'enter_short'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
|
||||
"""
|
||||
Based on TA indicators, populates the sell signal for the given dataframe
|
||||
:param dataframe: DataFrame populated with indicators
|
||||
:param metadata: Additional information, like the currently traded pair
|
||||
:return: DataFrame with sell column
|
||||
"""
|
||||
|
||||
dataframe.loc[
|
||||
(
|
||||
# Signal: RSI crosses above 30
|
||||
(qtpylib.crossed_above(dataframe['rsi'], self.exit_short_rsi.value)) &
|
||||
# Guard: tema below BB middle
|
||||
(dataframe['tema'] <= dataframe['bb_middleband']) &
|
||||
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard: tema is raising
|
||||
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||
),
|
||||
'exit_short'] = 1
|
||||
|
||||
return dataframe
|
@@ -352,7 +352,7 @@ class SampleStrategy(IStrategy):
|
||||
(dataframe['tema'] > dataframe['tema'].shift(1)) & # Guard: tema is raising
|
||||
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||
),
|
||||
'buy'] = 1
|
||||
'enter_long'] = 1
|
||||
|
||||
return dataframe
|
||||
|
||||
@@ -371,5 +371,5 @@ class SampleStrategy(IStrategy):
|
||||
(dataframe['tema'] < dataframe['tema'].shift(1)) & # Guard: tema is falling
|
||||
(dataframe['volume'] > 0) # Make sure Volume is not 0
|
||||
),
|
||||
'sell'] = 1
|
||||
'exit_long'] = 1
|
||||
return dataframe
|
||||
|
@@ -12,12 +12,11 @@ def bot_loop_start(self, **kwargs) -> None:
|
||||
"""
|
||||
pass
|
||||
|
||||
def custom_stake_amount(self, pair: str, current_time: 'datetime', current_rate: float,
|
||||
def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
|
||||
proposed_stake: float, min_stake: float, max_stake: float,
|
||||
**kwargs) -> float:
|
||||
side: str, **kwargs) -> float:
|
||||
"""
|
||||
Customize stake size for each new trade. This method is not called when edge module is
|
||||
enabled.
|
||||
Customize stake size for each new trade.
|
||||
|
||||
:param pair: Pair that's currently analyzed
|
||||
:param current_time: datetime object, containing the current datetime
|
||||
@@ -25,6 +24,7 @@ def custom_stake_amount(self, pair: str, current_time: 'datetime', current_rate:
|
||||
:param proposed_stake: A stake amount proposed by the bot.
|
||||
:param min_stake: Minimal stake size allowed by exchange.
|
||||
:param max_stake: Balance available for trading.
|
||||
:param side: 'long' or 'short' - indicating the direction of the proposed trade
|
||||
:return: A stake size, which is between min_stake and max_stake.
|
||||
"""
|
||||
return proposed_stake
|
||||
@@ -80,9 +80,10 @@ def custom_sell(self, pair: str, trade: 'Trade', current_time: 'datetime', curre
|
||||
return None
|
||||
|
||||
def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
|
||||
time_in_force: str, current_time: 'datetime', **kwargs) -> bool:
|
||||
time_in_force: str, current_time: datetime,
|
||||
side: str, **kwargs) -> bool:
|
||||
"""
|
||||
Called right before placing a buy order.
|
||||
Called right before placing a entry order.
|
||||
Timing for this function is critical, so avoid doing heavy computations or
|
||||
network requests in this method.
|
||||
|
||||
@@ -90,12 +91,13 @@ def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: f
|
||||
|
||||
When not implemented by a strategy, returns True (always confirming).
|
||||
|
||||
:param pair: Pair that's about to be bought.
|
||||
:param pair: Pair that's about to be bought/shorted.
|
||||
:param order_type: Order type (as configured in order_types). usually limit or market.
|
||||
:param amount: Amount in target (quote) currency that's going to be traded.
|
||||
:param rate: Rate that's going to be used when using limit orders
|
||||
:param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
|
||||
:param current_time: datetime object, containing the current datetime
|
||||
:param side: 'long' or 'short' - indicating the direction of the proposed trade
|
||||
:param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
|
||||
:return bool: When True is returned, then the buy-order is placed on the exchange.
|
||||
False aborts the process
|
||||
|
Reference in New Issue
Block a user