
# --- Do not remove these libs ---
from freqtrade.strategy.interface import IStrategy
from typing import Dict, List
from functools import reduce
from pandas import DataFrame
# --------------------------------
import numpy as np
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
from scipy.signal import argrelextrema
from freqtrade.strategy import stoploss_from_open, merge_informative_pair, DecimalParameter, IntParameter, CategoricalParameter, stoploss_from_open
from datetime import datetime, timedelta
from freqtrade.persistence import Trade
import pandas_ta as pd
import freqtrade.vendor.qtpylib.indicators as qtpylib

class rsiDivexperimental(IStrategy):

    timeframe = '5m'
    inf_1h = '1h'
    use_sell_signal = True
    sell_profit_only = False
    ignore_roi_if_buy_signal = False
    process_only_new_candles = True
    startup_candle_count = 30
    # ROI
    minimal_roi = {
        "0": 0.20,
        "1":0.10,         # I feel lucky!
        "5": 0.05,
        "60": 0.01,
        "150": 0.005
    }
    # Stoploss
    stoploss = -0.1
    trailing_stop = False
    trailing_stop_positive = 0.32234
    trailing_stop_positive_offset = 0.40815
    trailing_only_offset_is_reached = False
    use_custom_stoploss = True


    # trailing stoploss hyperopt parameters
    # hard stoploss profit


    plot_config = {
        'main_plot': {
            
            'close': {'color': 'yellow'},
            

        },
        'subplots': {

            "rsi_bull_div":{
                'rsi_bull_div': {'color': 'black'},
            },
            "rsi_bull_hidden_div": {
                'rsi_bull_div': {'color': 'orange'}
            },
            'rsi_fast': {
                'rsi_fast': {'color': 'blue'}
                # 'rsi_value_minima': {'color': 'green'}
            }

        }
    }


    # aligns with this trading view indicator - https://uk.tradingview.com/v/b2aAujaw/
    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        max_lookback = 5
        min_lookback = 5

        dataframe['rsi_fast'] = ta.RSI(dataframe, timeperiod=7)
        max_peak = argrelextrema(dataframe['rsi_fast'].values, np.greater, order=max_lookback)[0]
        min_peak = argrelextrema(dataframe['rsi_fast'].values, np.less, order=min_lookback)[0]

        dataframe.loc[max_peak,"max_peak",] = 1
        dataframe.loc[min_peak,"min_peak",] = 1
        
        dataframe["max_peak"] = dataframe["max_peak"].map({1: True, np.nan: False})
        dataframe["min_peak"] = dataframe["min_peak"].map({1: True, np.nan: False})

        dataframe["rsi_max_peak"] = dataframe['rsi_fast'].iloc[max_peak]
        rsi_value_min_peak = dataframe['rsi_fast'].iloc[min_peak]

        dataframe["close_max_peak"] = dataframe["close"].iloc[max_peak]
        close_value_min_peak = dataframe["close"].iloc[min_peak]

        dataframe["rsi_max_peak"] = dataframe["rsi_max_peak"].ffill(axis=0)
        rsi_value_min_peak = rsi_value_min_peak.ffill(axis=0)

        dataframe["close_max_peak"] = dataframe["close_max_peak"].ffill(axis=0)
        close_value_min_peak = close_value_min_peak.ffill(axis=0)

        dataframe["rsi_max_peak"] = dataframe["rsi_max_peak"].diff()
        rsi_value_min_peak = rsi_value_min_peak.diff()

        dataframe["close_max_peak"] = dataframe["close_max_peak"].diff()
        close_value_min_peak = close_value_min_peak.diff()

        dataframe["rsi_bull_div"] = ((rsi_value_min_peak > 0) & (
            close_value_min_peak < 0)).astype("int")

        dataframe["rsi_bull_hidden_div"] = ((rsi_value_min_peak < 0) & (
            close_value_min_peak > 0)).astype("int")
        # #print(dataframe)


        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['rsi'] = ta.RSI(dataframe, timeperiod=14)

        return dataframe

    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        conditions = []

        conditions.append(
            (
                (dataframe["rsi_bull_div"]>0) | (dataframe["rsi_bull_hidden_div"]>0)
            )
        )

        if conditions:
            dataframe.loc[
                reduce(lambda x, y: x | y, conditions),
                'buy'
        ]=1
        return dataframe

    def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
               
            ),
            'sell'] = 0
        return dataframe

