# source: https://raw.githubusercontent.com/rmallarapu-bc/brahma/9287745fc036c2f4c00c586e598290885c2883b9/archive/Sushila.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
from functools import reduce
import logging
import warnings
import pandas as pd
import requests

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

from datetime import datetime, time





class Github_rmallarapu_bc_brahma__Sushila__20240229_213751(IStrategy):
    INTERFACE_VERSION: int = 3
    minimal_roi = {"0": 1.0}

    can_short = True

    # Exit criteria
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = True

    # # Trailing stoploss
    # trailing_stop = True
    # trailing_stop_positive = 0.01
    # trailing_stop_positive_offset = 0.10
    # trailing_only_offset_is_reached = True

    stoploss = -0.30
    timeframe = '5m'

    position_adjustment_enable = True
    max_entry_position_adjustment = 10

    fear_index_long = IntParameter(1, 6, default=2, space="buy")
    fear_index_short = IntParameter(1, 6, default=4, space="sell")

    feardf = pd.DataFrame()

    def fear_index(self, dataframe, feardf):
        prev_resp = {
            "name": "Fear and Greed Index",
            "data": [
                {
                    "value": "3",
                    "value_classification": "Neutral",
                    "timestamp": str(datetime.today()),
                }
            ]
        }

        if feardf.empty:
            resp = requests.get('https://api.alternative.me/fng/?limit=9999&date_format=kr')
        else:
            if datetime.today() in feardf['date'].values:
                return feardf['value_classification']
            else:
                resp = requests.get('https://api.alternative.me/fng/?limit=1&date_format=kr')

        if resp is not None and resp.headers.get('Content-Type').startswith('application/json'):
            try:
                self.prev_resp = resp.json()
                df_gf = self.prev_resp['data']
            except:
                self.prev_resp = prev_resp
                df_gf = self.prev_resp['data']
        else:
            self.prev_resp = prev_resp
            df_gf = self.prev_resp['data']

        fear = pd.json_normalize(df_gf)
        fear.rename(columns={'value': 'fear'}, inplace=True)
        fear.rename(columns={'timestamp': 'date'}, inplace=True)

        fear['value_classification'] = fear['value_classification'].replace('Extreme Fear', 5)
        fear['value_classification'] = fear['value_classification'].replace('Fear', 4)
        fear['value_classification'] = fear['value_classification'].replace('Neutral', 3)
        fear['value_classification'] = fear['value_classification'].replace('Greed', 2)
        fear['value_classification'] = fear['value_classification'].replace('Extreme Greed', 1)

        df_copy = dataframe[['date']].copy()
        df_copy["date"] = pd.to_datetime(df_copy["date"], unit='ms')
        df_copy['date'] = df_copy['date'].astype(str)
        df_copy['date'] = df_copy['date'].str[:10]
        feardf = pd.merge(df_copy, fear, on='date')

        return feardf['value_classification']

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe['fear_index'] = self.fear_index(dataframe, self.feardf)
        log.info(dataframe['fear_index'].nunique())
        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        log.info(dataframe['fear_index'].nunique())
        dataframe.loc[
            (
                (dataframe['fear_index'] == self.fear_index_long.value) #&
                # (dataframe['fear_index'] > 1)
                # (dataframe['fear_index'].between(0, 4, inclusive='both').any())

                # &
                # (dataframe['date'].dt.hour == 0)
            ),
            'enter_long'] = 0

        dataframe.loc[
            (
                (dataframe['fear_index'] == self.fear_index_short.value) #&
                # (dataframe['fear_index'] <= 5)
                # (dataframe['fear_index'].between(0, 4, inclusive='both').any())

                # &
                # (dataframe['date'].dt.hour == 0)
            ),
            'enter_short'] = 1

        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        dataframe.loc[
            (
                # (dataframe['fear_index'].between(3, 6, inclusive='both').any())
                # (dataframe['fear_index'].between(4, 5).any()) 
                (dataframe['fear_index'] == self.fear_index_short.value) #&
                # (dataframe['fear_index'] <= 5)
                # &
                # (dataframe['date'].dt.hour == 23)
            ),
            'exit_long'] = 1

        dataframe.loc[
            (
                # (dataframe['fear_index'].between(3, 6, inclusive='both').any())
                # (dataframe['fear_index'].between(4, 5).any()) 
                (dataframe['fear_index'] == self.fear_index_long.value) #&
                # (dataframe['fear_index'] > 1)
                # &
                # (dataframe['date'].dt.hour == 23)
            ),
            'exit_short'] = 1

        return dataframe
