# 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


# This class is a sample. Feel free to customize it.
class StrategyJD(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=1, space="buy")

    # buy_rsi = IntParameter(20, 40, default=30, space="buy")
    # 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'},
            'sma100': {'color': 'green'},
            'sma500': {'color': 'blue'},
            'sma200_98': {'color': 'yellow'},
            'sma200_95': {'color': 'cyan'},
            'rsi': {'color': '#c58893'}

        },
        '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()
    #
    #     # Above 20% profit, sell when rsi < 80
    #     if current_profit > 0.2:
    #         if last_candle['rsi'] < 80:
    #             return 'rsi_below_80'
    #
    #     # Between 2% and 10%, sell if EMA-long above EMA-short
    #     if 0.02 < current_profit < 0.1:
    #         if last_candle['ema100'] > last_candle['ema10']:
    #             return 'ema_long_below_80'
    #
    #     # Sell any positions at a loss if they are held for more than one day.
    #     if current_profit < -0.20 and (current_time - trade.open_date_utc).days >= 3:
    #         return 'unclog'

    # def custom_stake_amount(self, pair: str, current_time: datetime, current_rate: float,
    #                         proposed_stake: float, min_stake: float, max_stake: float,
    #                         **kwargs) -> float:
    #
    #     dataframe, _ = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)
    #     current_candle = dataframe.iloc[-1].squeeze()
    #
    #     if dataframe['open'] < dataframe['sma100'] * 0.98:
    #         # if self.config['stake_amount'] == 'unlimited':
    #         #     # Use entire available wallet during favorable conditions when in compounding mode.
    #         #     return max_stake
    #         # else:
    #         # Compound profits during favorable conditions instead of using a static stake.
    #         return self.wallets.get_total_stake_amount() / self.config['max_open_trades']
    #
    #     # Use default stake amount.
    #     return proposed_stake

    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['adx'] = ta.ADX(dataframe)
        # dataframe['minus_dm'] = ta.MINUS_DM(dataframe)
        # dataframe['minus_di'] = ta.MINUS_DI(dataframe)

        dataframe['min'] = ta.MIN(dataframe)
        dataframe['max'] = ta.MAX(dataframe)
        dataframe['min50'] = ta.MIN(dataframe['close'], timeperiod=50)
        dataframe['min200'] = ta.MIN(dataframe['close'], timeperiod=200)

        dataframe['max50'] = ta.MAX(dataframe['close'], timeperiod=50)
        dataframe['max200'] = ta.MAX(dataframe['close'], timeperiod=200)
        # # 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['mema10_3'] = dataframe['ema10'] / dataframe['ema10'].shift(1)
        # dataframe['mema10_5'] = dataframe['ema10'].rolling(5).mean()

        # 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['msma10_3'] = dataframe['sma10'] / dataframe['sma10'].shift(1)

        # 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["rolling"] = (100 * (dataframe["close"] - dataframe["bb_lowerband"]) / dataframe["bb_lowerband"]).rolling(5).mean()
        # dataframe["bb_rolling"] = dataframe["rolling"] / dataframe["bb_width"]
        # dataframe['bb_rolling_min'] = ta.MIN(dataframe['bb_rolling'], timeperiod=5)

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

        for decalage in range(self.buy_decalage.value - 2, self.buy_decalage.value):
            conditions = [
                (dataframe['bb_width'].shift(decalage) >= self.buy_bollinger.value),
                # (dataframe['close'].shift(decalage) < dataframe['bb_lowerband'].shift(decalage)),
                (dataframe['close'].shift(decalage) < dataframe['sma10'].shift(decalage)),
                (dataframe['msma10_3'] > 0.998)
            ]
            # GUARDS AND TRENDS

            if conditions:
                dataframe.loc[
                    (
                        (reduce(lambda x, y: x & y, conditions))
                    )
                    ,
                    ['buy', 'buy_tag']] = (1, 'buy_msma_' + str(decalage))
                break
        return dataframe

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