freqtrade / freqtrade-strategies

Free trading strategies for Freqtrade bot
GNU General Public License v3.0
3.44k stars 1.13k forks source link

Using Leverage 10 x #258

Closed par3 closed 2 years ago

par3 commented 2 years ago

For requestion a new strategy. Please use the template below.
Any strategy request that does not follow the template will be closed.

  1. when used Freqtrade could not start
  2. i need to set leverage

Step 1: What indicators are required?

RSI

Step 2: Explain the Buy Strategy

long : RSI crossed_above 30 short : RSI crossed_below 70

Source

# --- Do not remove these libs ---
from freqtrade.strategy import IStrategy
from pandas import DataFrame
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib

# --------------------------------

class BRsi(IStrategy):

    INTERFACE_VERSION: int = 3
        # Can this strategy go short?
    can_short: bool = True
    # Minimal ROI designed for the strategy.
    # adjust based on market conditions. We would recommend to keep it low for quick turn arounds
    # This attribute will be overridden if the config file contains "minimal_roi"

    minimal_roi = {
    "15": 0.0,
    "10": 0.01,
    "5": 0.01,
    "0": 0.01
    }

    exit_profit_only = True
    exit_profit_offset = 0.01

    # Optimal stoploss designed for the strategy
    stoploss = -0.01

    # Optimal timeframe for the strategy
    timeframe = '1m'

    plot_config = {
        'main_plot': {
            'RSI': {'rsi': {'color': 'red'},},            
        },
    }

    def leverage(self, pair: str, current_time: datetime, current_rate: float,
                 proposed_leverage: float, max_leverage: float, entry_tag: Optional[str], side: str,
                 **kwargs) -> float:
        """
        Customize leverage for each new trade. This method is only called in futures mode.

        :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 exit_pricing.
        :param proposed_leverage: A leverage proposed by the bot.
        :param max_leverage: Max leverage allowed on this pair
        :param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
        :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 10.0

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)

        # 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']

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

        dataframe.loc[
            (
                # Signal: RSI crosses above 30
                (qtpylib.crossed_above(dataframe['rsi'], 30)) &
                (dataframe['volume'] > 0)  # Make sure Volume is not 0
            ),
            'enter_long'] = 1

        dataframe.loc[
            (
                # Signal: RSI crosses above 70
                (qtpylib.crossed_below(dataframe['rsi'], 70)) &
                (dataframe['volume'] > 0)  # Make sure Volume is not 0
            ),
            'enter_short'] = 1

        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

     return dataframe
xmatthias commented 2 years ago

I'm not sure what exactly your question here is.

your leverage - compared with the stoploss will not work - as this will result in a stoploss of 0.1% (0.01 / 10) - which is in unfortunate instances more than the fees + spread - but will at any rate result in very many stoplosses - as you'll not give the trade ANY room to work.

par3 commented 2 years ago

thank you is there any sample strategy using leverage and stoploss ?

par3 commented 2 years ago

whan i use docker cannot start freqtrade

xmatthias commented 2 years ago

The strategy itself seems mostly fine (there's a few missing imports - but any good editor (vscode with python plugin?) will highlight these and propose fixes.

without knowing the error itself, it's quite difficult to determine what causes problems for you.

par3 commented 2 years ago

i have some changes on my strategy but there is some questions now

  1. After I did the leverage 10x settings, still the bot is on 1x trade
  2. populate_exit_trend, how to set exit when got 1% profit

Source

# --- Do not remove these libs ---
# from freqtrade.strategy import IStrategy
from pandas import DataFrame

from datetime import datetime
from typing import Optional
from freqtrade.persistence import Trade
from freqtrade.strategy import (BooleanParameter, DecimalParameter, IntParameter, IStrategy,RealParameter)
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib

# --------------------------------

class BRsi(IStrategy):
    """
    author@: isildur
    """

    INTERFACE_VERSION: int = 3
        # Can this strategy go short?
    # can_short: bool = True
    # Minimal ROI designed for the strategy.
    # adjust based on market conditions. We would recommend to keep it low for quick turn arounds
    # This attribute will be overridden if the config file contains "minimal_roi"

    # class StrategyTestV3Futures(BRsi):

    can_short = True

    minimal_roi = {
    "10": 0.0,
    "5": 0.005,
    "0": 0.01
    }

    exit_profit_only = True
    exit_profit_offset = 0.01

    # Optimal stoploss designed for the strategy
    stoploss = -0.50
    trailing_stop = True
    trailing_stop_positive = 0.30
    trailing_stop_positive_offset = 0.0
    trailing_only_offset_is_reached = False  # Default - not necessary for this example

    # Optimal timeframe for the strategy
    timeframe = '1m'

    plot_config = {
        'main_plot': {
            'RSI': {'rsi': {'color': 'red'},},            
        },
    }

    buy_rsi = IntParameter([29, 31], default=30, space='buy')
    buy_plusdi = RealParameter(low=0, high=1, default=0.5, space='buy')
    sell_rsi = IntParameter(low=69, high=71, default=70, space='sell')
    sell_minusdi = DecimalParameter(low=0, high=1, default=0.5001, decimals=3, space='sell',
                                    load=False)
    protection_enabled = BooleanParameter(default=True)
    protection_cooldown_lookback = IntParameter([0, 50], default=30)

    def leverage(self, pair: str, current_time: datetime, current_rate: float,
                 proposed_leverage: float, max_leverage: float, entry_tag: Optional[str],
                 side: str, **kwargs) -> float:
        # Return 3.0 in all cases.
        # Bot-logic must make sure it's an allowed leverage and eventually adjust accordingly.

        return 10.0

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)

        # 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']

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

        dataframe.loc[
            (
                # Signal: RSI crosses above 30
                # (qtpylib.crossed_above(dataframe['rsi'], 30)) &
                (qtpylib.crossed_above(dataframe['rsi'],  self.buy_rsi.value)) &
                # (dataframe['tema'] <= dataframe['bb_middleband']) &  # Guard: tema below BB middle
                # (dataframe['tema'] > dataframe['tema'].shift(1)) &  # Guard: tema is raising
                (dataframe['volume'] > 0)  # Make sure Volume is not 0
            ),
            'enter_long'] = 1

        dataframe.loc[
            (
                # Signal: RSI crosses above 70
                # (qtpylib.crossed_below(dataframe['rsi'], 70)) &
                (qtpylib.crossed_below(dataframe['rsi'], self.sell_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_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:

        dataframe.loc[
            (
                qtpylib.crossed_above(dataframe['rsi'], self.buy_rsi.value)
            ),
            'exit_short'] = 1

        return dataframe
xmatthias commented 2 years ago

There is nothing obviously wrong with the above. Only a strategy is however not sufficient to diagnose any problem. Freqtrade can and will only apply leverage on markets that actually support this.

I'd again encourage you to read the documentation - which will be covering most of your questions.