# pr#agma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# isort: skip_file
# --- Do not remove these libs ---
from datetime import datetime

import numpy as np  # noqa
import pandas as pd  # noqa
from freqtrade.strategy.parameters import  DecimalParameter, BooleanParameter, IntParameter
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
from freqtrade.strategy.strategy_helper import merge_informative_pair


# This class is a sample. Feel free to customize it.
class StrategyJD_5_5(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_bollinger = DecimalParameter(0.025, 0.125, decimals=2, default=0.07, space="buy")
    #buy_msma_10 = DecimalParameter(0.997, 1.020, decimals=3, default=0.998, space="buy")
    # pourcentage sma à dépasser
    # buy_sma_percent = DecimalParameter(0.95, 1.05, decimals=2, default=0.97, space="buy")
    buy_decalage = IntParameter(1, 24, default=5, space="buy")
    buy_decalage2 = IntParameter(1, 24, default=5, space="buy")
    buy_decalage3 = IntParameter(1, 24, default=5, space="buy")
    buy_decalage4 = IntParameter(1, 24, default=5, space="buy")

    buy_min_max_n = DecimalParameter(0, 0.2, decimals=2, default=0.05, space='buy')
    buy_min_max_n2 = DecimalParameter(0, 0.2, decimals=2, default=0.05, space='buy')
    buy_min_max_n3 = DecimalParameter(0, 0.2, decimals=2, default=0.05, space='buy')
    buy_min_max_n4 = DecimalParameter(0, 0.2, decimals=2, default=0.05, space='buy')

    buy_rsi_min_1d = IntParameter(0, 25, default=5, space="buy")
    buy_rsi_min_1d2 = IntParameter(25, 50, default=15, space="buy")
    buy_rsi_min_1d3 = IntParameter(50, 75, default=50, space="buy")
    buy_rsi_min_1d4 = IntParameter(75, 100, default=75, space="buy")

    min_percent = DecimalParameter(1, 1.02, decimals=3, default=1.002, space='buy')
    min_percent2 = DecimalParameter(1, 1.02, decimals=3, default=1.002, space='buy')
    min_percent3 = DecimalParameter(1, 1.02, decimals=3, default=1.002, space='buy')
    min_percent4 = DecimalParameter(1, 1.02, decimals=3, default=1.002, space='buy')

    max_percent = DecimalParameter(0, 0.05, decimals=3, default=0.005, space='sell')
    max_percent2 = DecimalParameter(0, 0.05, decimals=3, default=0.005, space='sell')
    max_percent3 = DecimalParameter(0, 0.05, decimals=3, default=0.005, space='sell')
    max_percent4 = DecimalParameter(0, 0.05, decimals=3, default=0.005, space='sell')

    max_profit = DecimalParameter(0, 0.1, decimals=2, default=0.01, space='sell')
    max_profit2 = DecimalParameter(0, 0.1, decimals=2, default=0.01, space='sell')
    max_profit3 = DecimalParameter(0, 0.1, decimals=2, default=0.01, space='sell')
    max_profit4 = DecimalParameter(0, 0.1, decimals=2, default=0.01, space='sell')

    # sell_b_RSI = IntParameter(70, 98, default=88, space='sell')
    # sell_b_RSI2 = IntParameter(70, 98, default=88, space='sell')
    # sell_b_RSI3 = IntParameter(70, 98, default=80, space='sell')
    #
    # sell_b_RSI2_percent = DecimalParameter(0, 0.02, decimals=3,  default=0.01, space='sell')
    sell_h_RSI = IntParameter(70, 98, default=88, space='sell')
    sell_h_RSI2 = IntParameter(70, 98, default=88, space='sell')
    sell_h_RSI3 = IntParameter(70, 98, default=80, space='sell')

    sell_h_RSI2_percent = DecimalParameter(0, 0.02, decimals=3,  default=0.01, space='sell')
    # buy_rsi_max = IntParameter(50, 100, default=60, space="buy")

    buy_rsi_min = IntParameter(0, 50, default=25, space="buy")
    buy_rsi_max = IntParameter(50, 100, default=60, space="buy")
    # buy_rsi_min2 = IntParameter(0, 50, default=25, space="buy")
    # buy_rsi_max2 = IntParameter(50, 100, default=60, space="buy")

    min_n = IntParameter(0, 24, default=15, space="buy")
    min_p = DecimalParameter(1, 1.01, decimals=3, default=1.002, space="buy")
    n_percent = IntParameter(1, 12, default=1, space="protection")
    percent_sell = DecimalParameter(-0.2, -0.01, decimals=2, default=-0.08, space="protection")

    # buy_adx_enabled = BooleanParameter(default=True, space="buy")
    # buy_rsi_enabled = CategoricalParameter([True, False], default=False, space="buy")
    # buy_trigger = CategoricalParameter(["bb_lower", "macd_cross_signal"], default="bb_lower", space="buy")

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

    # Stoploss:
    stoploss = -1
    trailing_stop = True
    trailing_stop_positive = 0.001
    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_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'},
            'min200': {'color': 'yellow'},
            'min200_001': {'color': 'yellow'},
        },
        'subplots': {
            # Subplots - each dict defines one additional plot
            "BB": {
                'bb_width': {'color': 'white'},
            },
            "ADX": {
                'adx': {'color': 'white'},
                'minus_dm': {'color': 'blue'},
                'plus_dm': {'color': 'red'}
            },
            "rolling": {
                'bb_rolling': {'color': '#87e470'},
                "bb_rolling_min": {'color': '#ac3e2a'}
            }
        }
    }

    def custom_sell(self, pair: str, trade: 'Trade', current_time: 'datetime', current_rate: float,
                    current_profit: float, **kwargs):
        dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)
        last_candle = dataframe.iloc[-1].squeeze()
        previous_last_candle = dataframe.iloc[-2].squeeze()

        if last_candle['percent' + str(self.n_percent.value)] < self.percent_sell.value:
            return 'sell_lost_percent' + str(self.n_percent.value)

        if (last_candle['rsi_1h'] < self.buy_rsi_min_1d.value):
            max_percent = self.max_percent.value
            max_profit = self.max_profit.value
        else:
            if (last_candle['rsi_1h'] < self.buy_rsi_min_1d2.value):
                max_percent = self.max_percent2.value
                max_profit = self.max_profit2.value
            else:
                if (last_candle['rsi_1h'] < self.buy_rsi_min_1d3.value):
                    max_percent = self.max_percent3.value
                    max_profit = self.max_profit3.value
                else:
                    max_percent = self.max_percent4.value
                    max_profit = self.max_profit4.value

        if (current_profit > max_profit) & (
                (last_candle['percent1'] < -max_percent) | (last_candle['percent3'] < -max_percent) | (
                last_candle['percent5'] < -max_percent)):
            return 'h_percent_quick'

        if (current_profit > 0) & (previous_last_candle['rsi'] > self.sell_h_RSI.value):
            return 'h_over_rsi'

        if (current_profit > 0) & (previous_last_candle['rsi'] > self.sell_h_RSI2.value) & \
                (last_candle['percent1'] < - self.sell_h_RSI2_percent.value):
            return 'h_over_rsi_2'

        if (current_profit > 0) & (previous_last_candle['rsi'] > self.sell_h_RSI3.value) & \
                (last_candle['close'] >= last_candle['max200']):
            return 'h_over_rsi_max'

    def informative_pairs(self):
        # get access to all pairs available in whitelist.
        pairs = self.dp.current_whitelist()
        # informative_pairs = [(pair, '1d') for pair in pairs]
        # informative_pairs += [(pair, '4h') for pair in pairs]
        informative_pairs = [(pair, '1h') for pair in pairs]
        return informative_pairs

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['min'] = ta.MIN(dataframe)
        dataframe['max'] = ta.MAX(dataframe)
        dataframe['min200'] = ta.MIN(dataframe['close'], timeperiod=200)
        dataframe['min200_001'] = dataframe['min200'] * self.min_percent.value
        dataframe['min200_002'] = dataframe['min200'] * self.min_percent2.value
        dataframe['min200_003'] = dataframe['min200'] * self.min_percent3.value
        dataframe['min200_004'] = dataframe['min200'] * self.min_percent4.value
        dataframe['max200'] = ta.MAX(dataframe['close'], timeperiod=200)

        dataframe['min_n'] = ta.MIN(dataframe['close'], timeperiod=self.min_n.value * 12)
        dataframe['max_n'] = ta.MAX(dataframe['close'], timeperiod=self.min_n.value * 12)
        dataframe['min_max_n'] = (dataframe['max_n'] - dataframe['min_n']) / dataframe['min_n']
        dataframe['min_n_p'] = dataframe['min_n'] * self.min_p.value

        for n in range(1, 25):
            dataframe["percent" + str(n)] = dataframe['close'].pct_change(n)

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

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

        ################### INFORMATIVE 1h
        informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe="1h")
        informative["rsi"] = ta.RSI(informative)
        informative["rsi3"] = ta.RSI(informative, 3)
        informative['r_rsi'] = (informative['rsi3'].div(10).round())
        # for n in range(1, 5):
        #     informative["percent" + str(n)] = informative['close'].pct_change(n)
        dataframe = merge_informative_pair(dataframe, informative, self.timeframe, "1h", ffill=True)

        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        for decalage in range(self.buy_decalage.value - 2, self.buy_decalage.value):
            conditions = [
                (dataframe['rsi_1h'] < self.buy_rsi_min_1d.value),
                (dataframe['close'].shift(decalage) < dataframe['min200_001'].shift(decalage)),
                (dataframe['min_max_n'] >= self.buy_min_max_n.value),
                (dataframe['rsi_1h'] > self.buy_rsi_min.value),
                (dataframe['rsi_1h'] < self.buy_rsi_max.value),
            ]
            # GUARDS AND TRENDS
            if conditions:
                dataframe.loc[(reduce(lambda x, y: x & y, conditions)),
                ['buy', 'buy_tag']] = (1, 'buy_1_' + str(decalage))
                break

        for decalage in range(self.buy_decalage2.value - 2, self.buy_decalage2.value):
            conditions = [
                (dataframe['rsi_1h'] >= self.buy_rsi_min_1d.value),
                (dataframe['rsi_1h'] < self.buy_rsi_min_1d2.value),
                (dataframe['close'].shift(decalage) < dataframe['min200_002'].shift(decalage)),
                (dataframe['min_max_n'] >= self.buy_min_max_n2.value),
                (dataframe['rsi_1h'] > self.buy_rsi_min.value),
                (dataframe['rsi_1h'] < self.buy_rsi_max.value),
            ]
            # GUARDS AND TRENDS
            if conditions:
                dataframe.loc[(reduce(lambda x, y: x & y, conditions)),
                ['buy', 'buy_tag']] = (1, 'buy_2_' + str(decalage))
                break

        for decalage in range(self.buy_decalage3.value - 2, self.buy_decalage3.value):
            conditions = [
                (dataframe['rsi_1h'] >= self.buy_rsi_min_1d2.value),
                (dataframe['rsi_1h'] < self.buy_rsi_min_1d3.value),
                (dataframe['close'].shift(decalage) < dataframe['min200_003'].shift(decalage)),
                (dataframe['min_max_n'] >= self.buy_min_max_n3.value),
                (dataframe['rsi_1h'] > self.buy_rsi_min.value),
                (dataframe['rsi_1h'] < self.buy_rsi_max.value),
            ]
            # GUARDS AND TRENDS
            if conditions:
                dataframe.loc[(reduce(lambda x, y: x & y, conditions)),
                ['buy', 'buy_tag']] = (1, 'buy_3_' + str(decalage))
                break

        for decalage in range(self.buy_decalage4.value - 2, self.buy_decalage4.value):
            conditions = [
                (dataframe['rsi_1h'] >= self.buy_rsi_min_1d3.value),
                (dataframe['rsi_1h'] < self.buy_rsi_min_1d4.value),
                (dataframe['close'].shift(decalage) < dataframe['min200_004'].shift(decalage)),
                (dataframe['min_max_n'] >= self.buy_min_max_n4.value),
                (dataframe['rsi_1h'] > self.buy_rsi_min.value),
                (dataframe['rsi_1h'] < self.buy_rsi_max.value),
            ]
            # GUARDS AND TRENDS
            if conditions:
                dataframe.loc[(reduce(lambda x, y: x & y, conditions)),
                ['buy', 'buy_tag']] = (1, 'buy_4_' + str(decalage))
                break

        return dataframe

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