[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n"
  },
  {
    "path": "CryptoFrog.py",
    "content": "from typing import Dict, List, Optional, Tuple\nfrom datetime import datetime, timedelta\nfrom cachetools import TTLCache\n\n## I hope you know what these are already\nfrom pandas import DataFrame\nimport numpy as np\n\n## Indicator libs\nimport talib.abstract as ta\nfrom finta import TA as fta\n\n## FT stuffs\nfrom freqtrade.strategy import IStrategy, merge_informative_pair, stoploss_from_open, IntParameter, DecimalParameter, CategoricalParameter\nimport freqtrade.vendor.qtpylib.indicators as qtpylib\nfrom freqtrade.exchange import timeframe_to_minutes\nfrom freqtrade.persistence import Trade\nfrom skopt.space import Dimension\n\nclass CryptoFrog(IStrategy):\n\n    # ROI table - this strat REALLY benefits from roi and trailing hyperopt:\n    minimal_roi = {\n        \"0\": 0.213,\n        \"39\": 0.103,\n        \"96\": 0.037,\n        \"166\": 0\n    }\n\n    # Stoploss:\n    stoploss = -0.085\n\n    # Trailing stop:\n    trailing_stop = True\n    trailing_stop_positive = 0.01\n    trailing_stop_positive_offset = 0.047\n    trailing_only_offset_is_reached = False\n    \n    use_custom_stoploss = True\n    custom_stop = {\n        # Linear Decay Parameters\n        'decay-time': 166,       # minutes to reach end, I find it works well to match this to the final ROI value - default 1080\n        'decay-delay': 0,         # minutes to wait before decay starts\n        'decay-start': -0.085, # -0.32118, # -0.07163,     # starting value: should be the same or smaller than initial stoploss - default -0.30\n        'decay-end': -0.02,       # ending value - default -0.03\n        # Profit and TA  \n        'cur-min-diff': 0.03,     # diff between current and minimum profit to move stoploss up to min profit point\n        'cur-threshold': -0.02,   # how far negative should current profit be before we consider moving it up based on cur/min or roc\n        'roc-bail': -0.03,        # value for roc to use for dynamic bailout\n        'rmi-trend': 50,          # rmi-slow value to pause stoploss decay\n        'bail-how': 'immediate',  # set the stoploss to the atr offset below current price, or immediate\n        # Positive Trailing\n        'pos-trail': True,        # enable trailing once positive  \n        'pos-threshold': 0.005,   # trail after how far positive\n        'pos-trail-dist': 0.015   # how far behind to place the trail\n    }\n\n    # Dynamic ROI\n    droi_trend_type = CategoricalParameter(['rmi', 'ssl', 'candle', 'any'], default='any', space='sell', optimize=True)\n    droi_pullback = CategoricalParameter([True, False], default=True, space='sell', optimize=True)\n    droi_pullback_amount = DecimalParameter(0.005, 0.02, default=0.005, space='sell')\n    droi_pullback_respect_table = CategoricalParameter([True, False], default=False, space='sell', optimize=True)    \n    \n    # Custom Stoploss\n    cstp_threshold = DecimalParameter(-0.05, 0, default=-0.03, space='sell')\n    cstp_bail_how = CategoricalParameter(['roc', 'time', 'any'], default='roc', space='sell', optimize=True)\n    cstp_bail_roc = DecimalParameter(-0.05, -0.01, default=-0.03, space='sell')\n    cstp_bail_time = IntParameter(720, 1440, default=720, space='sell')    \n    \n    stoploss = custom_stop['decay-start']    \n\n    custom_trade_info = {}\n    custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes\n        \n    # run \"populate_indicators\" only for new candle\n    process_only_new_candles = False\n\n    # Experimental settings (configuration will overide these if set)\n    use_sell_signal = True\n    sell_profit_only = False\n    ignore_roi_if_buy_signal = False\n\n    use_dynamic_roi = True    \n    \n    timeframe = '5m'\n    informative_timeframe = '1h'\n\n    # Optional order type mapping\n    order_types = {\n        'buy': 'limit',\n        'sell': 'limit',\n        'stoploss': 'market',\n        'stoploss_on_exchange': False\n    }\n    \n    plot_config = {\n        'main_plot': {\n            'Smooth_HA_H': {'color': 'orange'},\n            'Smooth_HA_L': {'color': 'yellow'},\n        },\n        'subplots': {\n            \"StochRSI\": {\n                'srsi_k': {'color': 'blue'},\n                'srsi_d': {'color': 'red'},\n            },\n            \"MFI\": {\n                'mfi': {'color': 'green'},\n            },\n            \"BBEXP\": {\n                'bbw_expansion': {'color': 'orange'},\n            },\n            \"FAST\": {\n                'fastd': {'color': 'red'},\n                'fastk': {'color': 'blue'},\n            },\n            \"SQZMI\": {\n                'sqzmi': {'color': 'lightgreen'},\n            },\n            \"VFI\": {\n                'vfi': {'color': 'lightblue'},\n            },\n            \"DMI\": {\n                'dmi_plus': {'color': 'orange'},\n                'dmi_minus': {'color': 'yellow'},\n            },\n            \"EMACO\": {\n                'emac_1h': {'color': 'red'},\n                'emao_1h': {'color': 'blue'},\n            },\n        }\n    }\n\n    def informative_pairs(self):\n        pairs = self.dp.current_whitelist()\n        #pairs.append(\"BTC/USDT\")\n        #pairs.append(\"ETH/USDT\")\n        informative_pairs = [(pair, self.informative_timeframe) for pair in pairs]\n        return informative_pairs\n\n    ## smoothed Heiken Ashi\n    def HA(self, dataframe, smoothing=None):\n        df = dataframe.copy()\n\n        df['HA_Close']=(df['open'] + df['high'] + df['low'] + df['close'])/4\n\n        df.reset_index(inplace=True)\n\n        ha_open = [ (df['open'][0] + df['close'][0]) / 2 ]\n        [ ha_open.append((ha_open[i] + df['HA_Close'].values[i]) / 2) for i in range(0, len(df)-1) ]\n        df['HA_Open'] = ha_open\n\n        df.set_index('index', inplace=True)\n\n        df['HA_High']=df[['HA_Open','HA_Close','high']].max(axis=1)\n        df['HA_Low']=df[['HA_Open','HA_Close','low']].min(axis=1)\n\n        if smoothing is not None:\n            sml = abs(int(smoothing))\n            if sml > 0:\n                df['Smooth_HA_O']=ta.EMA(df['HA_Open'], sml)\n                df['Smooth_HA_C']=ta.EMA(df['HA_Close'], sml)\n                df['Smooth_HA_H']=ta.EMA(df['HA_High'], sml)\n                df['Smooth_HA_L']=ta.EMA(df['HA_Low'], sml)\n                \n        return df\n    \n    def hansen_HA(self, informative_df, period=6):\n        dataframe = informative_df.copy()\n        \n        dataframe['hhclose']=(dataframe['open'] + dataframe['high'] + dataframe['low'] + dataframe['close']) / 4\n        dataframe['hhopen']= ((dataframe['open'].shift(2) + dataframe['close'].shift(2))/ 2) #it is not the same as real heikin ashi since I found that this is better.\n        dataframe['hhhigh']=dataframe[['open','close','high']].max(axis=1)\n        dataframe['hhlow']=dataframe[['open','close','low']].min(axis=1)\n\n        dataframe['emac'] = ta.SMA(dataframe['hhclose'], timeperiod=period) #to smooth out the data and thus less noise.\n        dataframe['emao'] = ta.SMA(dataframe['hhopen'], timeperiod=period)\n        \n        return {'emac': dataframe['emac'], 'emao': dataframe['emao']}\n    \n    ## detect BB width expansion to indicate possible volatility\n    def bbw_expansion(self, bbw_rolling, mult=1.1):\n        bbw = list(bbw_rolling)\n\n        m = 0.0\n        for i in range(len(bbw)-1):\n            if bbw[i] > m:\n                m = bbw[i]\n\n        if (bbw[-1] > (m * mult)):\n            return 1\n        return 0\n\n    ## do_indicator style a la Obelisk strategies\n    def do_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Stoch fast - mainly due to 5m timeframes\n        stoch_fast = ta.STOCHF(dataframe)\n        dataframe['fastd'] = stoch_fast['fastd']\n        dataframe['fastk'] = stoch_fast['fastk']        \n        \n        #StochRSI for double checking things\n        period = 14\n        smoothD = 3\n        SmoothK = 3\n        dataframe['rsi'] = ta.RSI(dataframe, timeperiod=14)\n        stochrsi  = (dataframe['rsi'] - dataframe['rsi'].rolling(period).min()) / (dataframe['rsi'].rolling(period).max() - dataframe['rsi'].rolling(period).min())\n        dataframe['srsi_k'] = stochrsi.rolling(SmoothK).mean() * 100\n        dataframe['srsi_d'] = dataframe['srsi_k'].rolling(smoothD).mean()\n\n        # Bollinger Bands because obviously\n        bollinger = qtpylib.bollinger_bands(qtpylib.typical_price(dataframe), window=20, stds=1)\n        dataframe['bb_lowerband'] = bollinger['lower']\n        dataframe['bb_middleband'] = bollinger['mid']\n        dataframe['bb_upperband'] = bollinger['upper']\n        \n        # SAR Parabol - probably don't need this\n        dataframe['sar'] = ta.SAR(dataframe)\n        \n        ## confirm wideboi variance signal with bbw expansion\n        dataframe[\"bb_width\"] = ((dataframe[\"bb_upperband\"] - dataframe[\"bb_lowerband\"]) / dataframe[\"bb_middleband\"])\n        dataframe['bbw_expansion'] = dataframe['bb_width'].rolling(window=4).apply(self.bbw_expansion)\n\n        # confirm entry and exit on smoothed HA\n        dataframe = self.HA(dataframe, 4)\n\n        # thanks to Hansen_Khornelius for this idea that I apply to the 1hr informative\n        # https://github.com/hansen1015/freqtrade_strategy\n        hansencalc = self.hansen_HA(dataframe, 6)\n        dataframe['emac'] = hansencalc['emac']\n        dataframe['emao'] = hansencalc['emao']\n        \n        # money flow index (MFI) for in/outflow of money, like RSI adjusted for vol\n        dataframe['mfi'] = fta.MFI(dataframe)\n        \n        ## sqzmi to detect quiet periods\n        dataframe['sqzmi'] = fta.SQZMI(dataframe) #, MA=hansencalc['emac'])\n        \n        # Volume Flow Indicator (MFI) for volume based on the direction of price movement\n        dataframe['vfi'] = fta.VFI(dataframe, period=14)\n        \n        dmi = fta.DMI(dataframe, period=14)\n        dataframe['dmi_plus'] = dmi['DI+']\n        dataframe['dmi_minus'] = dmi['DI-']\n        dataframe['adx'] = fta.ADX(dataframe, period=14)\n        \n        ## for stoploss - all from Solipsis4\n        ## simple ATR and ROC for stoploss\n        dataframe['atr'] = ta.ATR(dataframe, timeperiod=14)\n        dataframe['roc'] = ta.ROC(dataframe, timeperiod=9)        \n        dataframe['rmi'] = RMI(dataframe, length=24, mom=5)\n        ssldown, sslup = SSLChannels_ATR(dataframe, length=21)\n        dataframe['sroc'] = SROC(dataframe, roclen=21, emalen=13, smooth=21)\n        dataframe['ssl-dir'] = np.where(sslup > ssldown,'up','down')        \n        dataframe['rmi-up'] = np.where(dataframe['rmi'] >= dataframe['rmi'].shift(),1,0)      \n        dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(5).sum() >= 3,1,0) \n        dataframe['candle-up'] = np.where(dataframe['close'] >= dataframe['close'].shift(),1,0)\n        dataframe['candle-up-trend'] = np.where(dataframe['candle-up'].rolling(5).sum() >= 3,1,0)        \n        \n        return dataframe\n\n    ## stolen from Obelisk's Ichi strat code and backtest blog post, and Solipsis4\n    def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        # Populate/update the trade data if there is any, set trades to false if not live/dry\n        self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair'])\n        \n        if self.config['runmode'].value in ('backtest', 'hyperopt'):\n            assert (timeframe_to_minutes(self.timeframe) <= 30), \"Backtest this strategy in 5m or 1m timeframe.\"\n\n        if self.timeframe == self.informative_timeframe:\n            dataframe = self.do_indicators(dataframe, metadata)\n        else:\n            if not self.dp:\n                return dataframe\n\n            informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.informative_timeframe)\n\n            informative = self.do_indicators(informative.copy(), metadata)\n            \n            dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.informative_timeframe, ffill=True)\n            \n            skip_columns = [(s + \"_\" + self.informative_timeframe) for s in ['date', 'open', 'high', 'low', 'close', 'volume', 'emac', 'emao']]\n            dataframe.rename(columns=lambda s: s.replace(\"_{}\".format(self.informative_timeframe), \"\") if (not s in skip_columns) else s, inplace=True)\n\n        # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest\n        if self.dp.runmode.value in ('backtest', 'hyperopt'):\n            self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date')\n            self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date')\n            self.custom_trade_info[metadata['pair']]['sroc'] = dataframe[['date', 'sroc']].copy().set_index('date')\n            self.custom_trade_info[metadata['pair']]['ssl-dir'] = dataframe[['date', 'ssl-dir']].copy().set_index('date')\n            self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date')\n            self.custom_trade_info[metadata['pair']]['candle-up-trend'] = dataframe[['date', 'candle-up-trend']].copy().set_index('date')            \n            \n        return dataframe\n\n    ## cryptofrog signals\n    def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[\n            (\n                (\n                    ## close ALWAYS needs to be lower than the heiken low at 5m\n                    (dataframe['close'] < dataframe['Smooth_HA_L'])\n                    &\n                    ## Hansen's HA EMA at informative timeframe\n                    (dataframe['emac_1h'] < dataframe['emao_1h'])\n                )\n                &\n                (\n                    (\n                        ## potential uptick incoming so buy\n                        (dataframe['bbw_expansion'] == 1) & (dataframe['sqzmi'] == False)\n                        &\n                        (\n                            (dataframe['mfi'] < 20)\n                            |\n                            (dataframe['dmi_minus'] > 30)\n                        )\n                    )\n                    |\n                    (\n                        # this tries to find extra buys in undersold regions\n                        (dataframe['close'] < dataframe['sar'])\n                        &\n                        ((dataframe['srsi_d'] >= dataframe['srsi_k']) & (dataframe['srsi_d'] < 30))\n                        &\n                        ((dataframe['fastd'] > dataframe['fastk']) & (dataframe['fastd'] < 23))\n                        &\n                        (dataframe['mfi'] < 30)\n                    )\n                    |\n                    (\n                        # find smaller temporary dips in sideways\n                        (\n                            ((dataframe['dmi_minus'] > 30) & qtpylib.crossed_above(dataframe['dmi_minus'], dataframe['dmi_plus']))\n                            &\n                            (dataframe['close'] < dataframe['bb_lowerband'])\n                        )\n                        |\n                        (\n                            ## if nothing else is making a buy signal\n                            ## just throw in any old SQZMI shit based fastd\n                            ## this needs work!\n                            (dataframe['sqzmi'] == True)\n                            &\n                            ((dataframe['fastd'] > dataframe['fastk']) & (dataframe['fastd'] < 20))\n                        )\n                    )\n                    ## volume sanity checks\n                    &\n                    (dataframe['vfi'] < 0.0)                    \n                    &\n                    (dataframe['volume'] > 0)                    \n                )\n            ),\n            'buy'] = 1\n\n        return dataframe\n    \n    ## more going on here\n    def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame:\n        dataframe.loc[\n            (\n                (\n                    ## close ALWAYS needs to be higher than the heiken high at 5m\n                    (dataframe['close'] > dataframe['Smooth_HA_H'])\n                    &\n                    ## Hansen's HA EMA at informative timeframe\n                    (dataframe['emac_1h'] > dataframe['emao_1h'])\n                )\n                &\n                (\n                    ## try to find oversold regions with a corresponding BB expansion\n                    (\n                        (dataframe['bbw_expansion'] == 1)\n                        &\n                        (\n                            (dataframe['mfi'] > 80)\n                            |\n                            (dataframe['dmi_plus'] > 30)\n                        )\n                    )\n                    ## volume sanity checks\n                    &\n                    (dataframe['vfi'] > 0.0)\n                    &\n                    (dataframe['volume'] > 0)                    \n                )\n            ),\n            'sell'] = 1\n        return dataframe\n\n    \"\"\"\n    Everything from here completely stolen from the godly work of @werkkrew\n    \n    Custom Stoploss \n    \"\"\" \n    def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float:\n        trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60)\n\n        if self.config['runmode'].value in ('live', 'dry_run'):\n            dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe)\n            sroc = dataframe['sroc'].iat[-1]\n        # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!)\n        else:\n            sroc = self.custom_trade_info[trade.pair]['sroc'].loc[current_time]['sroc']\n\n        if current_profit < self.cstp_threshold.value:\n            if self.cstp_bail_how.value == 'roc' or self.cstp_bail_how.value == 'any':\n                # Dynamic bailout based on rate of change\n                if (sroc/100) <= self.cstp_bail_roc.value:\n                    return 0.001\n            if self.cstp_bail_how.value == 'time' or self.cstp_bail_how.value == 'any':\n                # Dynamic bailout based on time\n                if trade_dur > self.cstp_bail_time.value:\n                    return 0.001\n                   \n        return 1\n\n    \"\"\"\n    Freqtrade ROI Overload for dynamic ROI functionality\n    \"\"\"\n    def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]:\n\n        minimal_roi = self.minimal_roi\n        _, table_roi = self.min_roi_reached_entry(trade_dur)\n\n        # see if we have the data we need to do this, otherwise fall back to the standard table\n        if self.custom_trade_info and trade and trade.pair in self.custom_trade_info:\n            if self.config['runmode'].value in ('live', 'dry_run'):\n                dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe)\n                rmi_trend = dataframe['rmi-up-trend'].iat[-1]\n                candle_trend = dataframe['candle-up-trend'].iat[-1]\n                ssl_dir = dataframe['ssl-dir'].iat[-1]\n            # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!)\n            else:\n                rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend']\n                candle_trend = self.custom_trade_info[trade.pair]['candle-up-trend'].loc[current_time]['candle-up-trend']\n                ssl_dir = self.custom_trade_info[trade.pair]['ssl-dir'].loc[current_time]['ssl-dir']\n\n            min_roi = table_roi\n            max_profit = trade.calc_profit_ratio(trade.max_rate)\n            pullback_value = (max_profit - self.droi_pullback_amount.value)\n            in_trend = False\n\n            if self.droi_trend_type.value == 'rmi' or self.droi_trend_type.value == 'any':\n                if rmi_trend == 1:\n                    in_trend = True\n            if self.droi_trend_type.value == 'ssl' or self.droi_trend_type.value == 'any':\n                if ssl_dir == 'up':\n                    in_trend = True\n            if self.droi_trend_type.value == 'candle' or self.droi_trend_type.value == 'any':\n                if candle_trend == 1:\n                    in_trend = True\n\n            # Force the ROI value high if in trend\n            if (in_trend == True):\n                min_roi = 100\n                # If pullback is enabled, allow to sell if a pullback from peak has happened regardless of trend\n                if self.droi_pullback.value == True and (current_profit < pullback_value):\n                    if self.droi_pullback_respect_table.value == True:\n                        min_roi = table_roi\n                    else:\n                        min_roi = current_profit / 2\n\n        else:\n            min_roi = table_roi\n\n        return trade_dur, min_roi\n\n    # Change here to allow loading of the dynamic_roi settings\n    def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool:  \n        trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60)\n\n        if self.use_dynamic_roi:\n            _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur)\n        else:\n            _, roi = self.min_roi_reached_entry(trade_dur)\n        if roi is None:\n            return False\n        else:\n            return current_profit > roi    \n    \n    # Get the current price from the exchange (or local cache)\n    def get_current_price(self, pair: str, refresh: bool) -> float:\n        if not refresh:\n            rate = self.custom_current_price_cache.get(pair)\n            # Check if cache has been invalidated\n            if rate:\n                return rate\n\n        ask_strategy = self.config.get('ask_strategy', {})\n        if ask_strategy.get('use_order_book', False):\n            ob = self.dp.orderbook(pair, 1)\n            rate = ob[f\"{ask_strategy['price_side']}s\"][0][0]\n        else:\n            ticker = self.dp.ticker(pair)\n            rate = ticker['last']\n\n        self.custom_current_price_cache[pair] = rate\n        return rate    \n    \n    \"\"\"\n    Stripped down version from Schism, meant only to update the price data a bit\n    more frequently than the default instead of getting all sorts of trade information\n    \"\"\"\n    def populate_trades(self, pair: str) -> dict:\n        # Initialize the trades dict if it doesn't exist, persist it otherwise\n        if not pair in self.custom_trade_info:\n            self.custom_trade_info[pair] = {}\n\n        # init the temp dicts and set the trade stuff to false\n        trade_data = {}\n        trade_data['active_trade'] = False\n\n        # active trade stuff only works in live and dry, not backtest\n        if self.config['runmode'].value in ('live', 'dry_run'):\n            \n            # find out if we have an open trade for this pair\n            active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all()\n\n            # if so, get some information\n            if active_trade:\n                # get current price and update the min/max rate\n                current_rate = self.get_current_price(pair, True)\n                active_trade[0].adjust_min_max_rates(current_rate)\n\n        return trade_data\n\n    # nested hyperopt class\n    class HyperOpt:\n\n        # defining as dummy, so that no error is thrown about missing\n        # sell indicator space when hyperopting for all spaces\n        @staticmethod\n        def indicator_space() -> List[Dimension]:\n            return []\n\n## goddamnit\n\ndef RMI(dataframe, *, length=20, mom=5):\n    \"\"\"\n    Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L912\n    \"\"\"\n    df = dataframe.copy()\n\n    df['maxup'] = (df['close'] - df['close'].shift(mom)).clip(lower=0)\n    df['maxdown'] = (df['close'].shift(mom) - df['close']).clip(lower=0)\n\n    df.fillna(0, inplace=True)\n\n    df[\"emaInc\"] = ta.EMA(df, price='maxup', timeperiod=length)\n    df[\"emaDec\"] = ta.EMA(df, price='maxdown', timeperiod=length)\n\n    df['RMI'] = np.where(df['emaDec'] == 0, 0, 100 - 100 / (1 + df[\"emaInc\"] / df[\"emaDec\"]))\n\n    return df[\"RMI\"]\n\ndef SSLChannels_ATR(dataframe, length=7):\n    \"\"\"\n    SSL Channels with ATR: https://www.tradingview.com/script/SKHqWzql-SSL-ATR-channel/\n    Credit to @JimmyNixx for python\n    \"\"\"\n    df = dataframe.copy()\n\n    df['ATR'] = ta.ATR(df, timeperiod=14)\n    df['smaHigh'] = df['high'].rolling(length).mean() + df['ATR']\n    df['smaLow'] = df['low'].rolling(length).mean() - df['ATR']\n    df['hlv'] = np.where(df['close'] > df['smaHigh'], 1, np.where(df['close'] < df['smaLow'], -1, np.NAN))\n    df['hlv'] = df['hlv'].ffill()\n    df['sslDown'] = np.where(df['hlv'] < 0, df['smaHigh'], df['smaLow'])\n    df['sslUp'] = np.where(df['hlv'] < 0, df['smaLow'], df['smaHigh'])\n\n    return df['sslDown'], df['sslUp']\n\ndef SROC(dataframe, roclen=21, emalen=13, smooth=21):\n    df = dataframe.copy()\n\n    roc = ta.ROC(df, timeperiod=roclen)\n    ema = ta.EMA(df, timeperiod=emalen)\n    sroc = ta.ROC(ema, timeperiod=smooth)\n\n    return sroc\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "# cryptofrog-strategies\nCryptoFrog - My First Strategy for freqtrade\n\n**_DO NOT USE THIS FOR LIVE TRADING_**\n\n# \"Release\" Notes\n\n- 2021-04-26: The informatives branch now includes a big refactor to include new KAMA and Madrid Squeeze code. Hyperopting now in the main strategy. I'll pull this into main whenever I feel it's ready.\n- 2021-04-20: You'll need the latest freqtrade develop branch otherwise you might see weird \"supersell\" results in your backtraces. Head to the freqtrade discord for more info.\n\nHeavily borrowing ideas from:\n\n- https://github.com/werkkrew/freqtrade-strategies : Amazing work on Solipsis that influenced my general framework and custom_stoploss\n- https://github.com/brookmiles/freqtrade-stuff : Great Ichi based strat from Obelisk\n- https://github.com/hansen1015/freqtrade_strategy/blob/main/heikin.py : Using the smoothed Heiken Ashi on the CryptoFrog 1hr informative timeframe\n\n# Things to Know\n\n- Fairly conservative strategy focusing on fewer buys and longer holds to find large peaks.\n- Designed to trade altcoins against stablecoins, and I've used USDT intentionally to gain relative stability within BTC/ETH dump cycles\n- Hyperopting is now available for most of the key indicator thresholds.\n- Protections need to be enabled. I've included a basic template config - hit me up on the freqtrade discord for any info but no surprises expected really\n- Included a live_plotting.ipynb notebook that can be used to immediately and easily view backtest results\n\n# TODO\n\n- Better buy signals\n- Better informative pair work looking for BTC/ETH trends\n- More testing\n\n# Preprequisites\n\nYou'll need:\n- Python 3.7+\n- Jupyter Notebook for the live_plotting.ipynb\n- finta\n- TA-Lib (I run my bot on a Raspberry Pi 400, so you'll need to build TA-Lib as per the Freqtrade docs if you're doing the same)\n- Pandas\n- Numpy\n- Pandas-TA indicator library\n- ~~Solipsis_v4 custom_indicators.py (now included in this repo - thanks for the go-ahead @werkkrew)~~\n"
  },
  {
    "path": "cryptofrog.config.json",
    "content": "{\n    \"max_open_trades\": -1,\n    \"stake_currency\": \"USDT\",\n    \"stake_amount\": 150,\n    \"tradable_balance_ratio\": 0.99,\n    \"fiat_display_currency\": \"GBP\",\n    \"dry_run\": true,\n    \"dry_run_wallet\": 1500,\n    \"unfilledtimeout\": {\n        \"buy\": 20,\n        \"sell\": 40\n    },\n    \"bid_strategy\": {\n        \"price_side\" : \"ask\",\n        \"ask_last_balance\": 0.0,\n        \"use_order_book\": true,\n        \"order_book_top\": 1,\n        \"check_depth_of_market\": {\n            \"enabled\": true,\n            \"bids_to_ask_delta\": 1\n        }\n    },\n    \"ask_strategy\": {\n        \"price_side\" : \"bid\",\n        \"use_order_book\": true,\n        \"order_book_min\": 1,\n        \"order_book_max\": 1,\n    },\n    \"exchange\": {\n        \"name\": \"\",\n        \"sandbox\": false,\n        \"key\": \"\",\n        \"secret\": \"\",\n        \"ccxt_config\": {\"enableRateLimit\": true},\n        \"ccxt_async_config\": {\n            \"enableRateLimit\": false,\n            \"rateLimit\": 500\n        },\n        \"pair_whitelist\":[],\n        \"pair_blacklist\": [\n            \"GBP/USDT\", \"EUR/USDT\", \"BUSD/USDT\", \"USDC/USDT\"\n        ]\n    },\n\n    \"pairlists\": [\n    {\n        \"method\": \"StaticPairList\"\n    },\n//    {\n//        \"method\": \"VolumePairList\",\n//        \"number_assets\": 80,\n//        \"sort_key\": \"quoteVolume\",\n//        \"refresh_period\": 300\n//    },\n\n    {\"method\": \"AgeFilter\", \"min_days_listed\": 30},\n//    {\"method\": \"PrecisionFilter\"},\n    {\"method\": \"PriceFilter\", \"low_price_ratio\": 0.01},\n    {\"method\": \"SpreadFilter\", \"max_spread_ratio\": 0.003},\n    {\n        \"method\": \"RangeStabilityFilter\",\n        \"lookback_days\": 3,\n        \"min_rate_of_change\": 0.1,\n        \"refresh_period\": 360\n    },\n    ],\n\n    \"protections\": [\n    {\n        \"method\": \"CooldownPeriod\",\n        \"stop_duration_candles\": 1\n    },\n    {\n        \"method\": \"StoplossGuard\",\n        \"lookback_period_candles\": 6,\n        \"trade_limit\": 2,\n        \"stop_duration_candles\": 1440,\n        \"only_per_pair\": true\n    },\n//    {\n//        \"method\": \"LowProfitPairs\",\n//        \"lookback_period_candles\": 3,\n//        \"trade_limit\": 2,\n//        \"stop_duration_candles\": 4,\n//        \"required_profit\": 0.015\n//    },\n//    {\n//        \"method\": \"LowProfitPairs\",\n//        \"lookback_period_candles\": 24,\n//        \"trade_limit\": 3,\n//        \"stop_duration_candles\": 12,\n//        \"required_profit\": 0.01\n//    }\n    ],\n    \"edge\": {\n        \"enabled\": false,\n        \"process_throttle_secs\": 3600,\n        \"calculate_since_number_of_days\": 10,\n        \"allowed_risk\": 0.02,\n        \"stoploss_range_min\": -0.01,\n        \"stoploss_range_max\": -0.3,\n        \"stoploss_range_step\": -0.01,\n        \"minimum_winrate\": 0.60,\n        \"minimum_expectancy\": 0.20,\n        \"min_trade_number\": 10,\n        \"max_trade_duration_minute\": 1440,\n        \"remove_pumps\": false\n    },\n    \"api_server\": {\n        \"enabled\": false,\n        \"listen_ip_address\": \"127.0.0.1\",\n        \"listen_port\": 8080,\n        \"verbosity\": \"error\",\n        \"enable_openapi\": false,\n        \"jwt_secret_key\": \"\",\n        \"CORS_origins\": [],\n        \"username\": \"\",\n        \"password\": \"\"\n    },\n    \"telegram\": {\n        \"enabled\": false,\n        \"token\": \"\",\n        \"chat_id\": \"\"\n    },\n    \"initial_state\": \"running\",\n    \"forcebuy_enable\": false,\n    \"internals\": {\n        \"process_throttle_secs\": 5\n    },\n    \"db_url\": \"sqlite:///cryptofrog.sqlite\",\n    \"user_data_dir\" : \"user_data\",\n    \"strategy\": \"CryptoFrog\",\n    \"strategy_path\": \"user_data/strategies\"\n}\n"
  },
  {
    "path": "custom_indicators.py",
    "content": "\"\"\"\nSolipsis Custom Indicators and Maths\n\"\"\"\nimport numpy as np\nimport talib.abstract as ta\nimport freqtrade.vendor.qtpylib.indicators as qtpylib\n\nfrom pandas import DataFrame, Series\n\n\n\"\"\"\nMisc. Helper Functions\n\"\"\"\ndef same_length(bigger, shorter):\n    return np.concatenate((np.full((bigger.shape[0] - shorter.shape[0]), np.nan), shorter))\n\n\"\"\"\nMaths\n\"\"\"\ndef linear_growth(start: float, end: float, start_time: int, end_time: int, trade_time: int) -> float:\n    \"\"\"\n    Simple linear growth function. Grows from start to end after end_time minutes (starts after start_time minutes)\n    \"\"\"\n    time = max(0, trade_time - start_time)\n    rate = (end - start) / (end_time - start_time)\n\n    return min(end, start + (rate * time))\n\n\"\"\"\nTA Indicators\n\"\"\"\n\ndef zema(dataframe, period, field='close'):\n    \"\"\"\n    Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/overlap_studies.py#L79\n    Modified slightly to use ta.EMA instead of technical ema\n    \"\"\"\n    df = dataframe.copy()\n\n    df['ema1'] = ta.EMA(df[field], timeperiod=period)\n    df['ema2'] = ta.EMA(df['ema1'], timeperiod=period)\n    df['d'] = df['ema1'] - df['ema2']\n    df['zema'] = df['ema1'] + df['d']\n\n    return df['zema']\n\ndef RMI(dataframe, *, length=20, mom=5):\n    \"\"\"\n    Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L912\n    \"\"\"\n    df = dataframe.copy()\n\n    df['maxup'] = (df['close'] - df['close'].shift(mom)).clip(lower=0)\n    df['maxdown'] = (df['close'].shift(mom) - df['close']).clip(lower=0)\n\n    df.fillna(0, inplace=True)\n\n    df[\"emaInc\"] = ta.EMA(df, price='maxup', timeperiod=length)\n    df[\"emaDec\"] = ta.EMA(df, price='maxdown', timeperiod=length)\n\n    df['RMI'] = np.where(df['emaDec'] == 0, 0, 100 - 100 / (1 + df[\"emaInc\"] / df[\"emaDec\"]))\n\n    return df[\"RMI\"]\n\ndef mastreak(dataframe: DataFrame, period: int = 4, field='close') -> Series:\n    \"\"\"\n    MA Streak\n    Port of: https://www.tradingview.com/script/Yq1z7cIv-MA-Streak-Can-Show-When-a-Run-Is-Getting-Long-in-the-Tooth/\n    \"\"\"    \n    df = dataframe.copy()\n\n    avgval = zema(df, period, field)\n\n    arr = np.diff(avgval)\n    pos = np.clip(arr, 0, 1).astype(bool).cumsum()\n    neg = np.clip(arr, -1, 0).astype(bool).cumsum()\n    streak = np.where(arr >= 0, pos - np.maximum.accumulate(np.where(arr <= 0, pos, 0)),\n                    -neg + np.maximum.accumulate(np.where(arr >= 0, neg, 0)))\n\n    res = same_length(df['close'], streak)\n\n    return res\n\ndef pcc(dataframe: DataFrame, period: int = 20, mult: int = 2):\n    \"\"\"\n    Percent Change Channel\n    PCC is like KC unless it uses percentage changes in price to set channel distance.\n    https://www.tradingview.com/script/6wwAWXA1-MA-Streak-Change-Channel/\n    \"\"\"\n    df = dataframe.copy()\n\n    df['previous_close'] = df['close'].shift()\n\n    df['close_change'] = (df['close'] - df['previous_close']) / df['previous_close'] * 100\n    df['high_change'] = (df['high'] - df['close']) / df['close'] * 100\n    df['low_change'] = (df['low'] - df['close']) / df['close'] * 100\n\n    df['delta'] = df['high_change'] - df['low_change']\n\n    mid = zema(df, period, 'close_change')\n    rangema = zema(df, period, 'delta')\n\n    upper = mid + rangema * mult\n    lower = mid - rangema * mult\n\n    return upper, rangema, lower\n\ndef SSLChannels(dataframe, length=10, mode='sma'):\n    \"\"\"\n    Source: https://www.tradingview.com/script/xzIoaIJC-SSL-channel/\n    Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L1025\n    Usage:\n        dataframe['sslDown'], dataframe['sslUp'] = SSLChannels(dataframe, 10)\n    \"\"\"\n    if mode not in ('sma'):\n        raise ValueError(f\"Mode {mode} not supported yet\")\n\n    df = dataframe.copy()\n\n    if mode == 'sma':\n        df['smaHigh'] = df['high'].rolling(length).mean()\n        df['smaLow'] = df['low'].rolling(length).mean()\n\n    df['hlv'] = np.where(df['close'] > df['smaHigh'], 1,\n                         np.where(df['close'] < df['smaLow'], -1, np.NAN))\n    df['hlv'] = df['hlv'].ffill()\n\n    df['sslDown'] = np.where(df['hlv'] < 0, df['smaHigh'], df['smaLow'])\n    df['sslUp'] = np.where(df['hlv'] < 0, df['smaLow'], df['smaHigh'])\n\n    return df['sslDown'], df['sslUp']\n\ndef SSLChannels_ATR(dataframe, length=7):\n    \"\"\"\n    SSL Channels with ATR: https://www.tradingview.com/script/SKHqWzql-SSL-ATR-channel/\n    Credit to @JimmyNixx for python\n    \"\"\"\n    df = dataframe.copy()\n\n    df['ATR'] = ta.ATR(df, timeperiod=14)\n    df['smaHigh'] = df['high'].rolling(length).mean() + df['ATR']\n    df['smaLow'] = df['low'].rolling(length).mean() - df['ATR']\n    df['hlv'] = np.where(df['close'] > df['smaHigh'], 1, np.where(df['close'] < df['smaLow'], -1, np.NAN))\n    df['hlv'] = df['hlv'].ffill()\n    df['sslDown'] = np.where(df['hlv'] < 0, df['smaHigh'], df['smaLow'])\n    df['sslUp'] = np.where(df['hlv'] < 0, df['smaLow'], df['smaHigh'])\n\n    return df['sslDown'], df['sslUp']\n\ndef WaveTrend(dataframe, chlen=10, avg=21, smalen=4):\n    \"\"\"\n    WaveTrend Ocillator by LazyBear\n    https://www.tradingview.com/script/2KE8wTuF-Indicator-WaveTrend-Oscillator-WT/\n    \"\"\"\n    df = dataframe.copy()\n\n    df['hlc3'] = (df['high'] + df['low'] + df['close']) / 3\n    df['esa'] = ta.EMA(df['hlc3'], timeperiod=chlen)\n    df['d'] = ta.EMA((df['hlc3'] - df['esa']).abs(), timeperiod=chlen)\n    df['ci'] = (df['hlc3'] - df['esa']) / (0.015 * df['d'])\n    df['tci'] = ta.EMA(df['ci'], timeperiod=avg)\n\n    df['wt1'] = df['tci']\n    df['wt2'] = ta.SMA(df['wt1'], timeperiod=smalen)\n    df['wt1-wt2'] = df['wt1'] - df['wt2']\n\n    return df['wt1'], df['wt2']\n\ndef T3(dataframe, length=5):\n    \"\"\"\n    T3 Average by HPotter on Tradingview\n    https://www.tradingview.com/script/qzoC9H1I-T3-Average/\n    \"\"\"\n    df = dataframe.copy()\n\n    df['xe1'] = ta.EMA(df['close'], timeperiod=length)\n    df['xe2'] = ta.EMA(df['xe1'], timeperiod=length)\n    df['xe3'] = ta.EMA(df['xe2'], timeperiod=length)\n    df['xe4'] = ta.EMA(df['xe3'], timeperiod=length)\n    df['xe5'] = ta.EMA(df['xe4'], timeperiod=length)\n    df['xe6'] = ta.EMA(df['xe5'], timeperiod=length)\n    b = 0.7\n    c1 = -b*b*b\n    c2 = 3*b*b+3*b*b*b\n    c3 = -6*b*b-3*b-3*b*b*b\n    c4 = 1+3*b+b*b*b+3*b*b\n    df['T3Average'] = c1 * df['xe6'] + c2 * df['xe5'] + c3 * df['xe4'] + c4 * df['xe3']\n\n    return df['T3Average']\n\n\ndef SROC(dataframe, roclen=21, emalen=13, smooth=21):\n    df = dataframe.copy()\n\n    roc = ta.ROC(df, timeperiod=roclen)\n    ema = ta.EMA(df, timeperiod=emalen)\n    sroc = ta.ROC(ema, timeperiod=smooth)\n\n    return sroc"
  },
  {
    "path": "live_plotting.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"difficult-binding\",\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json, os\\n\",\n    \"from pathlib import Path\\n\",\n    \"\\n\",\n    \"from freqtrade.configuration import Configuration\\n\",\n    \"from freqtrade.data.btanalysis import load_trades_from_db, load_backtest_data, load_backtest_stats\\n\",\n    \"from freqtrade.data.history import load_pair_history\\n\",\n    \"from freqtrade.data.dataprovider import DataProvider\\n\",\n    \"from freqtrade.plugins.pairlistmanager import PairListManager\\n\",\n    \"from freqtrade.exceptions import ExchangeError, OperationalException\\n\",\n    \"from freqtrade.exchange import Exchange\\n\",\n    \"from freqtrade.resolvers import ExchangeResolver, StrategyResolver\\n\",\n    \"from freqtrade.state import RunMode\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"import pandas as pd\\n\",\n    \"import random\\n\",\n    \"from collections import deque\\n\",\n    \"\\n\",\n    \"import nest_asyncio\\n\",\n    \"nest_asyncio.apply()\\n\",\n    \"\\n\",\n    \"configs=[\\\"cryptofrog.config.json\\\"]\\n\",\n    \"\\n\",\n    \"ft_config = Configuration.from_files(files=configs)\\n\",\n    \"ft_exchange = ExchangeResolver.load_exchange(ft_config['exchange']['name'], config=ft_config, validate=True)\\n\",\n    \"ft_pairlists = PairListManager(ft_exchange, ft_config)\\n\",\n    \"ft_dataprovider = DataProvider(ft_config, ft_exchange, ft_pairlists)\\n\",\n    \"\\n\",\n    \"data_location = Path(ft_config['user_data_dir'], 'data', 'binance')\\n\",\n    \"backtest_dir = Path(ft_config['user_data_dir'], 'backtest_results')\\n\",\n    \"\\n\",\n    \"# Load strategy using values set above\\n\",\n    \"strategy = StrategyResolver.load_strategy(ft_config)\\n\",\n    \"strategy.dp = ft_dataprovider\\n\",\n    \"\\n\",\n    \"# Generate buy/sell signals using strategy\\n\",\n    \"timeframe = \\\"5m\\\"\\n\",\n    \"\\n\",\n    \"backtest = False\\n\",\n    \"\\n\",\n    \"if ft_config[\\\"timeframe\\\"] is not None:\\n\",\n    \"    timeframe = ft_config[\\\"timeframe\\\"]\\n\",\n    \"    print(\\\"Using config timeframe:\\\" , timeframe)\\n\",\n    \"elif strategy.timeframe is not None:\\n\",\n    \"    timeframe = strategy.timeframe\\n\",\n    \"    print(\\\"Using strategy timeframe:\\\" , timeframe)\\n\",\n    \"else:\\n\",\n    \"    print(\\\"Using default timeframe:\\\" , timeframe)\\n\",\n    \"\\n\",\n    \"def do_analysis(pair, strategy, timeframe, only_backtest=False, hist_and_backtest=True):\\n\",\n    \"    if only_backtest is True:\\n\",\n    \"        print(\\\"Loading backtest data...\\\")\\n\",\n    \"        trades = load_backtest_data(backtest_dir)\\n\",\n    \"    else:\\n\",\n    \"        print(\\\"Loading historic data...\\\")\\n\",\n    \"        candles = load_pair_history(datadir=data_location,\\n\",\n    \"                                    timeframe=timeframe,\\n\",\n    \"                                    pair=pair,\\n\",\n    \"                                    data_format = \\\"json\\\",\\n\",\n    \"                                    )\\n\",\n    \"\\n\",\n    \"        # Confirm success\\n\",\n    \"        print(\\\"Loaded \\\" + str(len(candles)) + f\\\" rows of data for {pair} from {data_location}\\\")\\n\",\n    \"        df = strategy.analyze_ticker(candles, {'pair': pair})\\n\",\n    \"        \\n\",\n    \"        if hist_and_backtest is True:\\n\",\n    \"            print(\\\"Loading backtest trades data...\\\")\\n\",\n    \"            trades = load_backtest_data(backtest_dir)            \\n\",\n    \"        else:\\n\",\n    \"            # Fetch trades from database\\n\",\n    \"            print(\\\"Loading DB trades data...\\\")\\n\",\n    \"            trades = load_trades_from_db(ft_config['db_url'])\\n\",\n    \"\\n\",\n    \"        print(f\\\"Generated {df['buy'].sum()} buy / {df['sell'].sum()} sell signals\\\")\\n\",\n    \"        data = df.set_index('date', drop=False)\\n\",\n    \"        # print(data.info())\\n\",\n    \"        # print(data.tail())\\n\",\n    \"        # print(data[\\\"buy\\\"].dropna())\\n\",\n    \"        return (data, trades)\\n\",\n    \"    \\n\",\n    \"    return (pd.Dataframe(), trades)\\n\",\n    \"\\n\",\n    \"def do_plot(pair, data, trades, plot_config=None):\\n\",\n    \"    from freqtrade.plot.plotting import generate_candlestick_graph\\n\",\n    \"    import plotly.offline as pyo\\n\",\n    \"\\n\",\n    \"    # Filter trades to one pair\\n\",\n    \"    trades_red = trades.loc[trades['pair'] == pair].copy()\\n\",\n    \"\\n\",\n    \"    # Limit graph period to your BT timerange\\n\",\n    \"    data_red = data['2021-04-01':'2021-04-20']\\n\",\n    \"\\n\",\n    \"    plotconf = strategy.plot_config\\n\",\n    \"    if plot_config is not None:\\n\",\n    \"        plotconf = plot_config\\n\",\n    \"    \\n\",\n    \"    # Generate candlestick graph\\n\",\n    \"    graph = generate_candlestick_graph(pair=pair,\\n\",\n    \"                                       data=data_red,\\n\",\n    \"                                       trades=trades_red,\\n\",\n    \"                                       plot_config=plotconf\\n\",\n    \"                                       )\\n\",\n    \"\\n\",\n    \"    pyo.iplot(graph, show_link = False)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"id\": \"effective-vintage\",\n   \"metadata\": {\n    \"scrolled\": false\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"# example inline plot config to override strat\\n\",\n    \"plot_config = {\\n\",\n    \"    'main_plot': {\\n\",\n    \"    },\\n\",\n    \"    'subplots': {\\n\",\n    \"        'STR' :{\\n\",\n    \"            'mastreak': {'color': 'black'},\\n\",\n    \"        },\\n\",\n    \"        'KAMA' :{\\n\",\n    \"            'kama': {'color': 'red'},\\n\",\n    \"        },\\n\",\n    \"        'RMI' :{\\n\",\n    \"            'rmi': {'color': 'blue'},\\n\",\n    \"        },\\n\",\n    \"        'MP' :{\\n\",\n    \"            'mp': {'color': 'green'},\\n\",\n    \"        },        \\n\",\n    \"    }\\n\",\n    \"}\\n\",\n    \"\\n\",\n    \"## set the pairlist you want to plot\\n\",\n    \"pairlist = [\\\"WIN/USDT\\\", \\\"SC/USDT\\\"]\\n\",\n    \"\\n\",\n    \"## don't do this for more than a couple of pairs and for a few days otherwise Slowness Will Occur\\n\",\n    \"for i in pairlist:\\n\",\n    \"    (data, trades) = do_analysis(i, strategy, timeframe)\\n\",\n    \"    do_plot(i, data, trades) #, plot_config=plot_config)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.8.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 5\n}\n"
  }
]