# source: https://raw.githubusercontent.com/arpanvyas/freqtrade_turtle/5a7b303b7e98a44fed39300d0aca36b9f67e3e63/Feb2023/TurtleTrader_273x.py
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement
# flake8: noqa: F401

# --- Do not remove these libs ---
import numpy as np  # noqa
import pandas as pd  # noqa
from pandas import DataFrame  # noqa
from datetime import datetime  # noqa
from typing import Optional, Union  # noqa

from freqtrade.strategy import (BooleanParameter, CategoricalParameter, DecimalParameter,
                                IStrategy, IntParameter)

# --------------------------------
# Add your lib to import here
import talib.abstract as ta
import pandas_ta as pta
import freqtrade.vendor.qtpylib.indicators as qtpylib
from freqtrade.persistence import Trade
import os

class Github_arpanvyas_freqtrade_turtle__TurtleTrader_273x__20250530_210658(IStrategy):
    ########################################################################
    ##  Achieves 273x profit from 1/1/18-1/31/23 with ETH/USDT
    ########################################################################
    """
    This is a strategy template to get you started.
    More information in https://www.freqtrade.io/en/latest/strategy-customization/

    You can:
        :return: a Dataframe with all mandatory indicators for the strategies
    - Rename the class name (Do not forget to update class_name)
    - Add any methods you want to build your strategy
    - Add any lib you need to build your strategy

    You must keep:
    - the lib in the section "Do not remove these libs"
    - the methods: populate_indicators, populate_entry_trend, populate_exit_trend
    You should keep:
    - timeframe, minimal_roi, stoploss, trailing_*
    """
    # Strategy interface version - allow new iterations of the strategy interface.
    # Check the documentation or the Sample strategy to get the latest version.
    INTERFACE_VERSION = 3

    # Optimal timeframe for the strategy.
    timeframe = '5m'

    # Can this strategy go short?
    can_short: bool = True
    #can_short: bool = False

    # Minimal ROI designed for the strategy.
    # This attribute will be overridden if the config file contains "minimal_roi".
    # Disabled by setting a very high value 1000,00%
    minimal_roi = {
        "0": 1000
    }

    # Optimal stoploss designed for the strategy.
    # This attribute will be overridden if the config file contains "stoploss".
    #stoploss = -0.002
    stoploss = -0.02
    #stoploss = -0.1

    # Trailing stoploss
    trailing_stop = False
    # trailing_only_offset_is_reached = False
    # trailing_stop_positive = 0.01
    # trailing_stop_positive_offset = 0.0  # Disabled / not configured

    # Run "populate_indicators()" only for new candle.
    process_only_new_candles = True

    # These values can be overridden in the config.
    use_exit_signal = True
    exit_profit_only = False
    ignore_roi_if_entry_signal = False

    # Number of candles the strategy requires before producing valid signals
    startup_candle_count: int = 30


    # Optional order type mapping.
    order_types = {
        'entry': 'limit',
        'exit': 'limit',
        'stoploss': 'market',
        'stoploss_on_exchange': False
    }

    # Optional order time in force.
    order_time_in_force = {
        'entry': 'gtc',
        'exit': 'gtc'
    }
    
    use_exit_signal = True

    n_entry = 0
    n_exit = 0

    win_loss = 0
    S1_nS2 = 1

    #use_custom_stoploss = True

    #def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime,
    #                    current_rate: float, current_profit: float, **kwargs) -> float:

    #    candle = dataframe.iloc[-1].squeeze()

    #    if(trade.is_short):
    #        candle = dataframe.loc[(dataframe['enter_short'] == 1)].tail(1).squeeze()
    #    else:
    #        candle = dataframe.loc[(dataframe['enter_long'] == 1)].tail(1).squeeze()
    #        
    #    
    #    return stoploss_from_open( (candle['atr'] * (-2))/candle['close'], current_profit, is_short=trade.is_short)
    
    @property
    def plot_config(self):
        return {
            # Main plot indicators (Moving averages, ...)
            'main_plot': {
                'tema': {},
                'sar': {'color': 'white'},
            },
            'subplots': {
                # Subplots - each dict defines one additional plot
                "MACD": {
                    'macd': {'color': 'blue'},
                    'macdsignal': {'color': 'orange'},
                },
                "RSI": {
                    'rsi': {'color': 'red'},
                }
            }
        }

    def informative_pairs(self):
        """
        Define additional, informative pair/interval combinations to be cached from the exchange.
        These pair/interval combinations are non-tradeable, unless they are part
        of the whitelist as well.
        For more information, please consult the documentation
        :return: List of tuples in the format (pair, interval)
            Sample: return [("ETH/USDT", "5m"),
                            ("BTC/USDT", "15m"),
                            ]
        """
        return []

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Adds several different TA indicators to the given DataFrame

        Performance Note: For the best performance be frugal on the number of indicators
        you are using. Let uncomment only the indicator you are using in your strategies
        or your hyperopt configuration, otherwise you will waste your memory and CPU usage.
        :param dataframe: Dataframe with data from the exchange
        :param metadata: Additional information, like the currently traded pair
        :return: a Dataframe with all mandatory indicators for the strategies
        """
        
        # Momentum Indicators
        # ------------------------------------

        mult = 288

        #same-same
        S1_big = 7 * mult
        S1_small = 2 * mult + 144  

        S2_big = 8 * mult
        S2_small = 2 * mult + 144  

        #5-day multiples
        #S1_big = 20 * mult
        #S1_small = 10 * mult

        #S2_big = 55 * mult
        #S2_small = 20 * mult

        ##week multiples
        #S1_big = 28 * mult
        #S1_small = 14 * mult

        #S2_big = 77 * mult
        #S2_small = 28 * mult

        ##long
        #S1_big = 44 * mult
        #S1_small = 22 * mult

        #S2_big = 99 * mult
        #S2_small = 22 * mult

        ##longer
        #S1_big = 56 * mult
        #S1_small = 28 * mult

        #S2_big = 130 * mult
        #S2_small = 56 * mult

        # ADX
        #dataframe['adx'] = ta.ADX(dataframe)

        # ATR
        dataframe['atr'] = ta.ATR(dataframe)

        # ATR Ratio
        dataframe['atr_ratio'] = dataframe['atr']/dataframe['close']

        # Breakouts

        ## S1 Breakouts
        ### S1 Long
        dataframe["S1_big_high"] = dataframe.close.rolling(S1_big).max()
        dataframe["S1_small_low"] = dataframe.close.rolling(S1_small).min()
        dataframe.loc[(dataframe['S1_big_high'] == dataframe['close']),'S1_big_high_this'] = 1
        dataframe.loc[(dataframe['S1_small_low'] == dataframe['close']),'S1_small_low_this'] = 1

        ### S1 Short
        dataframe["S1_big_low"] = dataframe.close.rolling(S1_big).min()
        dataframe["S1_small_high"] = dataframe.close.rolling(S1_small).max()
        dataframe.loc[(dataframe['S1_big_low'] == dataframe['close']),'S1_big_low_this'] = 1
        dataframe.loc[(dataframe['S1_small_high'] == dataframe['close']),'S1_small_high_this'] = 1


        ## S2 Breakouts
        ### S2 Long
        dataframe["S2_big_high"] = dataframe.close.rolling(S2_big).max()
        dataframe["S2_small_low"] = dataframe.close.rolling(S2_small).min()
        dataframe.loc[(dataframe['S2_big_high'] == dataframe['close']),'S2_big_high_this'] = 1
        dataframe.loc[(dataframe['S2_small_low'] == dataframe['close']),'S2_small_low_this'] = 1

        ### S2 Short
        dataframe["S2_big_low"] = dataframe.close.rolling(S2_big).min()
        dataframe["S2_small_high"] = dataframe.close.rolling(S2_small).max()
        dataframe.loc[(dataframe['S2_big_low'] == dataframe['close']),'S2_big_low_this'] = 1
        dataframe.loc[(dataframe['S2_small_high'] == dataframe['close']),'S2_small_high_this'] = 1

        """
        # first check if dataprovider is available
        if self.dp:
            if self.dp.runmode.value in ('live', 'dry_run'):
                ob = self.dp.orderbook(metadata['pair'], 1)
                dataframe['best_bid'] = ob['bids'][0][0]
                dataframe['best_ask'] = ob['asks'][0][0]
        """

        return dataframe

    def populate_entry_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the entry signal for the given dataframe
        :param dataframe: DataFrame
        :param metadata: Additional information, like the currently traded pair
        :return: DataFrame with entry columns populated
        """

        #S1 entries
        dataframe.loc[
            ( dataframe['S1_big_high_this'] == 1 ),
            'enter_long'] = 1
        dataframe.loc[
            ( dataframe['S1_big_low_this'] == 1 ),
            'enter_short'] = 1

        #S2 entries
        dataframe.loc[
            ( dataframe['S2_big_high_this'] == 1 ),
            'enter_long'] = 1
        dataframe.loc[
            ( dataframe['S2_big_low_this'] == 1 ),
            'enter_short'] = 1


        return dataframe

    def populate_exit_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """
        Based on TA indicators, populates the exit signal for the given dataframe
        :param dataframe: DataFrame
        :param metadata: Additional information, like the currently traded pair
        :return: DataFrame with exit columns populated
        """

        #S1 exits
        dataframe.loc[
            ( dataframe['S1_small_low_this'] == 1 ),
            'exit_long'] = 1
        dataframe.loc[
            ( dataframe['S1_small_high_this'] == 1 ),
            'exit_short'] = 1
        
        #S2 exits
        dataframe.loc[
            ( dataframe['S2_small_low_this'] == 1 ),
            'exit_long'] = 1
        dataframe.loc[
            ( dataframe['S2_small_high_this'] == 1 ),
            'exit_short'] = 1


        return dataframe

    def confirm_trade_entry(self, pair: str, order_type: str, amount: float, rate: float,
                            time_in_force: str, current_time: datetime, entry_tag: Optional[str],
                            side: str, **kwargs) -> bool:
        """
        Called right before placing a entry order.
        Timing for this function is critical, so avoid doing heavy computations or
        network requests in this method.

        For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/

        When not implemented by a strategy, returns True (always confirming).

        :param pair: Pair that's about to be bought/shorted.
        :param order_type: Order type (as configured in order_types). usually limit or market.
        :param amount: Amount in target (base) currency that's going to be traded.
        :param rate: Rate that's going to be used when using limit orders 
                     or current rate for market orders.
        :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
        :param current_time: datetime object, containing the current datetime
        :param entry_tag: Optional entry_tag (buy_tag) if provided with the buy signal.
        :param side: 'long' or 'short' - indicating the direction of the proposed trade
        :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
        :return bool: When True is returned, then the buy-order is placed on the exchange.
            False aborts the process
        """
        retval = False
        
        dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)

        if(self.win_loss == 0):
            self.S1_nS2 = 1
        else:
            self.S1_nS2 = 0

        if(side == 'long'):
            if((self.S1_nS2 == 1) and (dataframe.iloc[-1]['S1_big_high_this'] == 1)):
                retval = True
            elif((self.S1_nS2 == 0) and (dataframe.iloc[-1]['S2_big_high_this'] == 1)):
                retval = True
        else:
            if((self.S1_nS2 == 1) and (dataframe.iloc[-1]['S1_big_low_this'] == 1)):
                retval = True
            elif((self.S1_nS2 == 0) and (dataframe.iloc[-1]['S2_big_low_this'] == 1)):
                retval = True

        if(retval):
            print("Entry number: ",self.n_entry)
            print("Last exit was: ",self.win_loss)
            print("Trade direction is: ",side)

            self.n_entry = self.n_entry + 1

            if(self.S1_nS2 == 1):
                print("Using S1 Entry")
            else:
                print("Using S2 Entry")
                
        return retval
    

    def confirm_trade_exit(self, pair: str, trade: Trade, order_type: str, amount: float,
                           rate: float, time_in_force: str, exit_reason: str,
                           current_time: datetime, **kwargs) -> bool:
        """
        Called right before placing a regular exit order.
        Timing for this function is critical, so avoid doing heavy computations or
        network requests in this method.

        For full documentation please go to https://www.freqtrade.io/en/latest/strategy-advanced/

        When not implemented by a strategy, returns True (always confirming).

        :param pair: Pair for trade that's about to be exited.
        :param trade: trade object.
        :param order_type: Order type (as configured in order_types). usually limit or market.
        :param amount: Amount in base currency.
        :param rate: Rate that's going to be used when using limit orders
                     or current rate for market orders.
        :param time_in_force: Time in force. Defaults to GTC (Good-til-cancelled).
        :param exit_reason: Exit reason.
            Can be any of ['roi', 'stop_loss', 'stoploss_on_exchange', 'trailing_stop_loss',
                           'exit_signal', 'force_exit', 'emergency_exit']
        :param current_time: datetime object, containing the current datetime
        :param **kwargs: Ensure to keep this here so updates to this won't break your strategy.
        :return bool: When True, then the exit-order is placed on the exchange.
            False aborts the process
        """

        dataframe, _ = self.dp.get_analyzed_dataframe(pair, self.timeframe)


        if(exit_reason == 'exit_signal'):
            retval = False
    
    
            if(trade.trade_direction == 'long'):
                if((self.S1_nS2 == 1) and (dataframe.iloc[-1]['S1_small_low_this'] == 1)):
                    retval = True
                elif((self.S1_nS2 == 0) and (dataframe.iloc[-1]['S2_small_low_this'] == 1)):
                    retval = True
            else:
                if((self.S1_nS2 == 1) and (dataframe.iloc[-1]['S1_small_high_this'] == 1)):
                    retval = True
                elif((self.S1_nS2 == 0) and (dataframe.iloc[-1]['S2_small_high_this'] == 1)):
                    retval = True
            
            if(retval):
                if(trade.trade_direction == 'long'):
                    current_profit = dataframe.iloc[-1]['close'] - trade.open_rate 
                else:
                    current_profit = trade.open_rate - dataframe.iloc[-1]['close']
    
                if(current_profit > 0):
                    self.win_loss = 1
                else:
                    self.win_loss = 0
    
                print("Exit number: ",self.n_exit)
                print("Trade direction: ",trade.trade_direction)
                print("trade.open_rate: ",trade.open_rate)
                print("trade.close_rate: ",trade.close_rate)
                print("Last candle open rate: ",dataframe.iloc[-1]['open'])
                print("Last candle high rate: ",dataframe.iloc[-1]['high'])
                print("Last candle low rate: ",dataframe.iloc[-1]['low'])
                print("Last candle close rate: ",dataframe.iloc[-1]['close'])
                print("Current Profit: ",current_profit)
                print("Exit is: ",self.win_loss)
    
                if(self.S1_nS2 == 1):
                    print("Using S1 Exit")
                else:
                    print("Using S2 Exit")
    
                print("-----")
    
                self.n_exit = self.n_exit + 1

        else:
            self.win_loss = 0
    
            print("Exit number: ",self.n_exit)
            print("Trade direction: ",trade.trade_direction)
            print("trade.open_rate: ",trade.open_rate)
            print("trade.close_rate: ",trade.close_rate)
            print("Last candle open rate: ",dataframe.iloc[-1]['open'])
            print("Last candle high rate: ",dataframe.iloc[-1]['high'])
            print("Last candle low rate: ",dataframe.iloc[-1]['low'])
            print("Last candle close rate: ",dataframe.iloc[-1]['close'])
            print("Exit is: ",self.win_loss)
    
            print("Stoploss or Force Exit")
    
            print("-----")
            retval = True

        return retval
