# pr#agma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# isort: skip_file
# --- Do not remove these libs ---
import numpy as np  # noqa
import pandas as pd  # noqa
from freqtrade.strategy.parameters import  DecimalParameter, BooleanParameter
from pandas import DataFrame
import math
from functools import reduce


from freqtrade.strategy.interface import IStrategy

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


# This class is a sample. Feel free to customize it.
class StrategyPierrick4111(IStrategy):
    # 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

    # valeur de bbwidth pour démarrer
    buy_hausse_bollinger = DecimalParameter(0.025, 0.125, decimals=2, default=0.095, space="buy")
    buy_hausse_bollinger_enabled = BooleanParameter(default=True, space="buy")
    # Valeur de la deuxième h_condition bollinger avec h_condition sma200
    buy_hausse_bollinger_2 = DecimalParameter(0.0, 0.08, decimals=2, default=0.04, space="buy")
    buy_hausse_bollinger_2_enabled = BooleanParameter(default=True, space="buy")
    # pourcentage sma à dépasser
    buy_hausse_sma_percent = DecimalParameter(0.95, 1.05, decimals=2, default=0.098, space="buy")
    buy_hausse_sma_percent_enabled = BooleanParameter(default=True, space="buy")
    # volume à atteindre
    buy_hausse_volume = DecimalParameter(0, 50, decimals=1, default=0, space="buy")
    buy_hausse_volume_enabled = BooleanParameter(default=True, space="buy")

    # valeur de bbwidth pour démarrer
    buy_baisse_bollinger = DecimalParameter(0.025, 0.125, decimals=2, default=0.095, space="buy")
    buy_baisse_bollinger_enabled = BooleanParameter(default=True, space="buy")
    # Valeur de la deuxième h_condition bollinger avec h_condition sma200
    buy_baisse_bollinger_2 = DecimalParameter(0.0, 0.08, decimals=2, default=0.04, space="buy")
    buy_baisse_bollinger_2_enabled = BooleanParameter(default=True, space="buy")
    # pourcentage sma à dépasser
    buy_baisse_sma_percent = DecimalParameter(0.95, 1.05, decimals=2, default=0.098, space="buy")
    buy_baisse_sma_percent_enabled = BooleanParameter(default=True, space="buy")
    # volume à atteindre
    buy_baisse_volume = DecimalParameter(0, 50, decimals=1, default=0, space="buy")
    buy_baisse_volume_enabled = BooleanParameter(default=True, space="buy")

    # buy_hausse_rsi = IntParameter(20, 40, default=30, space="buy")
    # buy_hausse_adx_enabled = BooleanParameter(default=True, space="buy")
    # buy_hausse_rsi_enabled = CategoricalParameter([True, False], default=False, space="buy")
    # buy_hausse_trigger = CategoricalParameter(["bb_lower", "macd_cross_signal"], default="bb_lower", space="buy")

    # ROI table:
    minimal_roi = {
        # "0": 0.015
        "0": 0.5
    }

    # Stoploss:
    stoploss = 0.03
    trailing_stop = True
    trailing_stop_positive = 0.005
    trailing_stop_positive_offset = 0.0175  # 0.015
    trailing_only_offset_is_reached = True

    # max_open_trades = 3

    # Optimal ticker interval 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_hausse_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 indicators (Moving averages, ...)
        'main_plot': {
            'bb_lowerband': {'color': 'white'},
            'bb_upperband': {'color': 'white'},
            'sma100': {'color': 'green'},
            'sma500': {'color': 'blue'},
            'sma200_98': {'color': 'yellow'},
            'sma200_95': {'color': 'cyan'},
            # 'volatility_dcp': {'color': '#c58893'}

        },
        'subplots': {
            # Subplots - each dict defines one additional plot
            "BB": {
                'bb_width': {'color': 'white'},
            },
            "Aaron": {
                'aroonup': {'color': 'blue'},
                'aroondown': {'color': 'red'}
            }
        }
    }

    def informative_pairs(self):
        return []

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # MACD
        # macd = ta.MACD(dataframe)
        # dataframe['macd'] = macd['macd']
        # dataframe['macdsignal'] = macd['macdsignal']
        # dataframe['macdhist'] = macd['macdhist']

        # # 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)

        dataframe['min'] = ta.MIN(dataframe)
        dataframe['max'] = ta.MAX(dataframe)

        # Aroon, Aroon Oscillator
        aroon = ta.AROON(dataframe)
        dataframe['aroonup'] = aroon['aroonup']
        dataframe['aroondown'] = aroon['aroondown']
        dataframe['aroonosc'] = ta.AROONOSC(dataframe)

        # RSI
        # dataframe['rsi'] = ta.RSI(dataframe)

        # # 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)
        dataframe['sma200'] = ta.SMA(dataframe, timeperiod=200)
        dataframe['sma200_95'] = ta.SMA(dataframe, timeperiod=200) * 0.95
        dataframe['sma200_98'] = ta.SMA(dataframe, timeperiod=200) * 0.98
        dataframe['sma500'] = ta.SMA(dataframe, timeperiod=500)
        # dataframe['sma500_90'] = ta.SMA(dataframe, timeperiod=500) * 0.9
        # dataframe['sma500_95'] = ta.SMA(dataframe, timeperiod=500) * 0.95
        # dataframe['sma500_20'] = ta.SMA(dataframe, timeperiod=500) * 0.2

        # 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"]
        )

        # dataframe['volatility_kcw'] = ta.volatility.keltner_channel_wband(
        #     dataframe['high'],
        #     dataframe['low'],
        #     dataframe['close'],
        #     window=20,
        #     window_atr=10,
        #     fillna=False,
        #     original_version=True
        # )
        #
        # dataframe['volatility_dcp'] = ta.volatility.donchian_channel_pband(
        #     dataframe['high'],
        #     dataframe['low'],
        #     dataframe['close'],
        #     window=10,
        #     offset=0,
        #     fillna=False
        # )

        # dataframe['bb_lower_reg'] = dataframe["bb_lowerband"] - dataframe["bb_lowerband"].shift(1)
        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        value = 0
        p = dataframe['close'].shift(20) / dataframe['close']
        for k, v in p.iteritems():
            # print(k, v)
            value = v

        h_condition1 = np.where(value >= 1.04, True, False)

        h_conditions = []
        # GUARDS AND TRENDS
        if self.buy_hausse_bollinger_enabled.value:
            h_conditions.append(dataframe['bb_width'] >= self.buy_hausse_bollinger.value)

        h_conditions2 = []
        if self.buy_hausse_bollinger_2_enabled.value:
            h_conditions2.append(dataframe['bb_width'] >= self.buy_hausse_bollinger_2.value)

        h_conditions_volume = []
        h_condition_volume = True
        if self.buy_hausse_volume_enabled.value:
            h_conditions_volume.append(dataframe['volume'] >= self.buy_hausse_volume.value * 1000)
        if h_conditions_volume:
            h_condition_volume = np.where(h_conditions_volume, True, False)

        h_condition2 = False
        if h_conditions2:
            h_condition2 = reduce(lambda x, y: x & y, h_conditions2) & h_condition1

        h_condition_sma = False
        h_conditions_sma = []
        if self.buy_hausse_sma_percent_enabled.value:
            #h_conditions_sma.append(dataframe['close'] <= dataframe['sma200'] * self.buy_hausse_sma_percent.value)
            h_conditions_sma.append((dataframe['sma100'].shift(36) - dataframe['sma100']) / dataframe['sma100'] > self.buy_hausse_sma_percent.value)
        if h_conditions_sma:
            h_condition_sma = reduce(lambda x, y: x & y, h_conditions_sma)

        b_condition1 = np.where(value >= 1.04, True, False)

        b_conditions = []
        # GUARDS AND TRENDS
        if self.buy_baisse_bollinger_enabled.value:
            b_conditions.append(dataframe['bb_width'] >= self.buy_baisse_bollinger.value)

        b_conditions2 = []
        if self.buy_baisse_bollinger_2_enabled.value:
            b_conditions2.append(dataframe['bb_width'] >= self.buy_baisse_bollinger_2.value)

        b_conditions_volume = []
        b_condition_volume = True
        if self.buy_baisse_volume_enabled.value:
            b_conditions_volume.append(dataframe['volume'] >= self.buy_baisse_volume.value * 1000)
        if b_conditions_volume:
            b_condition_volume = np.where(b_conditions_volume, True, False)

        b_condition2 = False
        if b_conditions2:
            b_condition2 = reduce(lambda x, y: x & y, b_conditions2) & b_condition1

        b_condition_sma = False
        b_conditions_sma = []
        if self.buy_baisse_sma_percent_enabled.value:
            #b_conditions_sma.append(dataframe['close'] <= dataframe['sma200'] * self.buy_baisse_sma_percent.value)
            b_conditions_sma.append((dataframe['sma100'].shift(36) - dataframe['sma100']) / dataframe['sma100'] > self.buy_baisse_sma_percent.value)
        if b_conditions_sma:
            b_condition_sma = reduce(lambda x, y: x & y, b_conditions_sma)

        p = dataframe['sma500'].shift(60) - dataframe['sma500']
        for k, v in p.iteritems():
            # print(k, v)
            value = v
        hausse = np.where(value < 0, True, False)

        if hausse:
            if h_conditions:
                dataframe.loc[
                    (
                        # (((dataframe['close'].shift(1) - dataframe['close']) / dataframe['close']) < 0.025) &
                        (dataframe['close'] < dataframe['bb_lowerband']) &
                        h_condition_volume &
                        (
                            (
                                reduce(lambda x, y: x & y, h_conditions) |
                                (h_condition2 & h_condition_sma)
                            )
                        )
                    ),
                    'buy'] = 1
        else:
            if b_conditions:
                dataframe.loc[
                    (
                        # (((dataframe['close'].shift(1) - dataframe['close']) / dataframe['close']) < 0.025) &
                        (dataframe['close'] < dataframe['bb_lowerband']) &
                        b_condition_volume &
                        (
                            (
                                reduce(lambda x, y: x & y, b_conditions) |
                                (b_condition2 & b_condition_sma)
                            )
                        )
                    ),
                    'buy'] = 1

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                (dataframe['close'] < dataframe['bb_lowerband']) &
                (((dataframe['bb_lowerband'].shift(1) - dataframe['bb_lowerband']) / dataframe['bb_lowerband']) >= 0.015)
                # (((dataframe['close'].shift(1) - dataframe['close']) / dataframe['close']) >= 0.025)
            ),

            'sell'] = 1
        return dataframe
