# source: https://raw.githubusercontent.com/rmallarapu-bc/brahma/9287745fc036c2f4c00c586e598290885c2883b9/archive/Anasuya.py
# --- Do not remove these libs ---
from typing import Optional

from pandas import DataFrame
import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
from datetime import datetime
from freqtrade.persistence import Trade
from freqtrade.strategy import DecimalParameter, IntParameter, IStrategy, merge_informative_pair
from functools import reduce
import logging
import warnings
import pandas as pd

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning)


# --------------------------------


class Github_rmallarapu_bc_brahma__Anasuya__20240229_213751(IStrategy):
    INTERFACE_VERSION: int = 3
    can_short = True

    # Sell signal
    use_exit_signal = False
    exit_profit_only = False
    ignore_roi_if_entry_signal = True

    # ROI table:
    minimal_roi = {"0": 0.05}

    # Stoploss:
    stoploss = -0.01

    # Trailing stop:
    trailing_stop = True
    trailing_stop_positive = 0.001
    trailing_stop_positive_offset = 0.005
    trailing_only_offset_is_reached = True

    timeframe = '1h'
    # informative_timeframe = '15m'
    informative_timeframe = '1w'

    # Strategy parameters
    rsi_length = IntParameter(10, 40, default=14, space="buy")
    bb_window = IntParameter(10, 40, default=17, space="buy")
    bb_std = IntParameter(1, 6, default=1, space="buy")
    buy_rsi = IntParameter(10, 40, default=42, space="buy")
    sell_rsi = IntParameter(60, 90, default=76, space="sell")

    buy_params = {"buy_limit": 0.943}
    buy_limit = DecimalParameter(0.90, 0.98, default=0.98, space='buy', decimals=3, optimize=True, load=True)



    process_only_new_candles = False
    startup_candle_count = 10
    use_custom_stoploss = False

    def informative_pairs(self):
        pairs = self.dp.current_whitelist()
        informative_pairs = [(pair, self.informative_timeframe) for pair in pairs]
        return informative_pairs

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        pairs = self.dp.current_whitelist()[0] # Take the first pair
        informative = self.dp.get_pair_dataframe(pair=pairs, timeframe=self.informative_timeframe)
        # calculate SMA20 on informative pair
        informative['sma20'] = informative['close'].rolling(20).mean()

        # Combine the 2 dataframe
        # This will result in a column named 'closeETH' or 'closeBTC' - depending on stake_currency.
        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=self.rsi_length.value)

        # TEMA - Triple Exponential Moving Average
        dataframe["tema"] = ta.TEMA(dataframe, timeperiod=9)

        # Bollinger bands
        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=self.bb_window.value,
                                            stds=self.bb_std.value)
        dataframe['bb_lowerband'] = bollinger['lower']
        dataframe['bb_middleband'] = bollinger['mid']
        dataframe['bb_upperband'] = bollinger['upper']

        dataframe['ema20'] = ta.EMA(dataframe, timeperiod=20)
        dataframe['ema50'] = ta.EMA(dataframe, timeperiod=50)
        dataframe['ema100'] = ta.EMA(dataframe, timeperiod=100)

        dataframe = merge_informative_pair(dataframe, informative,
                                           self.timeframe, self.informative_timeframe, ffill=True)

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                    (dataframe['ema20'] > dataframe['ema50']) &
                    # (dataframe['close_15m'] > dataframe['sma20_15m']) &
                    (dataframe['close_1w'] > dataframe['sma20_1w']) &
                    (dataframe['rsi'] < self.buy_rsi.value) &
                    (dataframe['close'] < dataframe['bb_lowerband'])

            ),
            'enter_long'] = 0
        dataframe.loc[
            (
                    (dataframe['ema20'] < dataframe['ema50']) &
                    (dataframe['ema50'] < dataframe['ema100']) &
                    (dataframe['close_1w'] < dataframe['sma20_1w']) #&
                    # (dataframe['close'] > self.buy_limit.value * dataframe['bb_middleband']) #&
                    # (qtpylib.crossed_above(dataframe["rsi"], self.sell_rsi.value)) &
                    # (dataframe["tema"] > dataframe["bb_upperband"])
                    # (dataframe['close'] > dataframe['bb_upperband'])

            ),
            'enter_short'] = 1
        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                    # (dataframe['rsi'] > self.sell_rsi.value) &
                    (dataframe['close'] > dataframe['bb_upperband'])

            ),
            'exit_long'] = 1
        dataframe.loc[
            (
                    # (dataframe['rsi'] < self.buy_rsi.value) &
                    (dataframe['close'] < dataframe['bb_lowerband'])

            ),
            'exit_short'] = 1

        return dataframe


