# source: https://raw.githubusercontent.com/1amcord/freqtrade_settings/b078a9d66f5e88f6ad18d35066241aaf91c31032/strategies/RsiStrat.py
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# flake8: noqa: F401

# --- Do not remove these libs ---
import numpy as np  # noqa
import pandas as pd  # noqa
from pandas import DataFrame
from datetime import datetime
from freqtrade.persistence import Trade
from functools import reduce
from freqtrade.strategy import (DecimalParameter,
                                IStrategy, IntParameter, DecimalParameter, stoploss_from_open)

# --------------------------------
# Add your lib to import here
import talib.abstract as ta
import pandas_ta as pta
import freqtrade.vendor.qtpylib.indicators as qtpylib

import logging
logger = logging.getLogger(__name__)


class github_1amcord_freqtrade_settings__RsiStrat__20220814_101522(IStrategy):
    """
    This is a strategy template to get you started.
    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_enter_trend, populate_exit_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 = 3

    # Optimal timeframe for the strategy.
    timeframe = '5m'
    inf_tf = '4h'

    minimal_roi = {
        "0": 100
    }

    entry_params = {
    }
    # Stoploss:
    stoploss = -1

    # Trailing stop:
    trailing_stop = False
    trailing_stop_positive = 0.007
    trailing_stop_positive_offset = 0.009
    trailing_only_offset_is_reached = False
    use_custom_stoploss = True

# Perkmeister sagt (https://discord.com/channels/700048804539400213/702584639063064586/926946098898141205):
# The 'normal' range of these parameters are here, as used in BigZ04_TSL3, they are wildly different to yours:
#
#         "pHSL": -0.08,
#         "pPF_1": 0.016,
#         "pSL_1": 0.011,
#         "pPF_2": 0.080,
#         "pSL_2": 0.040,

    pHSL = -1
    pPF_1 = DecimalParameter(
        0.008, 0.04, decimals=3, default=0.012, space="sell", optimize=False)
    pSL_1 = DecimalParameter(
        0.001, 0.012, decimals=3, default=0.009, space="sell", optimize=False)
    pPF_2 = DecimalParameter(
        0.01, 0.1, decimals=3, default=0.045, space="sell", optimize=False)
    pSL_2 = DecimalParameter(
        0.008, 0.04, decimals=3, default=0.018, space="sell", optimize=False)

    # 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_exit_signal = False
    exit_profit_only = True
    ignore_roi_if_entry_signal = False

    # Number of candles the strategy requires before producing valid signals
    startup_candle_count: int = 6

    # Adjust position amount
    position_adjustment_enable = True
    dca_max_rebuys = IntParameter(
        1, 38, default=35, space="buy", optimize=True) #before: Default: 35
    dca_max_drawdown = DecimalParameter(
        0.1, 1, decimals=2, default=0.20, space="buy", optimize=False) #before: Default: 35
    cci_rol_smma_buy = IntParameter(
        1, 8, default=4, space="buy", optimize=False)
    rsi_rol_buy = IntParameter(
        1, 8, default=4, space="buy", optimize=False)
    

    # Optional order type mapping.
    order_types = {
        'entry': 'market',
        'exit': 'market',
        'stoploss': 'market',
        'stoploss_on_exchange': False,
        'stoploss_on_exchange_interval': 30,
        'stoploss_on_exchange_limit_ratio': 0.99
    }

    # Optional order time in force.
    order_time_in_force = {
        'entry': 'gtc',
        'exit': 'gtc'
    }

    @property
    def plot_config(self):
        return {
            # Main plot indicators (Moving averages, ...)
            'main_plot': {
            },
            'subplots': {
                # Subplots - each dict defines one additional plot
                "RSI": {
                    'RSI': {'color': 'red'},
                    'SMMA': {'color': 'yellow'},
                    'CCI': {'color': 'green'},
                }
            }
        }

    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"),
                            ]
        """
        # get access to all pairs available in whitelist.
        pairs = self.dp.current_whitelist()
        # Assign tf to each pair so they can be downloaded and cached for strategy.
        informative_pairs = [(pair, self.inf_tf)
                             for pair in pairs]
        return informative_pairs

    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
        """
        if not self.dp:
            # Don't do anything if DataProvider is not available.
            return dataframe

        # RSI
        dataframe['RSI'] = ta.RSI(dataframe, timeperiod=14)

        # CCI
        dataframe['CCI'] = ta.CCI(dataframe, timeperiod=14)

        # SMMA
        dataframe['SMMA'] = ta.SMA(
            ta.RSI(dataframe, timeperiod=5).rolling(3).mean(), period=14
        )

        #informative

         # Get the informative pair
        informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_tf)
        
        # Get the 14 day cci
        informative['RSI'] = ta.RSI(informative, timeperiod=14)

        # Rename columns to be unique
        informative.columns = [f"{col}_{self.inf_tf}" for col in informative.columns]
        # Assuming inf_tf = '1d' - then the columns will now be:
        # date_1d, open_1d, high_1d, low_1d, close_1d, rsi_1d

        # Combine the 2 dataframes
        # all indicators on the informative sample MUST be calculated before this point
        dataframe = pd.merge(dataframe, informative, left_on='date', right_on=f'date_{self.inf_tf}', how='left')
        # FFill to have the 1d value available in every row throughout the day.
        # Without this, comparisons would only work once per day.
        dataframe = dataframe.ffill()

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the entry signal for the given dataframe
        :param dataframe: DataFrame populated with indicators
        :param metadata: Additional information, like the currently traded pair
        :return: DataFrame with entry column
        """
        conditions = []
        conditions.append(
            (dataframe['RSI_4h'] >= dataframe['RSI_4h'].shift(1).rolling(self.rsi_rol_buy.value).max()) &
            (dataframe['CCI'] > dataframe['CCI'].shift(1).rolling(self.cci_rol_smma_buy.value).max()) &
            (qtpylib.crossed_above(dataframe['RSI'], dataframe['SMMA'])) &
            (dataframe['volume'] > 0)
        )

        if conditions:
            dataframe.loc[
                reduce(lambda x, y: x & y, conditions),
                'enter_long']=1

        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the exit signal for the given dataframe
        :param dataframe: DataFrame populated with indicators
        :param metadata: Additional information, like the currently traded pair
        :return: DataFrame with enter column
        """
        conditions = []

        conditions.append(
            (dataframe['volume'] > 0)
        )

        if conditions:
            dataframe.loc[
                reduce(lambda x, y: x & y, conditions),
                'exit_long']=0

        return dataframe

    # This is called when placing the initial order (opening trade)

    def custom_stake_amount(self, pair: str, current_rate: float,
                            proposed_stake: float, min_stake: float, max_stake: float, **kwargs) -> float:

        # We need to leave most of the funds for possible further DCA orders
        # This also applies to fixed stakes
        new_proposed_stake = (proposed_stake/(self.dca_max_rebuys.value+1))

        return (new_proposed_stake)
        # return proposed_stake

    def adjust_trade_position(self, trade: Trade, current_time: 'datetime',
                              current_rate: float, current_profit: float, min_stake: float,
                              max_stake: float, **kwargs):
        """
        Custom trade adjustment logic, returning the stake amount that a trade should be increased.
        This means extra enter orders with additional fees.

        :param trade: trade object.
        :param current_time: datetime object, containing the current datetime
        :param current_rate: Current enter rate.
        :param current_profit: Current profit (as ratio), calculated based on current_rate.
        :param min_stake: Minimal stake size allowed by exchange.
        :param max_stake: Balance available for trading.
        :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
        :return float: Stake amount to adjust your trade
        """
        # Obtain pair dataframe (just to show how to access it)
        dataframe, _ = self.dp.get_analyzed_dataframe(
            trade.pair, self.timeframe)

        last_candle = dataframe.iloc[-1].squeeze()
        filled_buys = trade.select_filled_orders(trade.entry_side)

        count_of_entries = trade.nr_of_successful_entries
        filled_entries = trade.select_filled_orders(trade.entry_side)
        first_buy_price = filled_buys[0].price

        max_rebuys = self.dca_max_rebuys.value
        max_drawdown = self.dca_max_drawdown.value
        drawdown_per_trade = max_drawdown/max_rebuys
        
        next_buy_price = first_buy_price*(1-(drawdown_per_trade*(count_of_entries+1)))
        last_candle_close = last_candle['close']
        trade_drawdown = 100-(last_candle_close/first_buy_price)*100


        if (last_candle_close > next_buy_price):
            return None
        if (max_stake < min_stake):
            return None

        logger.info('Date %s - First buy price: %s - last candle close price: %s - next buy price: %s', current_time,
                    first_buy_price, last_candle_close, format(next_buy_price, ".2f"))
        logger.info("\tFilled entries: %s (max: %s) - Trade Drawdown: %s",
                    count_of_entries+1, max_rebuys+1, format(trade_drawdown, ".1f"))
        # This returns first order stake size
        new_stake_amount = (filled_entries[0].cost)
        new_stake_amount = new_stake_amount

        # Don't stake more than left
        if (new_stake_amount > max_stake):
            new_stake_amount = max_stake

        # On last round, put in everything
        if(count_of_entries == max_rebuys):
            new_stake_amount = max_stake

        logger.info("\tNew stake: %s - stake left %s",
                     new_stake_amount, format(max_stake-new_stake_amount, ".2f"))
        return (new_stake_amount)

    # Custom Trailing stoploss ( credit to Perkmeister for this custom stoploss to help the strategy ride a green candle )
    def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
                        current_rate: float, current_profit: float, **kwargs) -> float:

        # hard stoploss profit
        HSL = self.pHSL
        PF_1 = self.pPF_1.value
        SL_1 = self.pSL_1.value
        PF_2 = self.pPF_2.value
        SL_2 = self.pSL_2.value
        my_sl = HSL

        # For profits between PF_1 and PF_2 the stoploss (sl_profit) used is linearly interpolated
        # between the values of SL_1 and SL_2. For all profits above PL_2 the sl_profit value
        # rises linearly with current profit, for profits below PF_1 the hard stoploss profit is used.

        # logger.info('Checking profit. Current: %s - PF_1: %s - PF_2: %s', current_profit, PF_1, PF_2)
        if (current_profit > PF_2):
            sl_profit = SL_2 + (current_profit - PF_2)
        elif (current_profit > PF_1):
            sl_profit = SL_1 + ((current_profit - PF_1) *
                                (SL_2 - SL_1) / (PF_2 - PF_1))
        else:
            sl_profit = HSL

        # Only for hyperopt invalid return
        if (sl_profit >= current_profit):
            return 1

        my_sl = stoploss_from_open(sl_profit, current_profit)

        return my_sl
