# --- Do not remove these libs ---
from freqtrade.strategy import IStrategy, DecimalParameter
from typing import Dict, List
from pandas import DataFrame, Series
# --------------------------------

import talib.abstract as ta
import pandas as pd


# Notes: ** DONT' GO LIVE ** with this strat. Risk of big losses.
# ==============================================================
# It works better with top 10-15 (mostly) coins per marketcap. Better avoid shitcoins. 
# Remember to set "timeframe": "1m" in config.



def chaikin_mf(df, periods=20):
    close = df['close']
    low = df['low']
    high = df['high']
    volume = df['volume']
    mfv = ((close - low) - (high - close)) / (high - low)
    mfv = mfv.fillna(0.0)
    mfv *= volume
    cmf = mfv.rolling(periods).sum() / volume.rolling(periods).sum()
    return Series(cmf, name='cmf')



class FollowTheGreenRabbitV1(IStrategy):

    minimal_roi = {
        "0": 0.06
    }
    stoploss = -0.08

    timeframe = '1m'
 
    # Sell signal
    use_sell_signal = True
    sell_profit_only = True
    ignore_roi_if_buy_signal = True

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

    # Number of candles the strategy requires before producing valid signals
    startup_candle_count = 100
    
    buy_sens_ema   = DecimalParameter(0.0, 200.0, default=0.02, decimals=2, space='buy', optimize=True, load=True)
    buy_sens       = DecimalParameter(0.0, 200.0, default=20.00, decimals=2, space='buy', optimize=True, load=True)
    sell_sens      = DecimalParameter(0.0, 200.0, default=20.00, decimals=2, space='sell', optimize=True, load=True)
    buy_hist_gain  = DecimalParameter(-1.0, 0.0, default=-0.50, decimals=2, space='buy', optimize=True, load=True)
    sell_hist_gain = DecimalParameter(0.0, 1.0, default=0.20, decimals=2, space='sell', optimize=True, load=True)

    #buy_sens_ema = 0.02
    #buy_sens = 20
    #sell_sens = 20
    #buy_hist_gain = -0.50
    #sell_hist_gain = 0.20
    

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

        # EMA
        dataframe['ema_fast']= ta.EMA(dataframe, 15)
        dataframe['ema_slow']= ta.EMA(dataframe, 100)

        # Chaikin Money Flow
        dataframe['cmf'] = chaikin_mf(dataframe)

        # MACD
        macd = ta.MACD(dataframe,12,26,50)
        dataframe['macd'] = macd['macd']
        dataframe['macdsignal'] = macd['macdsignal']
        dataframe['macdhist'] = macd['macdhist']
        return dataframe

# ============== BUY ======================

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

        dataframe.loc[
            (         
                (dataframe['ema_fast'] < dataframe['ema_slow']) 
                &
                (dataframe['ema_fast'] > (dataframe['ema_fast'].shift(1) + dataframe['ema_fast'].shift(1)*self.buy_sens_ema.value/100)) 
                &
                (dataframe['macdhist'] < self.buy_hist_gain.value) 
                &                
                (dataframe['cmf'] < -0.10) #Chaikin MF
                &                
                (dataframe['macdhist'] > (dataframe['macdhist'].shift(1) - dataframe['macdhist'].shift(1)*self.buy_sens.value/100))                
                &
                (dataframe['volume'] > 0)            
            ),            
            'buy'] = 1            
        return dataframe

# ============== SELL ======================

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

        dataframe.loc[
            (
                (dataframe['ema_fast'] > dataframe['ema_slow'])
                &                
                (dataframe['macdhist'] > self.sell_hist_gain.value)
                &
                (dataframe['cmf'] >= 0.20) #Chaikin MF
                &                
                (dataframe['macdhist'] < (dataframe['macdhist'].shift(1) - dataframe['macdhist'].shift(1)*self.sell_sens.value/100))                
                &
                (dataframe['volume'] > 0)
            ),
            'sell'] = 1
        return dataframe


    plot_config = {
        'main_plot':{
            'ema_slow':{},
            'ema_fast':{}
        },
        'subplots': {
            "MACD": {
                'macdhist':{'color':'black'},
            },
            "CMF" : {
                'cmf' : {'color':'red'}
            },            
        }        
    }  
