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

import numpy as np  # noqa
import pandas as pd  # noqa
from freqtrade.strategy.parameters import  DecimalParameter
from pandas import DataFrame

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 StrategyPierrick2(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


    # ROI table:
    minimal_roi = {
        "0": 1,
        # "600": 0.12,
        # "1200": 0.08,
        # "2400": 0.06,
        # "3600": 0.04,
        # "7289": 0
    }

    # Stoploss:
    stoploss = -1
    # Buy hypers
    timeframe = '4h'

    # Trailing stoploss
    trailing_stop = False
    trailing_stop_positive = 0.15
    trailing_stop_positive_offset = 0.20
    trailing_only_offset_is_reached = True


    plot_config = {
        # Main plot indicators (Moving averages, ...)
        'main_plot': {
            'bb_lowerband': {'color': 'white'},
            'bb_upperband': {'color': 'white'},
        },
        'subplots': {
            # Subplots - each dict defines one additional plot
            "BB": {
                'bb_width': {'color': 'white'},
            },
            "Aaron": {
                'aroonup': {'color': 'blue'},
                'aroondown': {'color': 'red'}
            }
        }
    }

    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()
        previous_5_candle = dataframe.iloc[-5].squeeze()
        #print("last_candle", last_candle)
        #print("previous_last_candle", previous_last_candle)

        count = 0
        for coin, balance in self.wallets.get_all_balances().items():
            count = count + 1
        #     print(coin, " ", balance)
        # print("count=", count)

        # (last_candle['percent5'] < -0.005) \
        # if (0 < current_profit < 0.005) \
        #         & ((current_time - trade.open_date_utc).seconds >= 3600 * 2):
        #     # & (previous_last_candle['sma10'] > last_candle['sma10']):
        #     print("too_small_gain", pair, trade, " profit=", current_profit, " rate=", current_rate, " percent5=",
        #           last_candle['percent5'])
        #     return 'too_small_gain'

        # if (current_profit < -0.05) \
        #         & ((current_time - trade.open_date_utc).days >= 3):
        #     print("lost_half_profit", pair, trade, " profit=", current_profit, " rate=", current_rate)
        #     return 'stop_loss_profit'

        # if (current_profit > 0.02) \
        #         & (last_candle['percent'] < 0.01) \
        #         & ((current_time - trade.open_date_utc).seconds >= 3600):
        #     print("lost_half_profit", pair, trade, " profit=", current_profit, " rate=", current_rate)
        #     return 'lost_half_profit'

        # ((current_time - trade.open_date_utc).seconds >= 3600 * 2) \
        if (current_profit > 0) \
                & (previous_5_candle['sma10'] > last_candle['sma10'] * 1.005) \
                & ((last_candle['percent'] < 0) & (last_candle['percent3'] < - (current_profit / 4))):
            # print("over_bb_band_sma10_desc", pair, trade, " profit=", current_profit, " rate=", current_rate)
            return 'over_bb_band_sma10_desc'

        # if (current_profit > 0) \
        #         & (last_candle['percent'] < -0.02):
        #     # print("over_bb_band_sma10_desc", pair, trade, " profit=", current_profit, " rate=", current_rate)
        #     return 'stop_percent_loss'

        #if (current_profit > 0) \
        #        & ((current_time - trade.open_date_utc).seconds >= 3600 * 2) \
        #        & (previous_last_candle['sma20'] > last_candle['sma20']) \
        #        & (last_candle['percent'] < 0):
        #    print("over_bb_band_sma20_desc", pair, trade, " profit=", current_profit, " rate=", current_rate)
        #    return 'over_bb_band_sma20_desc'

        if (current_profit > 0) \
                & (last_candle['rsi'] > 88): #| (previous_last_candle['rsi'] > 75 & last_candle['rsi'] < 70)):
            # print("over_rsi", pair, trade, " profit=", current_profit, " rate=", current_rate)
            return 'over_rsi'

        # description trade
        # Trade(id=0, pair=CAKE/USDT, amount=4.19815281, open_rate=11.91000000, open_since=2021-12-22 17:55:00)
        # print(last_candle)
        # if 0.05 < current_profit < 1:
        #     if (
        #             (previous_last_candle['sma10'] > last_candle['sma10'] * 1.005) &
        #             (current_time - trade.open_date_utc).seconds >= 3600 * 3
        #     # ) | (
        #     #         (current_time - trade.open_date_utc).seconds >= 3600 * 6
        #     ):
        #         # self.lock_pair(pair, until=current_time + timedelta(hours=3))
        #
        #         print("profit_3h_sma10_desc", pair, trade, " profit=", current_profit, " rate=", current_rate)
        #         return 'profit_3h_sma10_desc'
        #
        # if (0 < current_profit < 0.1) \
        #         & (previous_last_candle['sma20'] > last_candle['sma20']) \
        #         & ((current_time - trade.open_date_utc).seconds >= 3600 * 5):
        #     print("profit_5h_sma20_desc", pair, trade, " profit=", current_profit, " rate=", current_rate)
        #     return 'profit_5h_sma20_desc'

        # if (count == self.config['max_open_trades']) & (current_profit < -0.04) \
        #         & ((current_time - trade.open_date_utc).seconds >= 3600 * 6):
        #     self.lock_pair(pair, until=current_time + timedelta(hours=10))
        #     print("stop_short_loss", pair, trade, " profit=", current_profit, " rate=", current_rate,
        #           "count=", count, "max=", self.config['max_open_trades'])
        #     return 'stop_short_loss'


    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)

        # # 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['sma20'] = ta.SMA(dataframe, timeperiod=20)
        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
        dataframe["percent"] = (dataframe["close"] - dataframe["open"]) / dataframe["open"]
        dataframe["percent5"] = dataframe["percent"].rolling(5).sum()
        dataframe["percent3"] = dataframe["percent"].rolling(3).sum()
        dataframe["percent20"] = dataframe["percent"].rolling(20).sum()
        dataframe['min'] = ta.MIN(dataframe['close'], timeperiod=200)
        dataframe['min20'] = ta.MIN(dataframe['close'], timeperiod=20)

        dataframe['max'] = ta.MAX(dataframe['close'], timeperiod=200)
        dataframe['max_min'] = dataframe['max'] / dataframe['min']
        # 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['bb_min'] = ta.MIN(dataframe['bb_lowerband'], timeperiod=36)

        # Bollinger Bands - Weighted (EMA based instead of SMA)
        weighted_bollinger = qtpylib.weighted_bollinger_bands(
            qtpylib.typical_price(dataframe), window=20, stds=2
        )
        dataframe["wbb_upperband"] = weighted_bollinger["upper"]
        dataframe["wbb_lowerband"] = weighted_bollinger["lower"]
        dataframe["wbb_middleband"] = weighted_bollinger["mid"]
        dataframe["wbb_percent"] = (
            (dataframe["close"] - dataframe["wbb_lowerband"]) /
            (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"])
        )
        dataframe["wbb_width"] = (
            (dataframe["wbb_upperband"] - dataframe["wbb_lowerband"]) / dataframe["wbb_middleband"]
        )

        # # EMA - Exponential Moving Average
        # dataframe['ema3'] = ta.EMA(dataframe, timeperiod=3)
        return dataframe

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

        dataframe.loc[
            (
                (
                    (dataframe['close'] < dataframe['bb_lowerband'])
                    & (dataframe['bb_width'] >= 0.065)
                    #& (dataframe['rsi'] < 45)
                    & (dataframe['volume'] * dataframe['close'] / 1000 >= 100)
                )
            ),
            'buy'] = 1
        return dataframe

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

        dataframe.loc[
            (

            ),

            'sell'] = 1
        return dataframe

