# --- Do not remove these libs ---

from functools import reduce
from freqtrade.strategy import IStrategy, stoploss_from_open
import freqtrade.vendor.qtpylib.indicators as qtpylib
from freqtrade.persistence import Trade
from datetime import datetime, timedelta
from pandas import DataFrame
# --------------------------------

import talib.abstract as ta

class ShaneHolds_MyCSL_V2_BS_20211011(IStrategy):
    # ROI table:
    minimal_roi = {
        "0": 100.0,
    }
    timeframe = '15m'

    # Stoploss
    stoploss = -0.20
    startup_candle_count: int = 480
    trailing_stop = False
    use_custom_stoploss = True
    use_sell_signal = False

    # Indicator values:
    ema_xs = 3
    ema_sm = 5
    ema_md = 10
    ema_xl = 50
    ema_xxl = 200

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

        # Adding EMA's into the dataframe
        dataframe['ema_xs'] = ta.EMA(dataframe, timeperiod=self.ema_xs)
        dataframe['ema_sm'] = ta.EMA(dataframe, timeperiod=self.ema_sm)
        dataframe['ema_md'] = ta.EMA(dataframe, timeperiod=self.ema_md)
        dataframe['ema_xl'] = ta.EMA(dataframe, timeperiod=self.ema_xl)
        dataframe['ema_xxl'] = ta.EMA(dataframe, timeperiod=self.ema_xxl)

        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # basic buy methods to keep the strategy complex
        conditions = [
            (dataframe['close'] < dataframe['ema_xxl']),
            (qtpylib.crossed_above(dataframe['ema_sm'], dataframe['ema_md'])),
            (dataframe['ema_xs'] < dataframe['ema_xl']),
            (dataframe['volume'] > 0),
        ]
        dataframe.loc[reduce(lambda x, y: x & y, conditions), "buy"] = 1
        return dataframe

        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        # This is essentailly ignored as we're using strict ROI / Stoploss / TTP sale scenarios
        dataframe.loc[(), "sell"] = 0
        return dataframe

    def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
                        current_rate: float, current_profit: float, **kwargs) -> float:
        if (current_profit > 0.2):
            return stoploss_from_open(0.05, current_profit)
        elif (current_profit > 0.1):
            return stoploss_from_open(0.03, current_profit)
        elif (current_profit > 0.06):
            return stoploss_from_open(0.02, current_profit)
        elif (current_profit > 0.03):
            return stoploss_from_open(0.01, current_profit)

        return stoploss_from_open(-0.20, current_profit)
