
from freqtrade.strategy.interface import IStrategy
from typing import Dict, List
from functools import reduce
from pandas import DataFrame
from freqtrade.persistence import Trade
from datetime import datetime, date, timedelta


import talib.abstract as ta
import freqtrade.vendor.qtpylib.indicators as qtpylib
import numpy  # noqa
import logging

logger = logging.getLogger(__name__)

class jeroen_test(IStrategy):

    # Minimal ROI designed for the strategy.
    minimal_roi = {
        "0": 0.02
    }

    order_types = {
        'buy': 'market',
        'sell': 'market',
        'stoploss': 'market',
        'stoploss_on_exchange': False
    }

    # Optimal stoploss designed for the strategy
    stoploss = -10

    # Optimal timeframe for the strategy
    timeframe = '1m'

    def calc_profit(self, price: float, current: float) -> float:
        fee = 1.0007
        profit = ((current*fee) -
            (price*fee))

        return float(f"{profit:.8f}")

    def calc_percentage_lower(self, price: float, current: float) -> float:
        fee = 1.0007
        price = price*fee
        current = current*fee
        lowerpercent = ((price-current)/(price*fee))*100

        return float(f"{lowerpercent:.8f}")

    def bot_loop_start(self, **kwargs) -> None:
        print(" ")

    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:
        """ Adds several different TA indicators to the given DataFrame
        """
        profit = False
        profit_percent = False
        percent_lower = False
        current_price = dataframe['close'].iloc[-1]

        dataframe['should_sell'] = False
        dataframe['should_buy'] = False

        # Get the previous trade
        trade = Trade.get_trades_proxy(is_open=False, pair=metadata['pair'])
        if trade:
            trade = trade[-1]
            lsp = trade.close_rate
            if lsp:
                percent_lower = self.calc_percentage_lower(price=lsp, current=current_price)
            # Found a bug? When force selling it doesnt close it
            else:
                lsp = trade.open_rate
                if lsp:
                    percent_lower = self.calc_percentage_lower(price=lsp, current=current_price)
        else:
            lsp = 0.00

        # Get the current Trade
        trade = Trade.get_trades_proxy(is_open=True, pair=metadata['pair'])
        if trade:
            trade = trade[-1]
            lbp = trade.open_rate
            open_trade = True
            profit = self.calc_profit(price=lbp, current=current_price)
            profit_percent = (profit/lbp)*100
        else:
            lbp = 0.00
            open_trade = False
            profit = False
            profit_percent = False


        print("------------")

        print("Last Sold For:", lsp)

        if open_trade:
            print("Bought for: ", lbp)
        print("Current Price: ", current_price)
        if profit:
            print("Current Profit: ", profit, " ", float(f"{profit_percent:.8f}"), "%")
        if percent_lower and not open_trade:
            print("Percent Lower: ", float(f"{percent_lower:.8f}"), "%")


        # Should we Sell?
        if profit_percent:
            if profit_percent > 1:
                dataframe['should_sell'] = True

        # Should we buy?
        if not open_trade:
            if (lsp == 0.00 ) & (lbp == 0.00):
                dataframe['should_buy'] = True
            # Is the percentage of what we sold for and the current price 2% lower
            if percent_lower > 2:
                dataframe['should_buy'] = True


        dataframe['last_sell_price'] = lsp
        dataframe['last_buy_price'] = lbp


        print("Current Dataframe:")
        print(dataframe.tail(1))


        return dataframe

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

        dataframe.loc[(
            # We have not bought or sold anything yet, lets buy!
            ((dataframe['last_sell_price'] == 0.00) & (dataframe['last_buy_price'] == 0.00) ) |
            (
                # Make sure the last selling price is higher than the current price
                ((dataframe['last_sell_price']) > dataframe['close']) &

                # Calculated earlier
                (dataframe['should_buy'] == True)
            )
            ), 'buy'
        ] = 1

        return dataframe

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

        dataframe.loc[(
                # Make at least profit
                (dataframe['last_buy_price'] < (dataframe['close'])) &

                # Calculated earlier
                (dataframe['should_sell'] == True) &

                # If we have nothing we bought, there is nothing to sell
                (dataframe['last_buy_price'] > 0.00)
            ), 'sell'
        ] = 1

        return dataframe