kikocis/freqtrade-strategies public
Changesets · Branches · Tags · Compare
| Changeset | 9807db93d1abb8e076a993ad0041a89c98609f5c7caac0532f298f610c1ee50a |
|---|---|
| Author | Bryan Chain <bryan.chain@cerner.com> · 2021-04-16 14:24 -04:00 |
| Committer | Bryan Chain <bryan.chain@cerner.com> · 2021-04-16 14:24 -04:00 |
| Parents | 73a725507ce0 |
8 files changed
modified README.md +117 −69
| @@ -1,94 +1,149 @@ | ||
| 1 | 1 | # Freqtrade Strategies |
| 2 | 2 | |
| 3 | -Strategies for [Freqtrade](https://freqtrade.io), developed primarily in a partnership between @werkkrew and @JimmyNixx from the Freqtrade Discord. | |
| 3 | +Strategies for [Freqtrade](https://freqtrade.io), most were developed in a partnership between @werkkrew and @JimmyNixx from the Freqtrade Discord. Some are my own. | |
| 4 | 4 | |
| 5 | 5 | Use these strategies at your own risk. We are not responsible for anything. |
| 6 | 6 | |
| 7 | 7 | ## Repostitory Structure |
| 8 | 8 | |
| 9 | -The root of the `strategies/` and `hyperopts/` folders contains my current version of the strategy and is likely what I run live. Anything in the `old/` directory has been deprecated and I no longer run/maintain these strategies in any way. These are here for posterity and may still be useful/valuable/profitable, or contain useful examples for inspiration. | |
| 9 | +The root of the `strategies/` and `hyperopts/` folders contains my current version of the strategy and is likely what I run live. Anything in the `old/` directories have been deprecated and I no longer run/maintain these strategies in any way. These are here for posterity and may still be valuable/profitable, or contain useful examples for inspiration. | |
| 10 | 10 | |
| 11 | 11 | ## About Solipsis |
| 12 | 12 | |
| 13 | -Solipsis is the current strategy I run. It is an evolution of the `Schism` series found in the `old/` folder. The basic idea was to override the Freqtrade base ROI functionality to stimulate a sticking buy signal to exploit the use of `ignore_roi_if_buy_signal` and stay in trades that are in an upward trend past where the static ROI table would have sold. This evolved into several other things using active trade data. | |
| 13 | +Solipsis is an evolution of the `Schism` series found in the `old/` folder. The basic idea was to override the Freqtrade base ROI functionality to stimulate a sticking buy signal to exploit the use of `ignore_roi_if_buy_signal` and stay in trades that are in an upward trend past where the static ROI table would have sold without having to design a really strong sell signal. This evolved into several other things using active trade data. | |
| 14 | 14 | |
| 15 | -The primary difference between `Schism` and `Solipsis` is that Schism used active trade data within the confines of the buy and sell signals to accomplish this, which did not work in any way with backtesting or hyperoptimization. The fundamental idea worked but was only possible to validate and tune in a live or dry-run which was very time consuming. Solipsis attempts to solve this problem by making the ROI table truly dynamic within the `minimal_roi` methods, and does the dynamic sell bailout work within the scope of the `custom_stoploss`. This makes it possible to fully backtest and hyperopt the ideas, but does present some limitations (such as using data about other trades) that were used in `Schism`. | |
| 15 | +The primary difference between `Schism` and `Solipsis` is that Schism used active trade data within the confines of the buy and sell signals to accomplish this, which did not work in any way with backtesting or hyperoptimization. The fundamental idea worked but was only possible to validate and tune in a live or dry-run which was very time consuming. Solipsis attempts to solve this problem by making the ROI table truly dynamic within the `minimal_roi` methods, and does the dynamic sell bailout work within the scope of the `custom_stoploss`. This makes it possible to fully backtest and hyperopt the ideas, but does present some limitations (such as using data about other trades) that were used in `Schism` as well as the usual limitations backtesting only being able to use OHLC data presents. | |
| 16 | 16 | |
| 17 | 17 | ### TODO |
| 18 | 18 | |
| 19 | -- Continue to hunt for a better all around buy signal. | |
| 20 | -- Tweak ROI Trend Ride | |
| 21 | - - Adjust pullback to be more dynamic, seems to get out a tad bit early in many cases. | |
| 22 | - - Consider a way to identify very large/fast spikes when RMI has not yet reacted to stay in past ROI point. | |
| 19 | +- Continue to improve buy signal. Ideas are welcome! | |
| 20 | +- Continue to optimize and innovate around dynamic ROI idea. | |
| 23 | 21 | - Further enchance and optimize custom stop loss |
| 24 | 22 | - Continue to evaluate good circumstances to bail and sell vs hold on for recovery |
| 25 | 23 | - Curent implementation seems to work pretty well but feel like there is room for improvement. |
| 26 | -- Develop a PR to fully support hyperopting the custom_stoploss and dynamic_roi spaces? | |
| 27 | -- Make a container for my hyperopt fork available | |
| 24 | +- Consider some factors for how "strong" the buy signal is and consider a way to evaluate informative pairs/timeframes for how careful we should be when entering. For example, if BTC oracle says to be cautious, require a stronger buy signal for entry? | |
| 28 | 25 | |
| 29 | 26 | ### Features |
| 30 | 27 | |
| 31 | 28 | - **Dynamic ROI** |
| 32 | - - Several options, initial idea was to ride trends past ROI in a similar way to trailing stoploss but using indicators. | |
| 33 | - - Fallback choices includes table, roc, atr, and others. Has the ability to set ROI table values dynamically based on indicator math. | |
| 29 | + - Essentially the idea is to override the static ROI table when there is a trend to allow for larger profits. | |
| 34 | 30 | - **Custom Stoploss** |
| 35 | 31 | - Generally a vanilla implementation of Freqtrade custom stoploss but tries to do some clever things. Uses indicator data. (Thanks @JoeSchr!) |
| 36 | -- Dynamic informative indicators based on certain stake currences and whitelist contents. | |
| 37 | - - If BTC/STAKE is not in whitelist, make sure to use that for an informative. | |
| 32 | +- **Dynamic informative indicators** based on certain stake currences and whitelist contents. | |
| 33 | + - If BTC/STAKE is not in whitelist, make sure to use that for an informative. (This is important for strategy performance) | |
| 38 | 34 | - If your stake is BTC or ETH, use COIN/FIAT and BTC/FIAT as informatives. |
| 39 | -- Ability to provide custom parameters on a per-pair or group of pairs basis, this includes buy/sell/minimal_roi/dynamic_roi/custom_stop settings, if one desired. | |
| 40 | 35 | - Custom indicator file to keep primary strategy clean(ish). |
| 41 | - - Most (but not all) of what is in there is taken from freqtrade/technical with some slight modification, removes dependenacy on that import and allows for some customization without having to edit those files directly. | |
| 42 | -- Child strategy for stake specific settings and different settings for different instances, hoping to keep this strategy file relatively clutter-free from the extensive options especially when using per-pair settings. | |
| 36 | +- Child strategy for stake specific settings and different settings for different instances, hoping to keep this strategy file relatively clutter-free from the extensive options available. I personally use the child strategy to also document the current optimization results the strategy is running off of so I can reference them easily in subsequent optimization runs. | |
| 43 | 37 | |
| 44 | -### Notes and Recommendations | |
| 38 | +## Overview and Theory | |
| 39 | + | |
| 40 | +- **Buying** | |
| 41 | + - Base pair uses a "downtrend" buy where it expects a bounce from a lower resistance level. This uses several indicators including [RMI](https://www.tradingview.com/script/kwIt9OgQ-Relative-Momentum-Index/), [Momentum Pinball](https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/), [PCC](https://www.tradingview.com/script/6wwAWXA1-MA-Streak-Change-Channel/), and [MA Streak](https://www.tradingview.com/script/Yq1z7cIv-MA-Streak-Can-Show-When-a-Run-Is-Getting-Long-in-the-Tooth/). | |
| 42 | + - Base pair uses an upper guard by calculating the "Average Day Range" and not buying when markets are near daily peaks where we anticipate resistance. | |
| 43 | + - Informative pair on BTC/STAKE (e.g. BTC/USD) where we only buy alt-coins when BTC is doing well. Theoretically many alts perform well, or even better when BTC is doing poorly but more often than not the entire market follows the performance of BTC/USD and so we try to only make trades when BTC is looking bullish. | |
| 44 | + - Based on my testing when removing BTC/STAKE from the whitelist and using it as an informative provides a significant positive impact on strategy performance. *This feature can be disabled simply by having BTC/STAKE in your whitelist.* | |
| 45 | + - When stake is BTC or ETH, lets say we have XLM/BTC in our whitelist and our chosen stablecoin/fiat is USD. In this case XLM/USD and BTC/USD will be used as informative pairs for the XLM/BTC trade. Idea is if XLM/USD is strong, or BTC/USD is weak, then XLM/BTC is likely to go up. Conversely, if BTC/USD is very strong and XLM/USD is weak or neutral, then XLM/BTC is likely to go down. | |
| 46 | + | |
| 47 | +- **Dynamic ROI** | |
| 48 | + - To enable dynamic_roi for use you must set `use_dynamic_roi` to `True` | |
| 49 | + - Fundamentally, the idea is to override the base ROI table when an upward trend is present. This has been enhanced/extended in several ways. | |
| 50 | + - A sell will not happen when a strong enough upward trend is present, but a sell can happen when either the trend disappears or profit has retreated too far from the peak observed point and we are above the current `minimal_roi` table point. | |
| 51 | + | |
| 52 | +- **Custom Stoploss** | |
| 53 | + - To enable the custom_stoploss for use you must set `use_custom_stoploss` to `True` | |
| 54 | + - The stoploss is static as defined usually but a sell will happen if certain conditions are met. This is able to be hyperopted. | |
| 55 | + - If profit is below our defined threshold, and some conditions are met, sell. | |
| 56 | + - This is essentially just a sell trigger that uses an amount of profit (loss) as the primary guard. | |
| 57 | + | |
| 58 | +## Notes and Recommendations | |
| 45 | 59 | |
| 46 | 60 | - For whatever reason, hyperopt will not run from the child strategy, so point at SolipsisX (where X is the current version) directly in your hyperopt command. |
| 47 | -- If trading on a stablecoin or fiat stake (such as USD, EUR, USDT, etc.) is *highly recommended* that you remove BTC/STAKE from your whitelist as this strategy performs much better on alts when using BTC as an informative but does not buy any BTC itself. | |
| 48 | -- It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with "--enable-protections" as this strategy will hit a lot of stoplosses so the stoploss protection is helpful to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 61 | +- If trading on a stablecoin or fiat stake (such as USD, EUR, USDT, etc.) it is *highly recommended* that you remove BTC/STAKE from your whitelist as this strategy performs much better on alts when using BTC as an informative but does not buy any BTC itself. | |
| 62 | +- It is recommended to configure protections *if/as* you will use them in live and run *some* hyperopt/backtest with "--enable-protections" as this strategy will hit a lot of stoplosses (as we use it like a sell) so the stoploss protection is helpful to test. *However* - this option makes hyperopt very slow, so run your initial backtest/hyperopts without this option. Once you settle on a baseline set of options, do some final optimizations with protections on. | |
| 49 | 63 | - It is *not* recommended to use freqtrades built-in trailing stop, nor to hyperopt for that. |
| 50 | -- It is *highly* recommended to hyperopt this with '--spaces buy' only and at least 1000 total epochs several times. There are a lot of variables being hyperopted and it may take a lot of epochs to find the right settings. | |
| 51 | -- It is possible to hyperopt the custom stoploss and dynamic ROI settings, however a change to the freqtrade code is needed. I have done this in a fork on github and I use it personally, but this code will likely never get merged upstream so use with extreme caution. (https://github.com/werkkrew/freqtrade/tree/hyperopt) | |
| 64 | +- It is *highly* recommended to hyperopt this with '--spaces buy sell' only and at least 1000 total epochs several times. There are a lot of variables being hyperopted and it may take a lot of epochs to find the right settings. | |
| 65 | +- It is possible to hyperopt the custom stoploss and dynamic ROI settings, this is done by including the 'sell' space in your hyperopt. | |
| 52 | 66 | - Hyperopt Notes: |
| 53 | - - Hyperopting buy/custom-stoploss/dynamic-roi together takes a LOT of repeat 1000 epoch runs to get optimal results. There are a ton of variables moving around and often times the reported best epoch is not desirable. | |
| 54 | - - Avoid hyperopt results with small avg. profit and avg. duration of < 60m (in my opinion.) | |
| 55 | - - I find the best results come from SharpeHyperOptLoss | |
| 67 | + - `custom_stoploss` and `dynamic_roi` are hyperopted as part of the `sell` space. | |
| 68 | + - You need to set either (or both) `use_custom_stoploss` / `use_dynamic_roi` to `True` to make the sell space hyperopt these spaces, as well keep them enabled to have those settings impact a backtest or running strategy. You can hyperopt one space at a time by using different combinations of true/false here. | |
| 69 | + - Just food for thought, hyperopting buy/custom-stoploss/dynamic-roi together takes a LOT of repeat 1000 epoch runs to get optimal results. There are a ton of variables moving around and often times the **reported best epoch is not always desirable**, so make sure to look through the results and not just assume the "best" one is actually the best. | |
| 70 | + - Avoid hyperopt results with very small avg. profit and avg. duration of < 60m (in my opinion.) - This is best done by setting --min-trades to something as to prevent the loss function from going toward very small numbers of trades that inflate the loss function result. | |
| 71 | + - The hyperopt loss function you use will have a massive impact on how aggressive the strategy is. I find `Sharpe` to lean towards pretty aggresive buys and `SortinoDaily` to produce the most conservative results. | |
| 56 | 72 | - I personally re-run it until I find epochs with at least 0.5% avg profit and a 10:1 w/l ratio as my personal preference. |
| 57 | -- It is *recommended* to leave this file untouched and do your configuration / optimizations from the child strategy Solipsis.py. | |
| 58 | - | |
| 59 | -**Example of custom_pair_params format:** | |
| 60 | - | |
| 61 | -```python | |
| 62 | - custom_pair_params = [ | |
| 63 | - { | |
| 64 | - 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 65 | - 'buy_params': {}, | |
| 66 | - 'sell_params': {}, | |
| 67 | - 'minimal_roi': {}, | |
| 68 | - 'dynamic_roi': {}, | |
| 69 | - 'custom_stop': {} | |
| 70 | - } | |
| 71 | - ] | |
| 72 | -``` | |
| 73 | +- It is *recommended* to leave the base strategy file untouched and do your configuration from the child strategy Solipsis.py. | |
| 74 | +- You can adjust how aggressive/conservative the buy is by changing/restricting the hyperopt ranges, for example: | |
| 75 | + - Setting the minimum `base_ma_streak` value > 1 dramatically reduces the # of trades | |
| 76 | + - Changing optimize to False on the `base_trigger` and `xbtc_guard` and using default of `pcc` and `strict` respectively | |
| 77 | +- You might consider playing with some of the indicator periods defined, especially the `T3`, `mastreak`, and `pcc` as they have a rather dramatic impact. | |
| 73 | 78 | |
| 74 | 79 | ## Changelog |
| 75 | 80 | |
| 76 | 81 | **Note:** Comprehensive changelog has only been kept since v3, April 03, 2021 release. Prior change details are summary only. |
| 77 | 82 | |
| 78 | -v1: | |
| 79 | -``` | |
| 80 | -- Initial re-write of Schism v2. | |
| 81 | -- Moved sticking buy into ROI method | |
| 82 | -- Moved sell signal ideas into custom_stoploss | |
| 83 | -- Removed majority of 'populate_trades' | |
| 84 | -- Moved extranneous code and indicators out to custom_indicators helper file | |
| 85 | -- Added / Removed several indicators looking for a better buy signal, ultimately ended up keeping the primary Schism buy as it was. | |
| 86 | -``` | |
| 83 | +### v4 | |
| 84 | + | |
| 85 | +April 16, 2021: | |
| 86 | +- **General Changes** | |
| 87 | + - Updated README quite a bit to hopefully (probably not) cut down on questions. | |
| 88 | + - Added a RESULTS file to show some example results of the strategy. | |
| 89 | + - Hyperopt file and my hyperopt fork are no longer needed, **latest develop branch of freqtrade required**. | |
| 90 | + - Taking advantage of new "HyperStrategy" feature set means no more editing of hyperopt file and a clean way to hyperopt custom_stoploss and dynamic_roi without my forked hacks! | |
| 91 | + - custom_stoploss and dynamic_roi are hyperopted when using the 'sell' space, (e.g. include --spaces sell or --spaces buy sell) | |
| 92 | + - Cleaned up custom_indicators to remove some things I know I will definitely not be using. | |
| 93 | + - **Removed per-pair parameters support.** | |
| 94 | + - Keeping this working with the new changes to hyperopt would have been *some* amount of effort and I am personally not using this feature so I decided to just get rid of it. If you *really* want to use it, you can use the example code from Solipsis v3 to re-create it. | |
| 95 | + - After several rounds of extensive testing I found it very difficult to group pairs in any way that gave better results than the global hyperopted settings. | |
| 96 | + - Removed helper methods for updating price/trade data to simplify the contents of the file. | |
| 97 | +- **Indicator / Signal Changes** | |
| 98 | + - **Base Pair / Base Timeframe:** | |
| 99 | + - Changed the way the buy signal works a fair bit, counting occurrences of RMI downward trend, etc. | |
| 100 | + - Added MA Streak + PCC to the buy signal on base pair/base timeframe | |
| 101 | + - Added two triggers buy triggers with a hyperopt setting to choose which trigger to use | |
| 102 | + - **Base Pair / Informative Timeframe:** | |
| 103 | + - Changed upper ADR guard from 3d_low - 1d_high to 1d_low - 1d_high -> significant performance improvement | |
| 104 | + - Removed lower ADR guard. 90% of the time hyperopt decided to use upper only, the lower guard did not seem to have a big impact and removing it reduces the variables needed to optimize. | |
| 105 | + - **BTC/STAKE Informative Pair:** | |
| 106 | + - Removed informative timeframe from BTC/STAKE indicators. Base timeframe alone provides enough signals for our purposes. | |
| 107 | + - Adjusted base timeframe RMI period to be much longer (14 -> 55). | |
| 108 | + - Added a long T3 (144) to BTC/STAKE to stay out of the market when BTC is very bearish. | |
| 109 | + - Can be overridden by base pair being above T3 (233) so that if a particular pair is doing very well despite BTC it can be traded. | |
| 110 | + - BTC protection type is chose by hyperopt between `strict` (BTC guard only), `lazy` (BTC guard with base pair override), `none` (disable the BTC informative) | |
| 111 | + - **ETH and BTC as Stake Informatives:** | |
| 112 | + - Removed informative timeframe from BTC and ETH stake indicators. Base timeframe alone provides enough signals for our purposes. | |
| 113 | + | |
| 114 | +- **Custom Stoploss Changes** | |
| 115 | + - Almost completely stripped the previous custom_stoploss and dramatically simplified it. | |
| 116 | + - Got rid of positive trail options, in theory this is completely at odds with/redundant to the dynamic ROI feature set. | |
| 117 | + - Removed decay, stoploss is now a static stoploss unless something prompts us to get out earlier. | |
| 118 | + - Custom Stoploss is now exclusively a "dynamic bailout" intended to bail-out before the defined static stoploss point based on some factors: | |
| 119 | + - If current_profit is below the threshold value, allow a bailout. Bailout if some combination of the following are true: | |
| 120 | + - Rate of Change (ROC) is below the defined value. | |
| 121 | + - Amount of allowed time in trade has passed. | |
| 122 | + | |
| 123 | +- **Dynamic ROI Changes** | |
| 124 | + - Completely re-wrote dynamic ROI. It is now much simpler with far fewer options, highlights: | |
| 125 | + - No more options in terms of the fallback, it will now simply use the ROI table, or look for a trend. Dynamic ROI based on indicators seems to have potential but my implementation was not good. May look to re-implement this later with different indicators. | |
| 126 | + - Profit-pullback based on RMI and the profit_factor has been removed in favor of a static pullback value, similar to how a trailing stoploss would function. | |
| 127 | + - Got rid of RMI threshold growth over time. | |
| 128 | + - Added a hyperoptable option to enable/disable the peak pullback feature and if it should strictly respect the ROI table or not when a pullback occurs. | |
| 129 | + - Added options for what type of trend to use when holding onto a trade, this is part of the hyperopt for dynamic roi, currently choices are: `rmi`, `ssl`, `candle` or `any`. | |
| 130 | + - RMI uses the direction of the RMI indicator (3 out of 5 increasing), SSL uses SSL Channels with ATR, candle simply looks to see if the rolling window of 3 out of the last 5 candles have closed higher than the one before, any will consider it a trend if any of the above conditions are met. | |
| 131 | + | |
| 132 | +### v3 | |
| 133 | + | |
| 134 | +April 03, 2021: | |
| 135 | +- Moved header documentation into readme | |
| 136 | +- Fixed bug in 'get_pair_params' for minimal_roi per_pair settings | |
| 137 | + | |
| 138 | +Initial Release: | |
| 139 | +- Made dynamic_roi and custom_stoploss fully compliant with backtesting and hyperopt and validated results. | |
| 140 | +- Numerous bugfixes from previous versions | |
| 141 | +- Tons of changes that I failed to document | |
| 142 | + | |
| 143 | +### v2 | |
| 87 | 144 | |
| 88 | -v2: | |
| 89 | -``` | |
| 90 | 145 | - Fixed a significant bug in the custom_stoploss making part of it behave like a positive trail when it shouldn't have. |
| 91 | - - Added some other "modes" | |
| 146 | + - Added some other "modes" | |
| 92 | 147 | - Misc. de-clutter of some things |
| 93 | 148 | - Adjusted some hyperopt ranges a bit |
| 94 | 149 | - Removed PMAX indicator. I found in almost every hyperopt it was coming out disabled. It did not seem to add enough value to warrant the performance cost. |
| @@ -96,24 +151,17 @@ | ||
| 96 | 151 | - Removed the informative RSI indicator |
| 97 | 152 | - Removed the "uptrend" RMI stuff as well as the hyperopt to choose which is better (down trend was always better) |
| 98 | 153 | - Started some preliminary work to add BTC/STAKE on base and informative timeframes as an informative pair if it is not in whitelist. |
| 99 | - - Based on conversation with cyberd3vil it might be smart to blacklist BTC/USDT from trading and use it exclusively as an informative | |
| 100 | - for trading on alts. | |
| 101 | - - Added logic such that if BTC/STAKE is not in the whitelist, strategy automatically adds a couple additional indicators and conditions. | |
| 102 | - | |
| 103 | -``` | |
| 104 | - | |
| 105 | -v3: | |
| 106 | -``` | |
| 107 | -- Made dynamic_roi and custom_stoploss fully compliant with backtesting and hyperopt and validated results. | |
| 108 | -- Numerous bugfixes from previous versions | |
| 109 | - | |
| 110 | -April 03, 2021: | |
| 111 | -- Moved header documentation into readme | |
| 112 | -- Fixed bug in 'get_pair_params' for minimal_roi per_pair settings | |
| 113 | - | |
| 114 | -``` | |
| 154 | + - Based on conversation with cyberd3vil it might be smart to blacklist BTC/USDT from trading and use it exclusively as an informative for trading on alts. | |
| 155 | + - Added logic such that if BTC/STAKE is not in the whitelist, strategy automatically adds a couple additional indicators and conditions. | |
| 115 | 156 | |
| 157 | +### v1 | |
| 116 | 158 | |
| 159 | +- Initial re-write of Schism v2. | |
| 160 | +- Moved sticking buy into ROI method | |
| 161 | +- Moved sell signal ideas into custom_stoploss | |
| 162 | +- Removed majority of 'populate_trades' | |
| 163 | +- Moved extranneous code and indicators out to custom_indicators helper file | |
| 164 | +- Added / Removed several indicators looking for a better buy signal, ultimately ended up keeping the primary Schism buy as it was. | |
| 117 | 165 | |
| 118 | 166 | |
| 119 | 167 |
deleted hyperopts/SolipsisHyp_v3.py +0 −224
| @@ -1,224 +0,0 @@ | ||
| 1 | -from functools import reduce | |
| 2 | -from typing import Any, Callable, Dict, List | |
| 3 | - | |
| 4 | -import numpy as np | |
| 5 | -import pandas as pd | |
| 6 | -from pandas import DataFrame | |
| 7 | -from skopt.space import Categorical, Dimension, Integer, Real | |
| 8 | - | |
| 9 | -from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 10 | - | |
| 11 | -import talib.abstract as ta | |
| 12 | -import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 13 | - | |
| 14 | -class Solipsis3Hyp(IHyperOpt): | |
| 15 | - | |
| 16 | - @staticmethod | |
| 17 | - def indicator_space() -> List[Dimension]: | |
| 18 | - return [ | |
| 19 | - # Base Timeframe | |
| 20 | - Integer(20, 70, name='base-rmi-slow'), | |
| 21 | - Integer(30, 70, name='base-rmi-fast'), | |
| 22 | - Integer(30, 80, name='base-mp'), | |
| 23 | - # Informative Timeframe | |
| 24 | - Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 25 | - Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 26 | - Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 27 | - # Extra BTC/ETH Stakes | |
| 28 | - Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 29 | - Integer(10, 70, name='xtra-base-stake-rmi'), | |
| 30 | - Integer(10, 70, name='xtra-base-fiat-rmi'), | |
| 31 | - # Extra BTC/STAKE if not in whitelist | |
| 32 | - Integer(10, 70, name='xbtc-base-rmi'), | |
| 33 | - Integer(10, 70, name='xbtc-inf-rmi') | |
| 34 | - ] | |
| 35 | - | |
| 36 | - @staticmethod | |
| 37 | - def sell_indicator_space() -> List[Dimension]: | |
| 38 | - return [] | |
| 39 | - | |
| 40 | - @staticmethod | |
| 41 | - def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 42 | - | |
| 43 | - def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 44 | - conditions = [] | |
| 45 | - | |
| 46 | - """ | |
| 47 | - !!!!!!!! ALTER THESE PARAMETERS OR HYPEROPT WILL NOT DO THE RIGHT THINGS !!!!!!!! | |
| 48 | - inf_timeframe should match inf_timeframe from strategy | |
| 49 | - stake_currency should match your configured STAKE | |
| 50 | - custom_fiat should match the stablcoin you trade BTC or ETH pairs against (only relevant in BTC or ETH STAKES) | |
| 51 | - btc_in_whitelist should be self-explanatory | |
| 52 | - """ | |
| 53 | - | |
| 54 | - inf_timeframe = '1h' | |
| 55 | - stake_currency = 'USD' | |
| 56 | - custom_fiat = 'USD' | |
| 57 | - btc_in_whitelist = False | |
| 58 | - | |
| 59 | - if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 60 | - conditions.append( | |
| 61 | - (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 62 | - (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 63 | - ) | |
| 64 | - | |
| 65 | - if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 66 | - conditions.append( | |
| 67 | - (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 68 | - (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 69 | - ) | |
| 70 | - | |
| 71 | - conditions.append( | |
| 72 | - (dataframe['rmi-dn-trend'] == 1) & | |
| 73 | - (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 74 | - (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 75 | - (dataframe['mp'] <= params['base-mp']) | |
| 76 | - ) | |
| 77 | - | |
| 78 | - if stake_currency in ('BTC', 'ETH'): | |
| 79 | - conditions.append( | |
| 80 | - (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 81 | - (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 82 | - ) | |
| 83 | - conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 84 | - | |
| 85 | - else: | |
| 86 | - if btc_in_whitelist == False: | |
| 87 | - conditions.append( | |
| 88 | - (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 89 | - (dataframe[f"BTC_rmi_{inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 90 | - ) | |
| 91 | - | |
| 92 | - conditions.append(dataframe['volume'].gt(0)) | |
| 93 | - | |
| 94 | - if conditions: | |
| 95 | - dataframe.loc[ | |
| 96 | - reduce(lambda x, y: x & y, conditions), | |
| 97 | - 'buy'] = 1 | |
| 98 | - return dataframe | |
| 99 | - | |
| 100 | - return populate_buy_trend | |
| 101 | - | |
| 102 | - @staticmethod | |
| 103 | - def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 104 | - | |
| 105 | - def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 106 | - | |
| 107 | - dataframe['sell'] = 0 | |
| 108 | - return dataframe | |
| 109 | - | |
| 110 | - return populate_sell_trend | |
| 111 | - | |
| 112 | - # If not optimizing the sell space assume it is disabled entirely. | |
| 113 | - def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 114 | - | |
| 115 | - dataframe['sell'] = 0 | |
| 116 | - return dataframe | |
| 117 | - | |
| 118 | - @staticmethod | |
| 119 | - def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 120 | - | |
| 121 | - roi_table = {} | |
| 122 | - roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 123 | - roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 124 | - roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 125 | - roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 126 | - roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 127 | - roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 128 | - roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 129 | - | |
| 130 | - return roi_table | |
| 131 | - | |
| 132 | - @staticmethod | |
| 133 | - def roi_space() -> List[Dimension]: | |
| 134 | - # min / max min / max | |
| 135 | - return [ # 0 : 0.100 / 0.205 | |
| 136 | - Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 137 | - Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 138 | - Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 139 | - Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 140 | - Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 141 | - Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 142 | - | |
| 143 | - Real(0.05, 0.10, name='roi_p6'), | |
| 144 | - Real(0.02, 0.05, name='roi_p5'), | |
| 145 | - Real(0.015, 0.020, name='roi_p4'), | |
| 146 | - Real(0.005, 0.015, name='roi_p3'), | |
| 147 | - Real(0.005, 0.01, name='roi_p2'), | |
| 148 | - Real(0.005, 0.01, name='roi_p1'), | |
| 149 | - ] | |
| 150 | - | |
| 151 | - # None of this will work unless you pull the fork werkkrew/freqtrade and switch to branch hyperopt | |
| 152 | - # Which you almost certainly do *not* want to do. | |
| 153 | - # https://github.com/werkkrew/freqtrade/tree/hyperopt | |
| 154 | - @staticmethod | |
| 155 | - def generate_dynamic_roi(params: Dict) -> Dict[int, float]: | |
| 156 | - | |
| 157 | - dynamic_roi = { | |
| 158 | - 'enabled': params['droi_enabled'], | |
| 159 | - 'profit-factor': params['droi_profit_factor'], | |
| 160 | - 'rmi-start': params['droi_rmi_start'], | |
| 161 | - 'rmi-end': params['droi_rmi_end'], | |
| 162 | - 'grow-delay': params['droi_grow_delay'], | |
| 163 | - 'grow-time': params['droi_grow_time'], | |
| 164 | - 'fallback': params['droi_fallback'], | |
| 165 | - 'min-roc-atr': params['droi_min_roc_atr'] | |
| 166 | - } | |
| 167 | - | |
| 168 | - return dynamic_roi | |
| 169 | - | |
| 170 | - @staticmethod | |
| 171 | - def dynamic_roi_space() -> List[Dimension]: | |
| 172 | - | |
| 173 | - return [ | |
| 174 | - Categorical([True], name='droi_enabled'), | |
| 175 | - # Categorical([True, False], name='droi_enabled'), | |
| 176 | - Integer(200, 500, name='droi_profit_factor'), | |
| 177 | - Integer(0, 50, name='droi_rmi_start'), | |
| 178 | - Integer(50, 90, name='droi_rmi_end'), | |
| 179 | - Integer(0, 180, name='droi_grow_delay'), | |
| 180 | - Integer(360, 1440, name='droi_grow_time'), | |
| 181 | - # Categorical(['table'], name='droi_fallback'), | |
| 182 | - Categorical(['table', 'atr', 'roc', 'roc-table', 'atr-table'], name='droi_fallback'), | |
| 183 | - Real(0.005, 0.015, name='droi_min_roc_atr') | |
| 184 | - ] | |
| 185 | - | |
| 186 | - | |
| 187 | - @staticmethod | |
| 188 | - def generate_custom_stop(params: Dict) -> Dict[int, float]: | |
| 189 | - | |
| 190 | - custom_stop = { | |
| 191 | - 'decay-time': params['cstp_decay_time'], | |
| 192 | - 'decay-delay': params['cstp_decay_delay'], | |
| 193 | - 'decay-start': params['cstp_decay_start'], | |
| 194 | - 'decay-end': params['cstp_decay_end'], | |
| 195 | - 'cur-min-diff': params['cstp_cur_min_diff'], | |
| 196 | - 'cur-threshold': params['cstp_cur_threshold'], | |
| 197 | - 'roc-bail': params['cstp_roc_bail'], | |
| 198 | - 'rmi-trend': params['cstp_rmi_trend'], | |
| 199 | - 'bail-how': params['cstp_bail_how'], | |
| 200 | - 'pos-trail': params['cstp_pos_trail'], | |
| 201 | - 'pos-threshold': params['cstp_pos_threshold'], | |
| 202 | - 'pos-trail-dist': params['cstp_trail_dist'] | |
| 203 | - } | |
| 204 | - | |
| 205 | - return custom_stop | |
| 206 | - | |
| 207 | - @staticmethod | |
| 208 | - def custom_stoploss_space() -> List[Dimension]: | |
| 209 | - | |
| 210 | - return [ | |
| 211 | - Integer(300, 1440, name='cstp_decay_time'), | |
| 212 | - Integer(0, 180, name='cstp_decay_delay'), | |
| 213 | - Real(-0.35, -0.15, name='cstp_decay_start'), | |
| 214 | - Real(-0.05, 0, name='cstp_decay_end'), | |
| 215 | - Real(0.01, 0.04, name='cstp_cur_min_diff'), | |
| 216 | - Real(-0.05, 0, name='cstp_cur_threshold'), | |
| 217 | - Real(-0.05, 0, name='cstp_roc_bail'), | |
| 218 | - Integer(30, 70, name='cstp_rmi_trend'), | |
| 219 | - Categorical(['atr', 'immediate'], name='cstp_bail_how'), | |
| 220 | - # Categorical([False], name='cstp_pos_trail'), | |
| 221 | - Categorical([True, False], name='cstp_pos_trail'), | |
| 222 | - Real(0.0, 0.03, name='cstp_pos_threshold'), | |
| 223 | - Real(0.005, 0.03, name='cstp_trail_dist') | |
| 224 | - ] | |
| No newline at the end of the file |
added hyperopts/old/SolipsisHyp_v3.py +224 −0
| @@ -0,0 +1,224 @@ | ||
| 1 | +from functools import reduce | |
| 2 | +from typing import Any, Callable, Dict, List | |
| 3 | + | |
| 4 | +import numpy as np | |
| 5 | +import pandas as pd | |
| 6 | +from pandas import DataFrame | |
| 7 | +from skopt.space import Categorical, Dimension, Integer, Real | |
| 8 | + | |
| 9 | +from freqtrade.optimize.hyperopt_interface import IHyperOpt | |
| 10 | + | |
| 11 | +import talib.abstract as ta | |
| 12 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 13 | + | |
| 14 | +class Solipsis3Hyp(IHyperOpt): | |
| 15 | + | |
| 16 | + @staticmethod | |
| 17 | + def indicator_space() -> List[Dimension]: | |
| 18 | + return [ | |
| 19 | + # Base Timeframe | |
| 20 | + Integer(20, 70, name='base-rmi-slow'), | |
| 21 | + Integer(30, 70, name='base-rmi-fast'), | |
| 22 | + Integer(30, 80, name='base-mp'), | |
| 23 | + # Informative Timeframe | |
| 24 | + Categorical(['lower', 'upper', 'both', 'none'], name='inf-guard'), | |
| 25 | + Real(0.70, 0.99, name='inf-pct-adr-top'), | |
| 26 | + Real(0.01, 0.20, name='inf-pct-adr-bot'), | |
| 27 | + # Extra BTC/ETH Stakes | |
| 28 | + Integer(10, 70, name='xtra-inf-stake-rmi'), | |
| 29 | + Integer(10, 70, name='xtra-base-stake-rmi'), | |
| 30 | + Integer(10, 70, name='xtra-base-fiat-rmi'), | |
| 31 | + # Extra BTC/STAKE if not in whitelist | |
| 32 | + Integer(10, 70, name='xbtc-base-rmi'), | |
| 33 | + Integer(10, 70, name='xbtc-inf-rmi') | |
| 34 | + ] | |
| 35 | + | |
| 36 | + @staticmethod | |
| 37 | + def sell_indicator_space() -> List[Dimension]: | |
| 38 | + return [] | |
| 39 | + | |
| 40 | + @staticmethod | |
| 41 | + def buy_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 42 | + | |
| 43 | + def populate_buy_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 44 | + conditions = [] | |
| 45 | + | |
| 46 | + """ | |
| 47 | + !!!!!!!! ALTER THESE PARAMETERS OR HYPEROPT WILL NOT DO THE RIGHT THINGS !!!!!!!! | |
| 48 | + inf_timeframe should match inf_timeframe from strategy | |
| 49 | + stake_currency should match your configured STAKE | |
| 50 | + custom_fiat should match the stablcoin you trade BTC or ETH pairs against (only relevant in BTC or ETH STAKES) | |
| 51 | + btc_in_whitelist should be self-explanatory | |
| 52 | + """ | |
| 53 | + | |
| 54 | + inf_timeframe = '1h' | |
| 55 | + stake_currency = 'USD' | |
| 56 | + custom_fiat = 'USD' | |
| 57 | + btc_in_whitelist = False | |
| 58 | + | |
| 59 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 60 | + conditions.append( | |
| 61 | + (dataframe['close'] <= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 62 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 63 | + ) | |
| 64 | + | |
| 65 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 66 | + conditions.append( | |
| 67 | + (dataframe['close'] >= dataframe[f"3d_low_{inf_timeframe}"] + | |
| 68 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{inf_timeframe}"])) | |
| 69 | + ) | |
| 70 | + | |
| 71 | + conditions.append( | |
| 72 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 73 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 74 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 75 | + (dataframe['mp'] <= params['base-mp']) | |
| 76 | + ) | |
| 77 | + | |
| 78 | + if stake_currency in ('BTC', 'ETH'): | |
| 79 | + conditions.append( | |
| 80 | + (dataframe[f"{stake_currency}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 81 | + (dataframe[f"{custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 82 | + ) | |
| 83 | + conditions.append(dataframe[f"{stake_currency}_rmi_{inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 84 | + | |
| 85 | + else: | |
| 86 | + if btc_in_whitelist == False: | |
| 87 | + conditions.append( | |
| 88 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 89 | + (dataframe[f"BTC_rmi_{inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 90 | + ) | |
| 91 | + | |
| 92 | + conditions.append(dataframe['volume'].gt(0)) | |
| 93 | + | |
| 94 | + if conditions: | |
| 95 | + dataframe.loc[ | |
| 96 | + reduce(lambda x, y: x & y, conditions), | |
| 97 | + 'buy'] = 1 | |
| 98 | + return dataframe | |
| 99 | + | |
| 100 | + return populate_buy_trend | |
| 101 | + | |
| 102 | + @staticmethod | |
| 103 | + def sell_strategy_generator(params: Dict[str, Any]) -> Callable: | |
| 104 | + | |
| 105 | + def populate_sell_trend(dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 106 | + | |
| 107 | + dataframe['sell'] = 0 | |
| 108 | + return dataframe | |
| 109 | + | |
| 110 | + return populate_sell_trend | |
| 111 | + | |
| 112 | + # If not optimizing the sell space assume it is disabled entirely. | |
| 113 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 114 | + | |
| 115 | + dataframe['sell'] = 0 | |
| 116 | + return dataframe | |
| 117 | + | |
| 118 | + @staticmethod | |
| 119 | + def generate_roi_table(params: Dict) -> Dict[int, float]: | |
| 120 | + | |
| 121 | + roi_table = {} | |
| 122 | + roi_table[0] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] + params['roi_p6'] | |
| 123 | + roi_table[params['roi_t6']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] + params['roi_p5'] | |
| 124 | + roi_table[params['roi_t6'] + params['roi_t5']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] + params['roi_p4'] | |
| 125 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4']] = params['roi_p1'] + params['roi_p2'] + params['roi_p3'] | |
| 126 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3']] = params['roi_p1'] + params['roi_p2'] | |
| 127 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2']] = params['roi_p1'] | |
| 128 | + roi_table[params['roi_t6'] + params['roi_t5'] + params['roi_t4'] + params['roi_t3'] + params['roi_t2'] + params['roi_t1']] = 0 | |
| 129 | + | |
| 130 | + return roi_table | |
| 131 | + | |
| 132 | + @staticmethod | |
| 133 | + def roi_space() -> List[Dimension]: | |
| 134 | + # min / max min / max | |
| 135 | + return [ # 0 : 0.100 / 0.205 | |
| 136 | + Integer(1, 20, name='roi_t6'), # 1 -> 20 : 0.050 / 0.105 | |
| 137 | + Integer(10, 20, name='roi_t5'), # 11 -> 40 : 0.030 / 0.055 | |
| 138 | + Integer(10, 20, name='roi_t4'), # 21 -> 60 : 0.015 / 0.035 | |
| 139 | + Integer(15, 30, name='roi_t3'), # 36 -> 90 : 0.010 / 0.020 | |
| 140 | + Integer(264, 630, name='roi_t2'), # 300 -> 720 : 0.005 / 0.010 | |
| 141 | + Integer(420, 720, name='roi_t1'), # 720 -> 1440 : 0 | |
| 142 | + | |
| 143 | + Real(0.05, 0.10, name='roi_p6'), | |
| 144 | + Real(0.02, 0.05, name='roi_p5'), | |
| 145 | + Real(0.015, 0.020, name='roi_p4'), | |
| 146 | + Real(0.005, 0.015, name='roi_p3'), | |
| 147 | + Real(0.005, 0.01, name='roi_p2'), | |
| 148 | + Real(0.005, 0.01, name='roi_p1'), | |
| 149 | + ] | |
| 150 | + | |
| 151 | + # None of this will work unless you pull the fork werkkrew/freqtrade and switch to branch hyperopt | |
| 152 | + # Which you almost certainly do *not* want to do. | |
| 153 | + # https://github.com/werkkrew/freqtrade/tree/hyperopt | |
| 154 | + @staticmethod | |
| 155 | + def generate_dynamic_roi(params: Dict) -> Dict[int, float]: | |
| 156 | + | |
| 157 | + dynamic_roi = { | |
| 158 | + 'enabled': params['droi_enabled'], | |
| 159 | + 'profit-factor': params['droi_profit_factor'], | |
| 160 | + 'rmi-start': params['droi_rmi_start'], | |
| 161 | + 'rmi-end': params['droi_rmi_end'], | |
| 162 | + 'grow-delay': params['droi_grow_delay'], | |
| 163 | + 'grow-time': params['droi_grow_time'], | |
| 164 | + 'fallback': params['droi_fallback'], | |
| 165 | + 'min-roc-atr': params['droi_min_roc_atr'] | |
| 166 | + } | |
| 167 | + | |
| 168 | + return dynamic_roi | |
| 169 | + | |
| 170 | + @staticmethod | |
| 171 | + def dynamic_roi_space() -> List[Dimension]: | |
| 172 | + | |
| 173 | + return [ | |
| 174 | + Categorical([True], name='droi_enabled'), | |
| 175 | + # Categorical([True, False], name='droi_enabled'), | |
| 176 | + Integer(200, 500, name='droi_profit_factor'), | |
| 177 | + Integer(0, 50, name='droi_rmi_start'), | |
| 178 | + Integer(50, 90, name='droi_rmi_end'), | |
| 179 | + Integer(0, 180, name='droi_grow_delay'), | |
| 180 | + Integer(360, 1440, name='droi_grow_time'), | |
| 181 | + # Categorical(['table'], name='droi_fallback'), | |
| 182 | + Categorical(['table', 'atr', 'roc', 'roc-table', 'atr-table'], name='droi_fallback'), | |
| 183 | + Real(0.005, 0.015, name='droi_min_roc_atr') | |
| 184 | + ] | |
| 185 | + | |
| 186 | + | |
| 187 | + @staticmethod | |
| 188 | + def generate_custom_stop(params: Dict) -> Dict[int, float]: | |
| 189 | + | |
| 190 | + custom_stop = { | |
| 191 | + 'decay-time': params['cstp_decay_time'], | |
| 192 | + 'decay-delay': params['cstp_decay_delay'], | |
| 193 | + 'decay-start': params['cstp_decay_start'], | |
| 194 | + 'decay-end': params['cstp_decay_end'], | |
| 195 | + 'cur-min-diff': params['cstp_cur_min_diff'], | |
| 196 | + 'cur-threshold': params['cstp_cur_threshold'], | |
| 197 | + 'roc-bail': params['cstp_roc_bail'], | |
| 198 | + 'rmi-trend': params['cstp_rmi_trend'], | |
| 199 | + 'bail-how': params['cstp_bail_how'], | |
| 200 | + 'pos-trail': params['cstp_pos_trail'], | |
| 201 | + 'pos-threshold': params['cstp_pos_threshold'], | |
| 202 | + 'pos-trail-dist': params['cstp_trail_dist'] | |
| 203 | + } | |
| 204 | + | |
| 205 | + return custom_stop | |
| 206 | + | |
| 207 | + @staticmethod | |
| 208 | + def custom_stoploss_space() -> List[Dimension]: | |
| 209 | + | |
| 210 | + return [ | |
| 211 | + Integer(300, 1440, name='cstp_decay_time'), | |
| 212 | + Integer(0, 180, name='cstp_decay_delay'), | |
| 213 | + Real(-0.35, -0.15, name='cstp_decay_start'), | |
| 214 | + Real(-0.05, 0, name='cstp_decay_end'), | |
| 215 | + Real(0.01, 0.04, name='cstp_cur_min_diff'), | |
| 216 | + Real(-0.05, 0, name='cstp_cur_threshold'), | |
| 217 | + Real(-0.05, 0, name='cstp_roc_bail'), | |
| 218 | + Integer(30, 70, name='cstp_rmi_trend'), | |
| 219 | + Categorical(['atr', 'immediate'], name='cstp_bail_how'), | |
| 220 | + # Categorical([False], name='cstp_pos_trail'), | |
| 221 | + Categorical([True, False], name='cstp_pos_trail'), | |
| 222 | + Real(0.0, 0.03, name='cstp_pos_threshold'), | |
| 223 | + Real(0.005, 0.03, name='cstp_trail_dist') | |
| 224 | + ] | |
| No newline at the end of the file |
modified strategies/Solipsis.py +26 −180
| @@ -3,42 +3,28 @@ | ||
| 3 | 3 | from pathlib import Path |
| 4 | 4 | sys.path.append(str(Path(__file__).parent)) |
| 5 | 5 | |
| 6 | -from Solipsis_v3 import Solipsis3 as Solipsis | |
| 6 | +from Solipsis_v4 import Solipsis4 as Solipsis | |
| 7 | 7 | |
| 8 | 8 | """ |
| 9 | 9 | *** THIS IS YOUR LIVE TRADING COPY *** |
| 10 | 10 | *** THIS IS A CHILD STRATEGY, REQUIRES IMPORT OF PARENT STRATEGY ** |
| 11 | -*** CURRENTLY MAPS TO PARENT STRATEGY: Solipsis_v3 *** | |
| 12 | - | |
| 13 | -NOTE: Child strategy seems to have issues being used for hyperopt, I am not completely sure why. | |
| 14 | - Call hyperopts using the parent strategy (e.g. --strategy Solipsis3 --hyperopt Solipsis3Hyp ) | |
| 15 | - The child strategy is best used for keeping the parent strategy clean when using custom_pair_params | |
| 16 | - in live trading and backtest, but is not required. | |
| 17 | - | |
| 18 | -Example for Custom Pair Params: | |
| 19 | - | |
| 20 | - custom_pair_params = [ | |
| 21 | - { | |
| 22 | - 'pairs': ('ABC/XYZ', 'DEF/XYZ'), | |
| 23 | - 'buy_params': {}, | |
| 24 | - 'sell_params': {}, | |
| 25 | - 'minimal_roi': {} | |
| 26 | - } | |
| 11 | +*** CURRENTLY MAPS TO PARENT STRATEGY: Solipsis_v4 *** | |
| 27 | 12 | |
| 28 | 13 | LAST OPTIMIZED: |
| 29 | 14 | |
| 30 | -EXCHANGE: | |
| 15 | +EXCHANGE: Kraken, full pairlists with some personally selected blacklisted coins | |
| 31 | 16 | |
| 32 | -USD - | |
| 33 | -BTC - | |
| 34 | -ETH - | |
| 17 | +Stake Date Optimized | |
| 18 | +----------|---------------- | |
| 19 | +USD | |
| 20 | +BTC | |
| 21 | +ETH | |
| 22 | + | |
| 23 | + | |
| 24 | +Optimization / Backtest Results for Current Live Instance Settings | |
| 25 | +USD | |
| 26 | + | |
| 35 | 27 | |
| 36 | -USD - | |
| 37 | - Global: | |
| 38 | - 5m / 1h | |
| 39 | - 20210301- / Sharpe / DROI / CSTP | |
| 40 | - | |
| 41 | - Pairlists (Sorted/grouped by avg. profit in global backtests): | |
| 42 | 28 | |
| 43 | 29 | """ |
| 44 | 30 | # Sub-strategy with parameters specific to USD stake |
| @@ -49,194 +35,54 @@ | ||
| 49 | 35 | |
| 50 | 36 | minimal_roi = { |
| 51 | 37 | "0": 0.01, |
| 52 | - "360": 0.005, | |
| 53 | - "720": 0 | |
| 54 | - } | |
| 55 | - | |
| 56 | - # Global for not in custom_pair_params | |
| 57 | - buy_params = { | |
| 58 | - 'base-mp': 61, | |
| 59 | - 'base-rmi-fast': 65, | |
| 60 | - 'base-rmi-slow': 27, | |
| 61 | - 'inf-guard': 'lower', | |
| 62 | - 'inf-pct-adr-bot': 0.14002, | |
| 63 | - 'inf-pct-adr-top': 0.98205, | |
| 64 | - 'xbtc-base-rmi': 56, | |
| 65 | - 'xbtc-inf-rmi': 17, | |
| 66 | - 'xtra-base-fiat-rmi': 45, | |
| 67 | - 'xtra-base-stake-rmi': 69, | |
| 68 | - 'xtra-inf-stake-rmi': 27 | |
| 69 | - } | |
| 70 | - | |
| 71 | - # Global for not in custom_pair_params | |
| 72 | - dynamic_roi = { | |
| 73 | - 'enabled': True, | |
| 74 | - 'profit-factor': 308, | |
| 75 | - 'rmi-start': 48, | |
| 76 | - 'rmi-end': 53, | |
| 77 | - 'grow-delay': 17, | |
| 78 | - 'grow-time': 770, | |
| 79 | - 'fallback': 'table', | |
| 80 | - 'min-roc-atr': 0.0075 | |
| 81 | - } | |
| 82 | - | |
| 83 | - # Global for not in custom_pair_params | |
| 84 | - custom_stop = { | |
| 85 | - 'decay-time': 1058, | |
| 86 | - 'decay-delay': 131, | |
| 87 | - 'decay-start': -0.23, | |
| 88 | - 'decay-end': -0.043, | |
| 89 | - 'cur-min-diff': 0.03, | |
| 90 | - 'cur-threshold': -0.0056, | |
| 91 | - 'roc-bail': -0.01, | |
| 92 | - 'rmi-trend': 50, | |
| 93 | - 'bail-how': 'immediate', | |
| 94 | - 'pos-trail': False, | |
| 95 | - 'pos-threshold': 0.005, | |
| 96 | - 'pos-trail-dist': 0.015 | |
| 38 | + "1440": 0 | |
| 97 | 39 | } |
| 98 | 40 | |
| 99 | - stoploss = custom_stop['decay-start'] | |
| 41 | + use_dynamic_roi = True | |
| 100 | 42 | use_custom_stoploss = True |
| 101 | 43 | |
| 102 | - custom_pair_params = [] | |
| 44 | + stoploss = -0.10 | |
| 103 | 45 | |
| 104 | 46 | """ |
| 105 | -BTC - | |
| 106 | - Global: | |
| 107 | - 15m / 4h | |
| 108 | - 20210301- / Sharpe / DROI / CSTP | |
| 109 | - | |
| 47 | +Optimization / Backtest Results for Current Live Instance Settings | |
| 48 | +BTC | |
| 110 | 49 | |
| 111 | - Pairlists (Sorted/grouped by avg. profit in global backtests): | |
| 112 | 50 | |
| 113 | 51 | """ |
| 114 | 52 | # Sub-strategy with parameters specific to BTC stake |
| 115 | 53 | class Solipsis_BTC(Solipsis): |
| 116 | 54 | |
| 117 | - timeframe = '15m' | |
| 55 | + timeframe = '5m' | |
| 118 | 56 | inf_timeframe = '1h' |
| 119 | 57 | |
| 120 | 58 | minimal_roi = { |
| 121 | 59 | "0": 0.01, |
| 122 | - "720": 0.005, | |
| 123 | 60 | "1440": 0 |
| 124 | 61 | } |
| 125 | 62 | |
| 126 | - # Global for not in custom_pair_params | |
| 127 | - buy_params = { | |
| 128 | - 'base-mp': 36, | |
| 129 | - 'base-rmi-fast': 45, | |
| 130 | - 'base-rmi-slow': 36, | |
| 131 | - 'inf-guard': 'none', | |
| 132 | - 'inf-pct-adr-bot': 0.08671, | |
| 133 | - 'inf-pct-adr-top': 0.95097, | |
| 134 | - 'xbtc-base-rmi': 55, | |
| 135 | - 'xbtc-inf-rmi': 20, | |
| 136 | - 'xtra-base-fiat-rmi': 22, | |
| 137 | - 'xtra-base-stake-rmi': 62, | |
| 138 | - 'xtra-inf-stake-rmi': 68 | |
| 139 | - } | |
| 140 | - | |
| 141 | - # Global for not in custom_pair_params | |
| 142 | - dynamic_roi = { | |
| 143 | - 'enabled': True, | |
| 144 | - 'profit-factor': 400, | |
| 145 | - 'rmi-start': 11, | |
| 146 | - 'rmi-end': 72, | |
| 147 | - 'grow-delay': 137, | |
| 148 | - 'grow-time': 371, | |
| 149 | - 'fallback': 'roc', | |
| 150 | - 'min-roc-atr': 0.0025 | |
| 151 | - } | |
| 152 | - | |
| 153 | - # Global for not in custom_pair_params | |
| 154 | - custom_stop = { | |
| 155 | - 'decay-time': 761, | |
| 156 | - 'decay-delay': 122, | |
| 157 | - 'decay-start': -0.23, | |
| 158 | - 'decay-end': -0.001, | |
| 159 | - 'cur-min-diff': 0.013, | |
| 160 | - 'cur-threshold': -0.027, | |
| 161 | - 'roc-bail': -0.01068, | |
| 162 | - 'rmi-trend': 36, | |
| 163 | - 'bail-how': 'immediate', | |
| 164 | - 'pos-trail': True, | |
| 165 | - 'pos-threshold': 0.003, | |
| 166 | - 'pos-trail-dist': 0.016 | |
| 167 | - } | |
| 168 | - | |
| 169 | - stoploss = custom_stop['decay-start'] | |
| 63 | + use_dynamic_roi = True | |
| 170 | 64 | use_custom_stoploss = True |
| 171 | 65 | |
| 172 | - custom_pair_params = [] | |
| 66 | + stoploss = -0.10 | |
| 173 | 67 | |
| 174 | 68 | """ |
| 175 | -ETH - | |
| 176 | - Global: | |
| 177 | - 1h / 4h | |
| 178 | - 20210301- / Sharpe / DROI / CSTP | |
| 179 | - | |
| 69 | +Optimization / Backtest Results for Current Live Instance Settings | |
| 70 | +ETH | |
| 180 | 71 | |
| 181 | - Pairlists (Sorted/grouped by avg. profit in global backtests): | |
| 182 | 72 | |
| 183 | 73 | """ |
| 184 | 74 | # Sub-strategy with parameters specific to ETH stake |
| 185 | 75 | class Solipsis_ETH(Solipsis): |
| 186 | 76 | |
| 187 | - timeframe = '15m' | |
| 77 | + timeframe = '5m' | |
| 188 | 78 | inf_timeframe = '1h' |
| 189 | 79 | |
| 190 | 80 | minimal_roi = { |
| 191 | 81 | "0": 0.01, |
| 192 | - "720": 0.005, | |
| 193 | 82 | "1440": 0 |
| 194 | 83 | } |
| 195 | 84 | |
| 196 | - # Global for not in custom_pair_params | |
| 197 | - buy_params = { | |
| 198 | - 'base-mp': 60, | |
| 199 | - 'base-rmi-fast': 47, | |
| 200 | - 'base-rmi-slow': 20, | |
| 201 | - 'inf-guard': 'upper', | |
| 202 | - 'inf-pct-adr-bot': 0.17062, | |
| 203 | - 'inf-pct-adr-top': 0.7037, | |
| 204 | - 'xbtc-base-rmi': 27, | |
| 205 | - 'xbtc-inf-rmi': 69, | |
| 206 | - 'xtra-base-fiat-rmi': 32, | |
| 207 | - 'xtra-base-stake-rmi': 43, | |
| 208 | - 'xtra-inf-stake-rmi': 61 | |
| 209 | - } | |
| 210 | - | |
| 211 | - # Global for not in custom_pair_params | |
| 212 | - dynamic_roi = { | |
| 213 | - 'enabled': True, | |
| 214 | - 'profit-factor': 448, | |
| 215 | - 'rmi-start': 6, | |
| 216 | - 'rmi-end': 60, | |
| 217 | - 'grow-delay': 20, | |
| 218 | - 'grow-time': 1158, | |
| 219 | - 'fallback': 'roc', | |
| 220 | - 'min-roc-atr': 0.0025 | |
| 221 | - } | |
| 222 | - | |
| 223 | - # Global for not in custom_pair_params | |
| 224 | - custom_stop = { | |
| 225 | - 'decay-time': 1159, | |
| 226 | - 'decay-delay': 183, | |
| 227 | - 'decay-start': -0.25, | |
| 228 | - 'decay-end': -0.0225, | |
| 229 | - 'cur-min-diff': 0.0317, | |
| 230 | - 'cur-threshold': -0.04, | |
| 231 | - 'roc-bail': -0.034, | |
| 232 | - 'rmi-trend': 50, | |
| 233 | - 'bail-how': 'atr', | |
| 234 | - 'pos-trail': True, | |
| 235 | - 'pos-threshold': 0.0225, | |
| 236 | - 'pos-trail-dist': 0.01 | |
| 237 | - } | |
| 238 | - | |
| 239 | - stoploss = custom_stop['decay-start'] | |
| 85 | + use_dynamic_roi = True | |
| 240 | 86 | use_custom_stoploss = True |
| 241 | 87 | |
| 242 | - custom_pair_params = [] | |
| No newline at the end of the file | ||
| 88 | + stoploss = -0.10 | |
| No newline at the end of the file |
deleted strategies/Solipsis_v3.py +0 −558
| @@ -1,558 +0,0 @@ | ||
| 1 | -import numpy as np | |
| 2 | -import talib.abstract as ta | |
| 3 | -import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | -import arrow | |
| 5 | - | |
| 6 | -from freqtrade.strategy.interface import IStrategy | |
| 7 | -from freqtrade.strategy import merge_informative_pair, stoploss_from_open | |
| 8 | -from typing import Dict, List, Optional, Tuple | |
| 9 | -from pandas import DataFrame, Series | |
| 10 | -from functools import reduce | |
| 11 | -from datetime import datetime, timedelta | |
| 12 | -from freqtrade.persistence import Trade | |
| 13 | -from cachetools import TTLCache | |
| 14 | - | |
| 15 | -# Get rid of pandas warnings during backtesting | |
| 16 | -import pandas as pd | |
| 17 | -pd.options.mode.chained_assignment = None # default='warn' | |
| 18 | - | |
| 19 | -# Strategy specific imports, files must reside in same folder as strategy | |
| 20 | -import sys | |
| 21 | -from pathlib import Path | |
| 22 | -sys.path.append(str(Path(__file__).parent)) | |
| 23 | - | |
| 24 | -import custom_indicators as cta | |
| 25 | - | |
| 26 | -""" | |
| 27 | -Solipsis - By @werkkrew | |
| 28 | - | |
| 29 | -Credits - | |
| 30 | -@JimmyNixx for many of the ideas used throughout as well as helping me stay motivated throughout development! | |
| 31 | -@JoeSchr for documenting and doing the legwork of getting indicators to be available in the custom_stoploss | |
| 32 | - | |
| 33 | -We ask for nothing in return except that if you make changes which bring you greater success than what has been provided, you share those ideas back to us | |
| 34 | -and the rest of the community. Also, please don't nag us with a million questions and especially don't blame us if you lose a ton of money using this. | |
| 35 | - | |
| 36 | -We take no responsibility for any success or failure you have using this strategy. | |
| 37 | -""" | |
| 38 | - | |
| 39 | -class Solipsis3(IStrategy): | |
| 40 | - | |
| 41 | - # Recommended for USD/USDT/etc. | |
| 42 | - timeframe = '5m' | |
| 43 | - inf_timeframe = '1h' | |
| 44 | - | |
| 45 | - buy_params = { | |
| 46 | - 'base-mp': 30, | |
| 47 | - 'base-rmi-fast': 50, | |
| 48 | - 'base-rmi-slow': 30, | |
| 49 | - 'inf-guard': 'upper', | |
| 50 | - 'inf-pct-adr-bot': 0.10, | |
| 51 | - 'inf-pct-adr-top': 0.85, | |
| 52 | - 'xbtc-base-rmi': 50, | |
| 53 | - 'xbtc-inf-rmi': 20, | |
| 54 | - 'xtra-base-fiat-rmi': 45, | |
| 55 | - 'xtra-base-stake-rmi': 69, | |
| 56 | - 'xtra-inf-stake-rmi': 27 | |
| 57 | - } | |
| 58 | - | |
| 59 | - sell_params = {} | |
| 60 | - | |
| 61 | - # Custom buy/sell parameters per pair | |
| 62 | - custom_pair_params = [] | |
| 63 | - | |
| 64 | - # Recommended on 5m timeframe | |
| 65 | - minimal_roi = { | |
| 66 | - "0": 0.01, | |
| 67 | - "360": 0.005, | |
| 68 | - "720": 0 | |
| 69 | - } | |
| 70 | - | |
| 71 | - dynamic_roi = { | |
| 72 | - 'enabled': True, # enable dynamic roi which uses trennds and indicators to dynamically manipulate the roi table | |
| 73 | - 'profit-factor': 400, # factor for forumla of how far below peak profit to trigger sell | |
| 74 | - 'rmi-start': 30, # starting value for rmi-slow to be considered a positive trend | |
| 75 | - 'rmi-end': 70, # ending value | |
| 76 | - 'grow-delay': 0, # delay on growth | |
| 77 | - 'grow-time': 720, # finish time of growth | |
| 78 | - 'fallback': 'table', # if no trend, do what? (table, roc, atr, roc-table, atr-table) | |
| 79 | - 'min-roc-atr': 0.0075 # minimum roi value to return in roc or atr mode | |
| 80 | - } | |
| 81 | - | |
| 82 | - use_custom_stoploss = True | |
| 83 | - custom_stop = { | |
| 84 | - # Linear Decay Parameters | |
| 85 | - 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 86 | - 'decay-delay': 0, # minutes to wait before decay starts | |
| 87 | - 'decay-start': -0.30, # starting value: should be the same or smaller than initial stoploss | |
| 88 | - 'decay-end': -0.03, # ending value | |
| 89 | - # Profit and TA | |
| 90 | - 'cur-min-diff': 0.03, # diff between current and minimum profit to move stoploss up to min profit point | |
| 91 | - 'cur-threshold': -0.02, # how far negative should current profit be before we consider moving it up based on cur/min or roc | |
| 92 | - 'roc-bail': -0.03, # value for roc to use for dynamic bailout | |
| 93 | - 'rmi-trend': 50, # rmi-slow value to pause stoploss decay | |
| 94 | - 'bail-how': 'immediate', # set the stoploss to the atr offset below current price, or immediate | |
| 95 | - # Positive Trailing | |
| 96 | - 'pos-trail': False, # enable trailing once positive | |
| 97 | - 'pos-threshold': 0.005, # trail after how far positive | |
| 98 | - 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 99 | - } | |
| 100 | - | |
| 101 | - stoploss = custom_stop['decay-start'] | |
| 102 | - | |
| 103 | - # Recommended | |
| 104 | - use_sell_signal = False | |
| 105 | - sell_profit_only = False | |
| 106 | - ignore_roi_if_buy_signal = False | |
| 107 | - | |
| 108 | - # Required | |
| 109 | - startup_candle_count: int = 72 | |
| 110 | - process_only_new_candles = False | |
| 111 | - | |
| 112 | - # Strategy Specific Variable Storage | |
| 113 | - custom_trade_info = {} | |
| 114 | - custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 115 | - custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 116 | - | |
| 117 | - """ | |
| 118 | - Informative Pair Definitions | |
| 119 | - """ | |
| 120 | - def informative_pairs(self): | |
| 121 | - # add all whitelisted pairs on informative timeframe | |
| 122 | - pairs = self.dp.current_whitelist() | |
| 123 | - informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 124 | - | |
| 125 | - # add extra informative pairs if the stake is BTC or ETH | |
| 126 | - if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 127 | - for pair in pairs: | |
| 128 | - coin, stake = pair.split('/') | |
| 129 | - coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 130 | - informative_pairs += [(coin_fiat, self.timeframe)] | |
| 131 | - | |
| 132 | - stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 133 | - informative_pairs += [(stake_fiat, self.timeframe)] | |
| 134 | - informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 135 | - # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 136 | - else: | |
| 137 | - btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 138 | - if not btc_stake in pairs: | |
| 139 | - informative_pairs += [(btc_stake, self.timeframe)] | |
| 140 | - informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 141 | - | |
| 142 | - return informative_pairs | |
| 143 | - | |
| 144 | - """ | |
| 145 | - Indicator Definitions | |
| 146 | - """ | |
| 147 | - def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 148 | - # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 149 | - self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 150 | - | |
| 151 | - # Base timeframe indicators | |
| 152 | - dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 153 | - dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 154 | - | |
| 155 | - # Indicators for ROI and Custom Stoploss | |
| 156 | - dataframe['atr'] = ta.ATR(dataframe, timeperiod=24) | |
| 157 | - dataframe['roc'] = ta.ROC(dataframe, timeperiod=9) | |
| 158 | - | |
| 159 | - # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 160 | - dataframe['roc-mp'] = ta.ROC(dataframe, timeperiod=6) | |
| 161 | - dataframe['mp'] = ta.RSI(dataframe['roc-mp'], timeperiod=6) | |
| 162 | - | |
| 163 | - # Trends, Peaks and Crosses | |
| 164 | - dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 165 | - dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 166 | - dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 167 | - dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 168 | - | |
| 169 | - # Base pair informative timeframe indicators | |
| 170 | - informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 171 | - | |
| 172 | - # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 173 | - informative['1d_high'] = informative['close'].rolling(24).max() | |
| 174 | - informative['3d_low'] = informative['close'].rolling(72).min() | |
| 175 | - informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 176 | - | |
| 177 | - dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 178 | - | |
| 179 | - # Other stake specific informative indicators | |
| 180 | - # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 181 | - if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 182 | - coin, stake = metadata['pair'].split('/') | |
| 183 | - fiat = self.custom_fiat | |
| 184 | - coin_fiat = f"{coin}/{fiat}" | |
| 185 | - stake_fiat = f"{stake}/{fiat}" | |
| 186 | - | |
| 187 | - # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 188 | - coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 189 | - dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 190 | - | |
| 191 | - # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 192 | - stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 193 | - dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 194 | - | |
| 195 | - # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 196 | - stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 197 | - stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 198 | - dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 199 | - | |
| 200 | - # Informatives for BTC/STAKE if not in whitelist | |
| 201 | - else: | |
| 202 | - pairs = self.dp.current_whitelist() | |
| 203 | - btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 204 | - if not btc_stake in pairs: | |
| 205 | - # BTC/STAKE - Base Timeframe | |
| 206 | - btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 207 | - dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 208 | - | |
| 209 | - # BTC/STAKE - Informative Timeframe | |
| 210 | - btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 211 | - btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 212 | - dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 213 | - | |
| 214 | - # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 215 | - if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 216 | - self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date') | |
| 217 | - self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date') | |
| 218 | - self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 219 | - self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 220 | - | |
| 221 | - return dataframe | |
| 222 | - | |
| 223 | - """ | |
| 224 | - Buy Signal | |
| 225 | - """ | |
| 226 | - def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 227 | - params = self.get_pair_params(metadata['pair'], 'buy') | |
| 228 | - conditions = [] | |
| 229 | - | |
| 230 | - # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 231 | - if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 232 | - conditions.append( | |
| 233 | - (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 234 | - (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 235 | - ) | |
| 236 | - | |
| 237 | - if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 238 | - conditions.append( | |
| 239 | - (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 240 | - (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 241 | - ) | |
| 242 | - | |
| 243 | - # Base Timeframe | |
| 244 | - conditions.append( | |
| 245 | - (dataframe['rmi-dn-trend'] == 1) & | |
| 246 | - (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 247 | - (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 248 | - (dataframe['mp'] <= params['base-mp']) | |
| 249 | - ) | |
| 250 | - | |
| 251 | - # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 252 | - if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 253 | - conditions.append( | |
| 254 | - (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 255 | - (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 256 | - ) | |
| 257 | - conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 258 | - # Extra conditions for BTC/STAKE if not in whitelist | |
| 259 | - else: | |
| 260 | - pairs = self.dp.current_whitelist() | |
| 261 | - btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 262 | - if not btc_stake in pairs: | |
| 263 | - conditions.append( | |
| 264 | - (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 265 | - (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 266 | - ) | |
| 267 | - | |
| 268 | - conditions.append(dataframe['volume'].gt(0)) | |
| 269 | - | |
| 270 | - if conditions: | |
| 271 | - dataframe.loc[ | |
| 272 | - reduce(lambda x, y: x & y, conditions), | |
| 273 | - 'buy'] = 1 | |
| 274 | - | |
| 275 | - return dataframe | |
| 276 | - | |
| 277 | - """ | |
| 278 | - Sell Signal | |
| 279 | - """ | |
| 280 | - def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 281 | - # params = self.get_pair_params(metadata['pair'], 'sell') | |
| 282 | - | |
| 283 | - dataframe['sell'] = 0 | |
| 284 | - | |
| 285 | - return dataframe | |
| 286 | - | |
| 287 | - """ | |
| 288 | - Custom Stoploss | |
| 289 | - """ | |
| 290 | - def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 291 | - params = self.custom_stop | |
| 292 | - | |
| 293 | - trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 294 | - min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 295 | - max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 296 | - profit_diff = current_profit - min_profit | |
| 297 | - current_stoploss = trade.stop_loss | |
| 298 | - | |
| 299 | - decay_stoploss = cta.linear_growth(params['decay-start'], params['decay-end'], params['decay-delay'], params['decay-time'], trade_dur) | |
| 300 | - | |
| 301 | - # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 302 | - if params['pos-trail'] == True: | |
| 303 | - if current_profit > params['pos-threshold']: | |
| 304 | - return current_profit - params['pos-trail-dist'] | |
| 305 | - | |
| 306 | - if self.config['runmode'].value in ('live', 'dry_run'): | |
| 307 | - dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 308 | - roc = dataframe['roc'].iat[-1] | |
| 309 | - atr = dataframe['atr'].iat[-1] | |
| 310 | - rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 311 | - # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 312 | - else: | |
| 313 | - roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 314 | - atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 315 | - rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 316 | - | |
| 317 | - if current_profit < params['cur-threshold']: | |
| 318 | - # Dynamic bailout based on rate of change | |
| 319 | - if (roc/100) <= params['roc-bail']: | |
| 320 | - if params['bail-how'] == 'atr': | |
| 321 | - return ((current_rate - atr)/current_rate) - 1 | |
| 322 | - elif params['bail-how'] == 'immediate': | |
| 323 | - return 0.001 | |
| 324 | - else: | |
| 325 | - return min(max(stoploss_from_open(decay_stoploss, current_profit), 0.001), current_stoploss) | |
| 326 | - | |
| 327 | - # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 328 | - if (current_profit > min_profit) or roc > 0 or rmi_slow >= params['rmi-trend']: | |
| 329 | - if profit_diff > params['cur-min-diff'] and current_profit < 0: | |
| 330 | - return stoploss_from_open(min_profit, current_profit) | |
| 331 | - return 1 | |
| 332 | - | |
| 333 | - if current_profit < 0: | |
| 334 | - return min(max(stoploss_from_open(decay_stoploss, current_profit), 0.001), current_stoploss) | |
| 335 | - | |
| 336 | - return 1 | |
| 337 | - | |
| 338 | - """ | |
| 339 | - Freqtrade ROI Overload for dynamic ROI functionality | |
| 340 | - """ | |
| 341 | - def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 342 | - | |
| 343 | - dynamic_roi = self.get_pair_params(trade.pair, 'dynamic_roi') | |
| 344 | - minimal_roi = self.get_pair_params(trade.pair, 'minimal_roi') | |
| 345 | - | |
| 346 | - if not dynamic_roi or not minimal_roi: | |
| 347 | - return None, None | |
| 348 | - | |
| 349 | - _, table_roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 350 | - | |
| 351 | - # see if we have the data we need to do this, otherwise fall back to the standard table | |
| 352 | - if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 353 | - if self.config['runmode'].value in ('live', 'dry_run'): | |
| 354 | - dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 355 | - roc = dataframe['roc'].iat[-1] | |
| 356 | - atr = dataframe['atr'].iat[-1] | |
| 357 | - rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 358 | - rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 359 | - # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 360 | - else: | |
| 361 | - roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 362 | - atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 363 | - rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 364 | - rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 365 | - | |
| 366 | - d = dynamic_roi | |
| 367 | - open_rate = trade.open_rate | |
| 368 | - max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 369 | - | |
| 370 | - atr_roi = max(d['min-roc-atr'], ((open_rate + atr) / open_rate) - 1) | |
| 371 | - roc_roi = max(d['min-roc-atr'], (roc/100)) | |
| 372 | - | |
| 373 | - # atr as the fallback (if > min-roc-atr) | |
| 374 | - if d['fallback'] == 'atr': | |
| 375 | - min_roi = atr_roi | |
| 376 | - # roc as the fallback (if > min-roc-atr) | |
| 377 | - elif d['fallback'] == 'roc': | |
| 378 | - min_roi = roc_roi | |
| 379 | - # atr or table as the fallback (whichever is larger) | |
| 380 | - elif d['fallback'] == 'atr-table': | |
| 381 | - min_roi = max(table_roi, atr_roi) | |
| 382 | - # roc or table as the fallback (whichever is larger) | |
| 383 | - elif d['fallback'] == 'roc-table': | |
| 384 | - min_roi = max(table_roi, roc_roi) | |
| 385 | - # default to table | |
| 386 | - else: | |
| 387 | - min_roi = table_roi | |
| 388 | - | |
| 389 | - rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 390 | - profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 391 | - pullback_buffer = (max_profit * profit_factor) | |
| 392 | - | |
| 393 | - # If we observe a strong upward trend and our current profit has not retreated from the peak by much, hold | |
| 394 | - if (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 395 | - if (current_profit < pullback_buffer) and max_profit > min_roi: | |
| 396 | - # allow immediate bailout if we were above the ROI point and retreated below it | |
| 397 | - min_roi = current_profit / 2 | |
| 398 | - else: | |
| 399 | - min_roi = 100 | |
| 400 | - | |
| 401 | - else: | |
| 402 | - min_roi = table_roi | |
| 403 | - | |
| 404 | - return trade_dur, min_roi | |
| 405 | - | |
| 406 | - # Minor change to the usual method here to allow feeding the pair for per-pair settings | |
| 407 | - def min_roi_reached_entry(self, trade_dur: int, pair: str = 'backtest') -> Tuple[Optional[int], Optional[float]]: | |
| 408 | - minimal_roi = self.get_pair_params(pair, 'minimal_roi') | |
| 409 | - | |
| 410 | - roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 411 | - if not roi_list: | |
| 412 | - return None, None | |
| 413 | - roi_entry = max(roi_list) | |
| 414 | - min_roi = minimal_roi[roi_entry] | |
| 415 | - | |
| 416 | - return roi_entry, min_roi | |
| 417 | - | |
| 418 | - # Change here to allow loading of the dynamic_roi settings | |
| 419 | - def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 420 | - trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 421 | - | |
| 422 | - if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 423 | - _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 424 | - else: | |
| 425 | - _, roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 426 | - if roi is None: | |
| 427 | - return False | |
| 428 | - else: | |
| 429 | - return current_profit > roi | |
| 430 | - | |
| 431 | - """ | |
| 432 | - Trade Timeout Overloads | |
| 433 | - """ | |
| 434 | - def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 435 | - bid_strategy = self.config.get('bid_strategy', {}) | |
| 436 | - ob = self.dp.orderbook(pair, 1) | |
| 437 | - current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 438 | - if current_price > order['price'] * 1.01: | |
| 439 | - return True | |
| 440 | - return False | |
| 441 | - | |
| 442 | - def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 443 | - ask_strategy = self.config.get('ask_strategy', {}) | |
| 444 | - ob = self.dp.orderbook(pair, 1) | |
| 445 | - current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 446 | - if current_price < order['price'] * 0.99: | |
| 447 | - return True | |
| 448 | - return False | |
| 449 | - | |
| 450 | - """ | |
| 451 | - Custom Methods | |
| 452 | - """ | |
| 453 | - # Get parameters for various settings on a per pair or group of pairs basis | |
| 454 | - # This function can probably be simplified dramatically | |
| 455 | - def get_pair_params(self, pair: str, params: str) -> Dict: | |
| 456 | - buy_params, sell_params = self.buy_params, self.sell_params | |
| 457 | - minimal_roi, dynamic_roi = self.minimal_roi, self.dynamic_roi | |
| 458 | - custom_stop = self.custom_stop | |
| 459 | - | |
| 460 | - if self.custom_pair_params: | |
| 461 | - # custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 462 | - for item in self.custom_pair_params: | |
| 463 | - if 'pairs' in item and pair in item['pairs']: | |
| 464 | - custom_params = item | |
| 465 | - if 'buy_params' in custom_params: | |
| 466 | - buy_params = custom_params['buy_params'] | |
| 467 | - if 'sell_params' in custom_params: | |
| 468 | - sell_params = custom_params['sell_params'] | |
| 469 | - if 'minimal_roi' in custom_params: | |
| 470 | - minimal_roi = custom_params['minimal_roi'] | |
| 471 | - if 'custom_stop' in custom_params: | |
| 472 | - custom_stop = custom_params['custom_stop'] | |
| 473 | - if 'dynamic_roi' in custom_params: | |
| 474 | - dynamic_roi = custom_params['dynamic_roi'] | |
| 475 | - break | |
| 476 | - | |
| 477 | - if params == 'buy': | |
| 478 | - return buy_params | |
| 479 | - if params == 'sell': | |
| 480 | - return sell_params | |
| 481 | - if params == 'minimal_roi': | |
| 482 | - return minimal_roi | |
| 483 | - if params == 'custom_stop': | |
| 484 | - return custom_stop | |
| 485 | - if params == 'dynamic_roi': | |
| 486 | - return dynamic_roi | |
| 487 | - | |
| 488 | - return False | |
| 489 | - | |
| 490 | - # Get the current price from the exchange (or local cache) | |
| 491 | - def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 492 | - if not refresh: | |
| 493 | - rate = self.custom_current_price_cache.get(pair) | |
| 494 | - # Check if cache has been invalidated | |
| 495 | - if rate: | |
| 496 | - return rate | |
| 497 | - | |
| 498 | - ask_strategy = self.config.get('ask_strategy', {}) | |
| 499 | - if ask_strategy.get('use_order_book', False): | |
| 500 | - ob = self.dp.orderbook(pair, 1) | |
| 501 | - rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 502 | - else: | |
| 503 | - ticker = self.dp.ticker(pair) | |
| 504 | - rate = ticker['last'] | |
| 505 | - | |
| 506 | - self.custom_current_price_cache[pair] = rate | |
| 507 | - return rate | |
| 508 | - | |
| 509 | - """ | |
| 510 | - Stripped down version from Schism, meant only to update the price data a bit | |
| 511 | - more frequently than the default instead of getting all sorts of trade information | |
| 512 | - """ | |
| 513 | - def populate_trades(self, pair: str) -> dict: | |
| 514 | - # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 515 | - if not pair in self.custom_trade_info: | |
| 516 | - self.custom_trade_info[pair] = {} | |
| 517 | - | |
| 518 | - # init the temp dicts and set the trade stuff to false | |
| 519 | - trade_data = {} | |
| 520 | - trade_data['active_trade'] = False | |
| 521 | - | |
| 522 | - # active trade stuff only works in live and dry, not backtest | |
| 523 | - if self.config['runmode'].value in ('live', 'dry_run'): | |
| 524 | - | |
| 525 | - # find out if we have an open trade for this pair | |
| 526 | - active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 527 | - | |
| 528 | - # if so, get some information | |
| 529 | - if active_trade: | |
| 530 | - # get current price and update the min/max rate | |
| 531 | - current_rate = self.get_current_price(pair, True) | |
| 532 | - active_trade[0].adjust_min_max_rates(current_rate) | |
| 533 | - | |
| 534 | - return trade_data | |
| 535 | - | |
| 536 | -# Sub-strategy with parameters specific to BTC stake | |
| 537 | -class Solipsis3_BTC(Solipsis3): | |
| 538 | - | |
| 539 | - timeframe = '15m' | |
| 540 | - inf_timeframe = '1h' | |
| 541 | - | |
| 542 | - minimal_roi = { | |
| 543 | - "0": 0.01, | |
| 544 | - "720": 0.005, | |
| 545 | - "1440": 0 | |
| 546 | - } | |
| 547 | - | |
| 548 | -# Sub-strategy with parameters specific to ETH stake | |
| 549 | -class Solipsis3_ETH(Solipsis3): | |
| 550 | - | |
| 551 | - timeframe = '15m' | |
| 552 | - inf_timeframe = '1h' | |
| 553 | - | |
| 554 | - minimal_roi = { | |
| 555 | - "0": 0.01, | |
| 556 | - "720": 0.005, | |
| 557 | - "1440": 0 | |
| 558 | - } | |
| No newline at the end of the file |
added strategies/Solipsis_v4.py +444 −0
| @@ -0,0 +1,444 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | + | |
| 6 | +from freqtrade.strategy.interface import IStrategy | |
| 7 | +from freqtrade.strategy import merge_informative_pair, stoploss_from_open, IntParameter, DecimalParameter, CategoricalParameter | |
| 8 | +from typing import Dict, List, Optional, Tuple | |
| 9 | +from pandas import DataFrame, Series | |
| 10 | +from functools import reduce | |
| 11 | +from datetime import datetime, timedelta | |
| 12 | +from freqtrade.persistence import Trade | |
| 13 | + | |
| 14 | +# Get rid of pandas warnings during backtesting | |
| 15 | +import pandas as pd | |
| 16 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 17 | + | |
| 18 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 19 | +import sys | |
| 20 | +from pathlib import Path | |
| 21 | +sys.path.append(str(Path(__file__).parent)) | |
| 22 | + | |
| 23 | +import custom_indicators as cta | |
| 24 | + | |
| 25 | +""" | |
| 26 | +Solipsis - By @werkkrew | |
| 27 | + | |
| 28 | +Credits - | |
| 29 | +@JimmyNixx for many of the ideas used throughout as well as helping me stay motivated throughout development! | |
| 30 | +@JoeSchr for documenting and doing the legwork of getting indicators to be available in the custom_stoploss | |
| 31 | + | |
| 32 | +We ask for nothing in return except that if you make changes which bring you greater success than what has been provided, you share those ideas back to us | |
| 33 | +and the rest of the community. Also, please don't nag us with a million questions and especially don't blame us if you lose a ton of money using this. | |
| 34 | + | |
| 35 | +We take no responsibility for any success or failure you have using this strategy. | |
| 36 | +""" | |
| 37 | + | |
| 38 | +class Solipsis4(IStrategy): | |
| 39 | + | |
| 40 | + ## Buy Space Hyperopt Variables | |
| 41 | + | |
| 42 | + # Base Pair Params | |
| 43 | + base_mp = IntParameter(10, 50, default=30, space='buy') | |
| 44 | + base_rmi_max = IntParameter(30, 60, default=50, space='buy') | |
| 45 | + base_rmi_min = IntParameter(0, 30, default=20, space='buy') | |
| 46 | + base_ma_streak = IntParameter(1, 4, default=1, space='buy') | |
| 47 | + base_rmi_streak = IntParameter(3, 8, default=3, space='buy') | |
| 48 | + base_trigger = CategoricalParameter(['pcc', 'rmi', 'none'], default='rmi', space='buy', optimize=False) | |
| 49 | + inf_pct_adr = DecimalParameter(0.70, 0.99, default=0.80, space='buy') | |
| 50 | + # BTC Informative | |
| 51 | + xbtc_guard = CategoricalParameter(['strict', 'lazy', 'none'], default='lazy', space='buy', optimize=True) | |
| 52 | + xbtc_base_rmi = IntParameter(20, 70, default=40, space='buy') | |
| 53 | + # BTC / ETH Stake Parameters | |
| 54 | + xtra_base_stake_rmi = IntParameter(10, 50, default=50, space='buy') | |
| 55 | + xtra_base_fiat_rmi = IntParameter(30, 70, default=50, space='buy') | |
| 56 | + | |
| 57 | + ## Sell Space Params are being "hijacked" for custom_stoploss and dynamic_roi | |
| 58 | + | |
| 59 | + # Dynamic ROI | |
| 60 | + droi_trend_type = CategoricalParameter(['rmi', 'ssl', 'candle', 'any'], default='any', space='sell', optimize=True) | |
| 61 | + droi_pullback = CategoricalParameter([True, False], default=True, space='sell', optimize=True) | |
| 62 | + droi_pullback_amount = DecimalParameter(0.005, 0.02, default=0.005, space='sell') | |
| 63 | + droi_pullback_respect_table = CategoricalParameter([True, False], default=False, space='sell', optimize=True) | |
| 64 | + | |
| 65 | + # Custom Stoploss | |
| 66 | + cstp_threshold = DecimalParameter(-0.05, 0, default=-0.03, space='sell') | |
| 67 | + cstp_bail_how = CategoricalParameter(['roc', 'time', 'any'], default='roc', space='sell', optimize=True) | |
| 68 | + cstp_bail_roc = DecimalParameter(-0.05, -0.01, default=-0.03, space='sell') | |
| 69 | + cstp_bail_time = IntParameter(720, 1440, default=720, space='sell') | |
| 70 | + | |
| 71 | + timeframe = '5m' | |
| 72 | + inf_timeframe = '1h' | |
| 73 | + | |
| 74 | + buy_params = { | |
| 75 | + 'base_ma_streak': 1, | |
| 76 | + 'base_mp': 12, | |
| 77 | + 'base_rmi_max': 50, | |
| 78 | + 'base_rmi_min': 20, | |
| 79 | + 'base_rmi_streak': 3, | |
| 80 | + 'inf_pct_adr': 950, | |
| 81 | + 'xbtc_base_rmi': 20, | |
| 82 | + 'xbtc_guard': 'none', | |
| 83 | + 'xtra_base_fiat_rmi': 45, | |
| 84 | + 'xtra_base_stake_rmi': 13 | |
| 85 | + } | |
| 86 | + | |
| 87 | + sell_params = { | |
| 88 | + 'droi_pullback': True, | |
| 89 | + 'droi_pullback_amount': 0.006, | |
| 90 | + 'droi_pullback_respect_table': False, | |
| 91 | + 'droi_trend_type': 'any' | |
| 92 | + } | |
| 93 | + | |
| 94 | + minimal_roi = { | |
| 95 | + "0": 0.01, | |
| 96 | + "1440": 0 | |
| 97 | + } | |
| 98 | + | |
| 99 | + # Enable or disable these as desired | |
| 100 | + # Must be enabled when hyperopting the respective spaces | |
| 101 | + use_dynamic_roi = True | |
| 102 | + use_custom_stoploss = True | |
| 103 | + | |
| 104 | + stoploss = -0.10 | |
| 105 | + | |
| 106 | + # Recommended | |
| 107 | + use_sell_signal = False | |
| 108 | + sell_profit_only = False | |
| 109 | + ignore_roi_if_buy_signal = False | |
| 110 | + | |
| 111 | + # Required | |
| 112 | + startup_candle_count: int = 233 | |
| 113 | + process_only_new_candles = False | |
| 114 | + | |
| 115 | + # Strategy Specific Variable Storage | |
| 116 | + custom_trade_info = {} | |
| 117 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 118 | + custom_btc_inf = False # Don't change this. | |
| 119 | + | |
| 120 | + """ | |
| 121 | + Informative Pair Definitions | |
| 122 | + """ | |
| 123 | + def informative_pairs(self): | |
| 124 | + # add all whitelisted pairs on informative timeframe | |
| 125 | + pairs = self.dp.current_whitelist() | |
| 126 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 127 | + | |
| 128 | + # add extra informative pairs if the stake is BTC or ETH | |
| 129 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 130 | + for pair in pairs: | |
| 131 | + coin, stake = pair.split('/') | |
| 132 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 133 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 134 | + | |
| 135 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 136 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 137 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 138 | + else: | |
| 139 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 140 | + if not btc_stake in pairs: | |
| 141 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 142 | + | |
| 143 | + return informative_pairs | |
| 144 | + | |
| 145 | + """ | |
| 146 | + Indicator Definitions | |
| 147 | + """ | |
| 148 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 149 | + if not metadata['pair'] in self.custom_trade_info: | |
| 150 | + self.custom_trade_info[metadata['pair']] = {} | |
| 151 | + | |
| 152 | + ## Base Timeframe / Pair | |
| 153 | + | |
| 154 | + # T3: https://www.tradingview.com/script/qzoC9H1I-T3-Average/ | |
| 155 | + dataframe['T3'] = cta.T3(dataframe, length=233) | |
| 156 | + | |
| 157 | + # RMI: https://www.tradingview.com/script/kwIt9OgQ-Relative-Momentum-Index/ | |
| 158 | + dataframe['rmi'] = cta.RMI(dataframe, length=24, mom=5) | |
| 159 | + | |
| 160 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 161 | + dataframe['roc-mp'] = ta.ROC(dataframe, timeperiod=1) | |
| 162 | + dataframe['mp'] = ta.RSI(dataframe['roc-mp'], timeperiod=3) | |
| 163 | + | |
| 164 | + # MA Streak: https://www.tradingview.com/script/Yq1z7cIv-MA-Streak-Can-Show-When-a-Run-Is-Getting-Long-in-the-Tooth/ | |
| 165 | + dataframe['mastreak'] = cta.mastreak(dataframe, period=4) | |
| 166 | + | |
| 167 | + # Percent Change Channel: https://www.tradingview.com/script/6wwAWXA1-MA-Streak-Change-Channel/ | |
| 168 | + upper, mid, lower = cta.pcc(dataframe, period=40, mult=3) | |
| 169 | + dataframe['pcc-lowerband'] = lower | |
| 170 | + dataframe['pcc-upperband'] = upper | |
| 171 | + | |
| 172 | + lookup_idxs = dataframe.index.values - (abs(dataframe['mastreak'].values) + 1) | |
| 173 | + valid_lookups = lookup_idxs >= 0 | |
| 174 | + dataframe['sbc'] = np.nan | |
| 175 | + dataframe.loc[valid_lookups, 'sbc'] = dataframe['close'].to_numpy()[lookup_idxs[valid_lookups].astype(int)] | |
| 176 | + | |
| 177 | + dataframe['streak-roc'] = 100 * (dataframe['close'] - dataframe['sbc']) / dataframe['sbc'] | |
| 178 | + | |
| 179 | + # Trends, Peaks and Crosses | |
| 180 | + dataframe['candle-up'] = np.where(dataframe['close'] >= dataframe['close'].shift(),1,0) | |
| 181 | + dataframe['candle-up-trend'] = np.where(dataframe['candle-up'].rolling(5).sum() >= 3,1,0) | |
| 182 | + | |
| 183 | + dataframe['rmi-up'] = np.where(dataframe['rmi'] >= dataframe['rmi'].shift(),1,0) | |
| 184 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(5).sum() >= 3,1,0) | |
| 185 | + | |
| 186 | + dataframe['rmi-dn'] = np.where(dataframe['rmi'] <= dataframe['rmi'].shift(),1,0) | |
| 187 | + dataframe['rmi-dn-count'] = dataframe['rmi-dn'].rolling(8).sum() | |
| 188 | + | |
| 189 | + dataframe['streak-bo'] = np.where(dataframe['streak-roc'] < dataframe['pcc-lowerband'],1,0) | |
| 190 | + dataframe['streak-bo-count'] = dataframe['streak-bo'].rolling(8).sum() | |
| 191 | + | |
| 192 | + # Indicators used only for ROI and Custom Stoploss | |
| 193 | + ssldown, sslup = cta.SSLChannels_ATR(dataframe, length=21) | |
| 194 | + dataframe['sroc'] = cta.SROC(dataframe, roclen=21, emalen=13, smooth=21) | |
| 195 | + dataframe['ssl-dir'] = np.where(sslup > ssldown,'up','down') | |
| 196 | + | |
| 197 | + # Base pair informative timeframe indicators | |
| 198 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 199 | + | |
| 200 | + # Get the "average day range" between the 1d high and 1d low to set up guards | |
| 201 | + informative['1d-high'] = informative['close'].rolling(24).max() | |
| 202 | + informative['1d-low'] = informative['close'].rolling(24).min() | |
| 203 | + informative['adr'] = informative['1d-high'] - informative['1d-low'] | |
| 204 | + | |
| 205 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 206 | + | |
| 207 | + # Other stake specific informative indicators | |
| 208 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 209 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 210 | + coin, stake = metadata['pair'].split('/') | |
| 211 | + fiat = self.custom_fiat | |
| 212 | + coin_fiat = f"{coin}/{fiat}" | |
| 213 | + stake_fiat = f"{stake}/{fiat}" | |
| 214 | + | |
| 215 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 216 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 217 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=55, mom=5) | |
| 218 | + | |
| 219 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 220 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 221 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=55, mom=5) | |
| 222 | + | |
| 223 | + # Informatives for BTC/STAKE if not in whitelist | |
| 224 | + else: | |
| 225 | + pairs = self.dp.current_whitelist() | |
| 226 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 227 | + if not btc_stake in pairs: | |
| 228 | + self.custom_btc_inf = True | |
| 229 | + # BTC/STAKE - Base Timeframe | |
| 230 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 231 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=55, mom=5) | |
| 232 | + dataframe['BTC_close'] = btc_stake_tf['close'] | |
| 233 | + dataframe['BTC_T3'] = cta.T3(btc_stake_tf, length=144) | |
| 234 | + | |
| 235 | + # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 236 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 237 | + self.custom_trade_info[metadata['pair']]['sroc'] = dataframe[['date', 'sroc']].copy().set_index('date') | |
| 238 | + self.custom_trade_info[metadata['pair']]['ssl-dir'] = dataframe[['date', 'ssl-dir']].copy().set_index('date') | |
| 239 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 240 | + self.custom_trade_info[metadata['pair']]['candle-up-trend'] = dataframe[['date', 'candle-up-trend']].copy().set_index('date') | |
| 241 | + | |
| 242 | + return dataframe | |
| 243 | + | |
| 244 | + """ | |
| 245 | + Buy Signal | |
| 246 | + """ | |
| 247 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 248 | + conditions = [] | |
| 249 | + | |
| 250 | + # Informative Timeframe Guards | |
| 251 | + conditions.append( | |
| 252 | + (dataframe['close'] <= dataframe[f"1d-low_{self.inf_timeframe}"] + | |
| 253 | + (self.inf_pct_adr.value * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 254 | + ) | |
| 255 | + | |
| 256 | + # Base Timeframe Guards | |
| 257 | + conditions.append( | |
| 258 | + (dataframe['rmi-dn-count'] >= self.base_rmi_streak.value) & | |
| 259 | + (dataframe['streak-bo-count'] >= self.base_ma_streak.value) & | |
| 260 | + (dataframe['rmi'] <= self.base_rmi_max.value) & | |
| 261 | + (dataframe['rmi'] >= self.base_rmi_min.value) & | |
| 262 | + (dataframe['mp'] <= self.base_mp.value) | |
| 263 | + ) | |
| 264 | + | |
| 265 | + # Base Timeframe Trigger | |
| 266 | + if self.base_trigger.value == 'pcc': | |
| 267 | + conditions.append(qtpylib.crossed_above(dataframe['streak-roc'], dataframe['pcc-lowerband'])) | |
| 268 | + | |
| 269 | + if self.base_trigger.value == 'rmi': | |
| 270 | + conditions.append(dataframe['rmi-up-trend'] == 1) | |
| 271 | + | |
| 272 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 273 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 274 | + conditions.append( | |
| 275 | + (dataframe[f"{self.custom_fiat}_rmi"] > self.xtra_base_fiat_rmi.value) | | |
| 276 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < self.xtra_base_stake_rmi.value) | |
| 277 | + ) | |
| 278 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 279 | + else: | |
| 280 | + if self.custom_btc_inf: | |
| 281 | + if self.xbtc_guard.value == 'strict': | |
| 282 | + conditions.append( | |
| 283 | + ( | |
| 284 | + (dataframe['BTC_rmi'] > self.xbtc_base_rmi.value) & | |
| 285 | + (dataframe['BTC_close'] > dataframe['BTC_T3']) | |
| 286 | + ) | |
| 287 | + ) | |
| 288 | + if self.xbtc_guard.value == 'lazy': | |
| 289 | + conditions.append( | |
| 290 | + (dataframe['close'] > dataframe['T3']) | | |
| 291 | + ( | |
| 292 | + (dataframe['BTC_rmi'] > self.xbtc_base_rmi.value) & | |
| 293 | + (dataframe['BTC_close'] > dataframe['BTC_T3']) | |
| 294 | + ) | |
| 295 | + ) | |
| 296 | + | |
| 297 | + conditions.append(dataframe['volume'].gt(0)) | |
| 298 | + | |
| 299 | + if conditions: | |
| 300 | + dataframe.loc[ | |
| 301 | + reduce(lambda x, y: x & y, conditions), | |
| 302 | + 'buy'] = 1 | |
| 303 | + | |
| 304 | + return dataframe | |
| 305 | + | |
| 306 | + """ | |
| 307 | + Sell Signal | |
| 308 | + """ | |
| 309 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 310 | + | |
| 311 | + dataframe['sell'] = 0 | |
| 312 | + | |
| 313 | + return dataframe | |
| 314 | + | |
| 315 | + """ | |
| 316 | + Custom Stoploss | |
| 317 | + """ | |
| 318 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 319 | + | |
| 320 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 321 | + | |
| 322 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 323 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 324 | + sroc = dataframe['sroc'].iat[-1] | |
| 325 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 326 | + else: | |
| 327 | + sroc = self.custom_trade_info[trade.pair]['sroc'].loc[current_time]['sroc'] | |
| 328 | + | |
| 329 | + if current_profit < self.cstp_threshold.value: | |
| 330 | + if self.cstp_bail_how.value == 'roc' or self.cstp_bail_how.value == 'any': | |
| 331 | + # Dynamic bailout based on rate of change | |
| 332 | + if (sroc/100) <= self.cstp_bail_roc.value: | |
| 333 | + return 0.001 | |
| 334 | + if self.cstp_bail_how.value == 'time' or self.cstp_bail_how.value == 'any': | |
| 335 | + # Dynamic bailout based on time | |
| 336 | + if trade_dur > self.cstp_bail_time.value: | |
| 337 | + return 0.001 | |
| 338 | + | |
| 339 | + return 1 | |
| 340 | + | |
| 341 | + """ | |
| 342 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 343 | + """ | |
| 344 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 345 | + | |
| 346 | + minimal_roi = self.minimal_roi | |
| 347 | + _, table_roi = self.min_roi_reached_entry(trade_dur) | |
| 348 | + | |
| 349 | + # see if we have the data we need to do this, otherwise fall back to the standard table | |
| 350 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 351 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 352 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 353 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 354 | + candle_trend = dataframe['candle-up-trend'].iat[-1] | |
| 355 | + ssl_dir = dataframe['ssl-dir'].iat[-1] | |
| 356 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 357 | + else: | |
| 358 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 359 | + candle_trend = self.custom_trade_info[trade.pair]['candle-up-trend'].loc[current_time]['candle-up-trend'] | |
| 360 | + ssl_dir = self.custom_trade_info[trade.pair]['ssl-dir'].loc[current_time]['ssl-dir'] | |
| 361 | + | |
| 362 | + min_roi = table_roi | |
| 363 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 364 | + pullback_value = (max_profit - self.droi_pullback_amount.value) | |
| 365 | + in_trend = False | |
| 366 | + | |
| 367 | + if self.droi_trend_type.value == 'rmi' or self.droi_trend_type.value == 'any': | |
| 368 | + if rmi_trend == 1: | |
| 369 | + in_trend = True | |
| 370 | + if self.droi_trend_type.value == 'ssl' or self.droi_trend_type.value == 'any': | |
| 371 | + if ssl_dir == 'up': | |
| 372 | + in_trend = True | |
| 373 | + if self.droi_trend_type.value == 'candle' or self.droi_trend_type.value == 'any': | |
| 374 | + if candle_trend == 1: | |
| 375 | + in_trend = True | |
| 376 | + | |
| 377 | + # Force the ROI value high if in trend | |
| 378 | + if (in_trend == True): | |
| 379 | + min_roi = 100 | |
| 380 | + # If pullback is enabled, allow to sell if a pullback from peak has happened regardless of trend | |
| 381 | + if self.droi_pullback.value == True and (current_profit < pullback_value): | |
| 382 | + if self.droi_pullback_respect_table.value == True: | |
| 383 | + min_roi = table_roi | |
| 384 | + else: | |
| 385 | + min_roi = current_profit / 2 | |
| 386 | + | |
| 387 | + else: | |
| 388 | + min_roi = table_roi | |
| 389 | + | |
| 390 | + return trade_dur, min_roi | |
| 391 | + | |
| 392 | + # Change here to allow loading of the dynamic_roi settings | |
| 393 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 394 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 395 | + | |
| 396 | + if self.use_dynamic_roi: | |
| 397 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 398 | + else: | |
| 399 | + _, roi = self.min_roi_reached_entry(trade_dur) | |
| 400 | + if roi is None: | |
| 401 | + return False | |
| 402 | + else: | |
| 403 | + return current_profit > roi | |
| 404 | + | |
| 405 | + """ | |
| 406 | + Trade Timeout Overloads | |
| 407 | + """ | |
| 408 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 409 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 410 | + ob = self.dp.orderbook(pair, 1) | |
| 411 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 412 | + if current_price > order['price'] * 1.01: | |
| 413 | + return True | |
| 414 | + return False | |
| 415 | + | |
| 416 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 417 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 418 | + ob = self.dp.orderbook(pair, 1) | |
| 419 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 420 | + if current_price < order['price'] * 0.99: | |
| 421 | + return True | |
| 422 | + return False | |
| 423 | + | |
| 424 | +# Sub-strategy with parameters specific to BTC stake | |
| 425 | +class Solipsis4_BTC(Solipsis4): | |
| 426 | + | |
| 427 | + timeframe = '5m' | |
| 428 | + inf_timeframe = '1h' | |
| 429 | + | |
| 430 | + minimal_roi = { | |
| 431 | + "0": 0.01, | |
| 432 | + "1440": 0 | |
| 433 | + } | |
| 434 | + | |
| 435 | +# Sub-strategy with parameters specific to ETH stake | |
| 436 | +class Solipsis4_ETH(Solipsis4): | |
| 437 | + | |
| 438 | + timeframe = '5m' | |
| 439 | + inf_timeframe = '1h' | |
| 440 | + | |
| 441 | + minimal_roi = { | |
| 442 | + "0": 0.01, | |
| 443 | + "1440": 0 | |
| 444 | + } | |
| No newline at the end of the file |
modified strategies/custom_indicators.py +74 −221
| @@ -1,8 +1,5 @@ | ||
| 1 | 1 | """ |
| 2 | 2 | Solipsis Custom Indicators and Maths |
| 3 | - | |
| 4 | -Some indicators are direct copies from freqtrade/technical but I did not want to rely on that repository | |
| 5 | -to be stable and I needed to make some fixes/changes to fibonacci retracements and PMAX to suit my needs. | |
| 6 | 3 | """ |
| 7 | 4 | import numpy as np |
| 8 | 5 | import talib.abstract as ta |
| @@ -17,7 +14,6 @@ | ||
| 17 | 14 | def same_length(bigger, shorter): |
| 18 | 15 | return np.concatenate((np.full((bigger.shape[0] - shorter.shape[0]), np.nan), shorter)) |
| 19 | 16 | |
| 20 | - | |
| 21 | 17 | """ |
| 22 | 18 | Maths |
| 23 | 19 | """ |
| @@ -33,76 +29,6 @@ | ||
| 33 | 29 | """ |
| 34 | 30 | TA Indicators |
| 35 | 31 | """ |
| 36 | -def fib_ret(df, lookback=72, field='close') -> DataFrame: | |
| 37 | - """ | |
| 38 | - Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L735 | |
| 39 | - Modifed to have a specific lookback period to prevent lookahead bias. | |
| 40 | - """ | |
| 41 | - thresholds = [1.0, 0.786, 0.618, 0.5, 0.382, 0.236, 0.0] | |
| 42 | - | |
| 43 | - window_min = df[field].rolling(lookback).min() | |
| 44 | - window_max = df[field].rolling(lookback).max() | |
| 45 | - # I have no idea what this is for, maaybe graphing or jupyter? | |
| 46 | - fib_levels = [window_min + t * (window_max - window_min) for t in thresholds] | |
| 47 | - | |
| 48 | - data = (df[field] - window_min) / (window_max - window_min) | |
| 49 | - | |
| 50 | - # this return is broken and I don't know how to fix it. | |
| 51 | - #return data.apply(lambda x: max(t for t in thresholds if x >= t)) | |
| 52 | - return data | |
| 53 | - | |
| 54 | -def RMI(dataframe, *, length=20, mom=5): | |
| 55 | - """ | |
| 56 | - Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L912 | |
| 57 | - """ | |
| 58 | - df = dataframe.copy() | |
| 59 | - | |
| 60 | - df['maxup'] = (df['close'] - df['close'].shift(mom)).clip(lower=0) | |
| 61 | - df['maxdown'] = (df['close'].shift(mom) - df['close']).clip(lower=0) | |
| 62 | - | |
| 63 | - df.fillna(0, inplace=True) | |
| 64 | - | |
| 65 | - df["emaInc"] = ta.EMA(df, price='maxup', timeperiod=length) | |
| 66 | - df["emaDec"] = ta.EMA(df, price='maxdown', timeperiod=length) | |
| 67 | - | |
| 68 | - df['RMI'] = np.where(df['emaDec'] == 0, 0, 100 - 100 / (1 + df["emaInc"] / df["emaDec"])) | |
| 69 | - | |
| 70 | - return df["RMI"] | |
| 71 | - | |
| 72 | -def VIDYA(dataframe, length=9, select=True): | |
| 73 | - """ | |
| 74 | - Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L936 | |
| 75 | - """ | |
| 76 | - df = dataframe.copy() | |
| 77 | - | |
| 78 | - alpha = 2 / (length + 1) | |
| 79 | - df['momm'] = df['close'].diff() | |
| 80 | - df['m1'] = np.where(df['momm'] >= 0, df['momm'], 0.0) | |
| 81 | - df['m2'] = np.where(df['momm'] >= 0, 0.0, -df['momm']) | |
| 82 | - | |
| 83 | - df['sm1'] = df['m1'].rolling(length).sum() | |
| 84 | - df['sm2'] = df['m2'].rolling(length).sum() | |
| 85 | - | |
| 86 | - df['chandeMO'] = 100 * (df['sm1'] - df['sm2']) / (df['sm1'] + df['sm2']) | |
| 87 | - if select: | |
| 88 | - df['k'] = abs(df['chandeMO']) / 100 | |
| 89 | - else: | |
| 90 | - df['k'] = df['close'].rolling(length).std() | |
| 91 | - df.fillna(0.0, inplace=True) | |
| 92 | - | |
| 93 | - df['VIDYA'] = 0.0 | |
| 94 | - for i in range(length, len(df)): | |
| 95 | - | |
| 96 | - df['VIDYA'].iat[i] = alpha * df['k'].iat[i] * df['close'].iat[i] + \ | |
| 97 | - (1 - alpha * df['k'].iat[i]) * df['VIDYA'].iat[i-1] | |
| 98 | - | |
| 99 | - return df['VIDYA'] | |
| 100 | - | |
| 101 | -def vwma(df, window): | |
| 102 | - """ | |
| 103 | - Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/overlap_studies.py#L75 | |
| 104 | - """ | |
| 105 | - return (df['close'] * df['volume']).rolling(window).sum() / df.volume.rolling(window).sum() | |
| 106 | 32 | |
| 107 | 33 | def zema(dataframe, period, field='close'): |
| 108 | 34 | """ |
| @@ -118,127 +44,23 @@ | ||
| 118 | 44 | |
| 119 | 45 | return df['zema'] |
| 120 | 46 | |
| 121 | -def PMAX(dataframe, period=10, multiplier=3, length=12, MAtype=1, src=1): | |
| 122 | - """ | |
| 123 | - Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L1059 | |
| 124 | - Modified to return different series instead of a modified dataframe as well as not use unique | |
| 125 | - field names based on the input parameters. | |
| 126 | - | |
| 127 | - returns: atr, ma, pmax_value, pmax_location | |
| 128 | - | |
| 129 | - src==1 --> close | |
| 130 | - src==2 --> hl2 | |
| 131 | - src==3 --> ohlc4 | |
| 132 | - | |
| 133 | - MAtype==1 --> EMA | |
| 134 | - MAtype==2 --> DEMA | |
| 135 | - MAtype==3 --> T3 | |
| 136 | - MAtype==4 --> SMA | |
| 137 | - MAtype==5 --> VIDYA | |
| 138 | - MAtype==6 --> TEMA | |
| 139 | - MAtype==7 --> WMA | |
| 140 | - MAtype==8 --> VWMA | |
| 141 | - MAtype==9 --> zema | |
| 142 | - """ | |
| 143 | - df = dataframe.copy() | |
| 144 | - mavalue = 'ma' | |
| 145 | - atr = 'atr' | |
| 146 | - pm = 'pm' | |
| 147 | - pmx = 'pmx' | |
| 148 | - | |
| 149 | - df[atr] = ta.ATR(df, timeperiod=period) | |
| 150 | - | |
| 151 | - if src == 1: | |
| 152 | - masrc = df["close"] | |
| 153 | - elif src == 2: | |
| 154 | - masrc = (df["high"] + df["low"]) / 2 | |
| 155 | - elif src == 3: | |
| 156 | - masrc = (df["high"] + df["low"] + df["close"] + df["open"]) / 4 | |
| 157 | - | |
| 158 | - if MAtype == 1: | |
| 159 | - df[mavalue] = ta.EMA(masrc, timeperiod=length) | |
| 160 | - elif MAtype == 2: | |
| 161 | - df[mavalue] = ta.DEMA(masrc, timeperiod=length) | |
| 162 | - elif MAtype == 3: | |
| 163 | - df[mavalue] = ta.T3(masrc, timeperiod=length) | |
| 164 | - elif MAtype == 4: | |
| 165 | - df[mavalue] = ta.SMA(masrc, timeperiod=length) | |
| 166 | - elif MAtype == 5: | |
| 167 | - df[mavalue] = VIDYA(df, length=length) | |
| 168 | - elif MAtype == 6: | |
| 169 | - df[mavalue] = ta.TEMA(masrc, timeperiod=length) | |
| 170 | - elif MAtype == 7: | |
| 171 | - df[mavalue] = ta.WMA(df, timeperiod=length) | |
| 172 | - elif MAtype == 8: | |
| 173 | - df[mavalue] = vwma(df, length) | |
| 174 | - elif MAtype == 9: | |
| 175 | - df[mavalue] = zema(df, period=length) | |
| 176 | - | |
| 177 | - # Compute basic upper and lower bands | |
| 178 | - df['basic_ub'] = df[mavalue] + (multiplier * df[atr]) | |
| 179 | - df['basic_lb'] = df[mavalue] - (multiplier * df[atr]) | |
| 180 | - # Compute final upper and lower bands | |
| 181 | - df['final_ub'] = 0.00 | |
| 182 | - df['final_lb'] = 0.00 | |
| 183 | - for i in range(period, len(df)): | |
| 184 | - df['final_ub'].iat[i] = df['basic_ub'].iat[i] if ( | |
| 185 | - df['basic_ub'].iat[i] < df['final_ub'].iat[i - 1] | |
| 186 | - or df[mavalue].iat[i - 1] > df['final_ub'].iat[i - 1]) else df['final_ub'].iat[i - 1] | |
| 187 | - df['final_lb'].iat[i] = df['basic_lb'].iat[i] if ( | |
| 188 | - df['basic_lb'].iat[i] > df['final_lb'].iat[i - 1] | |
| 189 | - or df[mavalue].iat[i - 1] < df['final_lb'].iat[i - 1]) else df['final_lb'].iat[i - 1] | |
| 190 | - | |
| 191 | - # Set the Pmax value | |
| 192 | - df[pm] = 0.00 | |
| 193 | - for i in range(period, len(df)): | |
| 194 | - df[pm].iat[i] = ( | |
| 195 | - df['final_ub'].iat[i] if (df[pm].iat[i - 1] == df['final_ub'].iat[i - 1] | |
| 196 | - and df[mavalue].iat[i] <= df['final_ub'].iat[i]) | |
| 197 | - else df['final_lb'].iat[i] if ( | |
| 198 | - df[pm].iat[i - 1] == df['final_ub'].iat[i - 1] | |
| 199 | - and df[mavalue].iat[i] > df['final_ub'].iat[i]) else df['final_lb'].iat[i] | |
| 200 | - if (df[pm].iat[i - 1] == df['final_lb'].iat[i - 1] | |
| 201 | - and df[mavalue].iat[i] >= df['final_lb'].iat[i]) else df['final_ub'].iat[i] | |
| 202 | - if (df[pm].iat[i - 1] == df['final_lb'].iat[i - 1] | |
| 203 | - and df[mavalue].iat[i] < df['final_lb'].iat[i]) else 0.00) | |
| 204 | - | |
| 205 | - # Mark the trend direction up/down | |
| 206 | - df[pmx] = np.where((df[pm] > 0.00), np.where((df[mavalue] < df[pm]), 'down', 'up'), np.NaN) | |
| 207 | - # Remove basic and final bands from the columns | |
| 208 | - df.drop(['basic_ub', 'basic_lb', 'final_ub', 'final_lb'], inplace=True, axis=1) | |
| 209 | - | |
| 210 | - df.fillna(0, inplace=True) | |
| 211 | - | |
| 212 | - return df[atr], df[mavalue], df[pm], df[pmx] | |
| 213 | - | |
| 214 | -def macross(dataframe: DataFrame, fast: int = 20, slow: int = 50) -> Series: | |
| 47 | +def RMI(dataframe, *, length=20, mom=5): | |
| 215 | 48 | """ |
| 216 | - Moving Average Cross | |
| 217 | - Port of: https://www.tradingview.com/script/PcWAuplI-Moving-Average-Cross/ | |
| 49 | + Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L912 | |
| 218 | 50 | """ |
| 219 | 51 | df = dataframe.copy() |
| 220 | 52 | |
| 221 | - # Fast MAs | |
| 222 | - upper_fast = ta.EMA(df['high'], timeperiod=fast) | |
| 223 | - lower_fast = ta.EMA(df['low'], timeperiod=fast) | |
| 224 | - | |
| 225 | - # Slow MAs | |
| 226 | - upper_slow = ta.EMA(df['high'], timeperiod=slow) | |
| 227 | - lower_slow = ta.EMA(df['low'], timeperiod=slow) | |
| 228 | - | |
| 229 | - # Crosses | |
| 230 | - crosses_lf_us = qtpylib.crossed_above(lower_fast, upper_slow) | qtpylib.crossed_below(lower_fast, upper_slow) | |
| 231 | - crosses_uf_ls = qtpylib.crossed_above(upper_fast, lower_slow) | qtpylib.crossed_below(upper_fast, lower_slow) | |
| 53 | + df['maxup'] = (df['close'] - df['close'].shift(mom)).clip(lower=0) | |
| 54 | + df['maxdown'] = (df['close'].shift(mom) - df['close']).clip(lower=0) | |
| 232 | 55 | |
| 233 | - dir_1 = np.where(crosses_lf_us, 1, np.nan) | |
| 234 | - dir_2 = np.where(crosses_uf_ls, -1, np.nan) | |
| 56 | + df.fillna(0, inplace=True) | |
| 235 | 57 | |
| 236 | - dir = np.where(dir_1 == 1, dir_1, np.nan) | |
| 237 | - dir = np.where(dir_2 == -1, dir_2, dir_1) | |
| 58 | + df["emaInc"] = ta.EMA(df, price='maxup', timeperiod=length) | |
| 59 | + df["emaDec"] = ta.EMA(df, price='maxdown', timeperiod=length) | |
| 238 | 60 | |
| 239 | - res = Series(dir).fillna(method='ffill').to_numpy() | |
| 61 | + df['RMI'] = np.where(df['emaDec'] == 0, 0, 100 - 100 / (1 + df["emaInc"] / df["emaDec"])) | |
| 240 | 62 | |
| 241 | - return res | |
| 63 | + return df["RMI"] | |
| 242 | 64 | |
| 243 | 65 | def mastreak(dataframe: DataFrame, period: int = 4, field='close') -> Series: |
| 244 | 66 | """ |
| @@ -287,13 +109,6 @@ | ||
| 287 | 109 | """ |
| 288 | 110 | Source: https://www.tradingview.com/script/xzIoaIJC-SSL-channel/ |
| 289 | 111 | Source: https://github.com/freqtrade/technical/blob/master/technical/indicators/indicators.py#L1025 |
| 290 | - Author: xmatthias | |
| 291 | - Pinescript Author: ErwinBeckers | |
| 292 | - SSL Channels. | |
| 293 | - Average over highs and lows form a channel - lines "flip" when close crosses either of the 2 lines. | |
| 294 | - Trading ideas: | |
| 295 | - * Channel cross | |
| 296 | - * as confirmation based on up > down for long | |
| 297 | 112 | Usage: |
| 298 | 113 | dataframe['sslDown'], dataframe['sslUp'] = SSLChannels(dataframe, 10) |
| 299 | 114 | """ |
| @@ -315,32 +130,70 @@ | ||
| 315 | 130 | |
| 316 | 131 | return df['sslDown'], df['sslUp'] |
| 317 | 132 | |
| 318 | -# From CombinedBinHAAndCluc | |
| 319 | -def bollinger_bands(stock_price, window_size, num_of_std): | |
| 320 | - rolling_mean = stock_price.rolling(window=window_size).mean() | |
| 321 | - rolling_std = stock_price.rolling(window=window_size).std() | |
| 322 | - lower_band = rolling_mean - (rolling_std * num_of_std) | |
| 323 | - return np.nan_to_num(rolling_mean), np.nan_to_num(lower_band) | |
| 133 | +def SSLChannels_ATR(dataframe, length=7): | |
| 134 | + """ | |
| 135 | + SSL Channels with ATR: https://www.tradingview.com/script/SKHqWzql-SSL-ATR-channel/ | |
| 136 | + Credit to @JimmyNixx for python | |
| 137 | + """ | |
| 138 | + df = dataframe.copy() | |
| 139 | + | |
| 140 | + df['ATR'] = ta.ATR(df, timeperiod=14) | |
| 141 | + df['smaHigh'] = df['high'].rolling(length).mean() + df['ATR'] | |
| 142 | + df['smaLow'] = df['low'].rolling(length).mean() - df['ATR'] | |
| 143 | + df['hlv'] = np.where(df['close'] > df['smaHigh'], 1, np.where(df['close'] < df['smaLow'], -1, np.NAN)) | |
| 144 | + df['hlv'] = df['hlv'].ffill() | |
| 145 | + df['sslDown'] = np.where(df['hlv'] < 0, df['smaHigh'], df['smaLow']) | |
| 146 | + df['sslUp'] = np.where(df['hlv'] < 0, df['smaLow'], df['smaHigh']) | |
| 147 | + | |
| 148 | + return df['sslDown'], df['sslUp'] | |
| 149 | + | |
| 150 | +def WaveTrend(dataframe, chlen=10, avg=21, smalen=4): | |
| 151 | + """ | |
| 152 | + WaveTrend Ocillator by LazyBear | |
| 153 | + https://www.tradingview.com/script/2KE8wTuF-Indicator-WaveTrend-Oscillator-WT/ | |
| 154 | + """ | |
| 155 | + df = dataframe.copy() | |
| 156 | + | |
| 157 | + df['hlc3'] = (df['high'] + df['low'] + df['close']) / 3 | |
| 158 | + df['esa'] = ta.EMA(df['hlc3'], timeperiod=chlen) | |
| 159 | + df['d'] = ta.EMA((df['hlc3'] - df['esa']).abs(), timeperiod=chlen) | |
| 160 | + df['ci'] = (df['hlc3'] - df['esa']) / (0.015 * df['d']) | |
| 161 | + df['tci'] = ta.EMA(df['ci'], timeperiod=avg) | |
| 324 | 162 | |
| 163 | + df['wt1'] = df['tci'] | |
| 164 | + df['wt2'] = ta.SMA(df['wt1'], timeperiod=smalen) | |
| 165 | + df['wt1-wt2'] = df['wt1'] - df['wt2'] | |
| 325 | 166 | |
| 326 | -""" | |
| 327 | -Market Cipher, from @Drafy in Freqtrade discord | |
| 328 | -""" | |
| 329 | -def market_cipher(self, dataframe) -> DataFrame: | |
| 330 | - #dataframe['volume_rolling'] = dataframe['volume'].shift(14).rolling(14).mean() | |
| 331 | - # | |
| 332 | - dataframe['ap'] = (dataframe['high'] + dataframe['low'] + dataframe['close']) / 3 | |
| 333 | - dataframe['esa'] = ta.EMA(dataframe['ap'], self.n1) | |
| 334 | - dataframe['d'] = ta.EMA((dataframe['ap']-dataframe['esa']).abs(), self.n1) | |
| 335 | - dataframe['ci'] = ( dataframe['ap']-dataframe['esa'] ) / (0.015 * dataframe['d']) | |
| 336 | - dataframe['tci'] = ta.EMA(dataframe['ci'], self.n2) | |
| 337 | - | |
| 338 | - dataframe['wt1'] = dataframe['tci'] | |
| 339 | - dataframe['wt2'] = ta.SMA(dataframe['wt1'],4) | |
| 340 | - dataframe['wt1-wt2'] = dataframe['wt1'] - dataframe['wt2'] | |
| 341 | - | |
| 342 | - dataframe['crossed_above'] = qtpylib.crossed_above(dataframe['wt2'], dataframe['wt1']) | |
| 343 | - dataframe['crossed_below'] = qtpylib.crossed_below(dataframe['wt2'], dataframe['wt1']) | |
| 344 | - #dataframe['slope_gd'] = ta.LINEARREG_ANGLE(dataframe['crossed_above'] * dataframe['wt2'], 10) | |
| 345 | - | |
| 346 | - return dataframe | |
| 167 | + return df['wt1'], df['wt2'] | |
| 168 | + | |
| 169 | +def T3(dataframe, length=5): | |
| 170 | + """ | |
| 171 | + T3 Average by HPotter on Tradingview | |
| 172 | + https://www.tradingview.com/script/qzoC9H1I-T3-Average/ | |
| 173 | + """ | |
| 174 | + df = dataframe.copy() | |
| 175 | + | |
| 176 | + df['xe1'] = ta.EMA(df['close'], timeperiod=length) | |
| 177 | + df['xe2'] = ta.EMA(df['xe1'], timeperiod=length) | |
| 178 | + df['xe3'] = ta.EMA(df['xe2'], timeperiod=length) | |
| 179 | + df['xe4'] = ta.EMA(df['xe3'], timeperiod=length) | |
| 180 | + df['xe5'] = ta.EMA(df['xe4'], timeperiod=length) | |
| 181 | + df['xe6'] = ta.EMA(df['xe5'], timeperiod=length) | |
| 182 | + b = 0.7 | |
| 183 | + c1 = -b*b*b | |
| 184 | + c2 = 3*b*b+3*b*b*b | |
| 185 | + c3 = -6*b*b-3*b-3*b*b*b | |
| 186 | + c4 = 1+3*b+b*b*b+3*b*b | |
| 187 | + df['T3Average'] = c1 * df['xe6'] + c2 * df['xe5'] + c3 * df['xe4'] + c4 * df['xe3'] | |
| 188 | + | |
| 189 | + return df['T3Average'] | |
| 190 | + | |
| 191 | + | |
| 192 | +def SROC(dataframe, roclen=21, emalen=13, smooth=21): | |
| 193 | + df = dataframe.copy() | |
| 194 | + | |
| 195 | + roc = ta.ROC(df, timeperiod=roclen) | |
| 196 | + ema = ta.EMA(df, timeperiod=emalen) | |
| 197 | + sroc = ta.ROC(ema, timeperiod=smooth) | |
| 198 | + | |
| 199 | + return sroc | |
| No newline at the end of the file |
added strategies/old/Solipsis_v3.py +558 −0
| @@ -0,0 +1,558 @@ | ||
| 1 | +import numpy as np | |
| 2 | +import talib.abstract as ta | |
| 3 | +import freqtrade.vendor.qtpylib.indicators as qtpylib | |
| 4 | +import arrow | |
| 5 | + | |
| 6 | +from freqtrade.strategy.interface import IStrategy | |
| 7 | +from freqtrade.strategy import merge_informative_pair, stoploss_from_open | |
| 8 | +from typing import Dict, List, Optional, Tuple | |
| 9 | +from pandas import DataFrame, Series | |
| 10 | +from functools import reduce | |
| 11 | +from datetime import datetime, timedelta | |
| 12 | +from freqtrade.persistence import Trade | |
| 13 | +from cachetools import TTLCache | |
| 14 | + | |
| 15 | +# Get rid of pandas warnings during backtesting | |
| 16 | +import pandas as pd | |
| 17 | +pd.options.mode.chained_assignment = None # default='warn' | |
| 18 | + | |
| 19 | +# Strategy specific imports, files must reside in same folder as strategy | |
| 20 | +import sys | |
| 21 | +from pathlib import Path | |
| 22 | +sys.path.append(str(Path(__file__).parent)) | |
| 23 | + | |
| 24 | +import custom_indicators as cta | |
| 25 | + | |
| 26 | +""" | |
| 27 | +Solipsis - By @werkkrew | |
| 28 | + | |
| 29 | +Credits - | |
| 30 | +@JimmyNixx for many of the ideas used throughout as well as helping me stay motivated throughout development! | |
| 31 | +@JoeSchr for documenting and doing the legwork of getting indicators to be available in the custom_stoploss | |
| 32 | + | |
| 33 | +We ask for nothing in return except that if you make changes which bring you greater success than what has been provided, you share those ideas back to us | |
| 34 | +and the rest of the community. Also, please don't nag us with a million questions and especially don't blame us if you lose a ton of money using this. | |
| 35 | + | |
| 36 | +We take no responsibility for any success or failure you have using this strategy. | |
| 37 | +""" | |
| 38 | + | |
| 39 | +class Solipsis3(IStrategy): | |
| 40 | + | |
| 41 | + # Recommended for USD/USDT/etc. | |
| 42 | + timeframe = '5m' | |
| 43 | + inf_timeframe = '1h' | |
| 44 | + | |
| 45 | + buy_params = { | |
| 46 | + 'base-mp': 30, | |
| 47 | + 'base-rmi-fast': 50, | |
| 48 | + 'base-rmi-slow': 30, | |
| 49 | + 'inf-guard': 'upper', | |
| 50 | + 'inf-pct-adr-bot': 0.10, | |
| 51 | + 'inf-pct-adr-top': 0.85, | |
| 52 | + 'xbtc-base-rmi': 50, | |
| 53 | + 'xbtc-inf-rmi': 20, | |
| 54 | + 'xtra-base-fiat-rmi': 45, | |
| 55 | + 'xtra-base-stake-rmi': 69, | |
| 56 | + 'xtra-inf-stake-rmi': 27 | |
| 57 | + } | |
| 58 | + | |
| 59 | + sell_params = {} | |
| 60 | + | |
| 61 | + # Custom buy/sell parameters per pair | |
| 62 | + custom_pair_params = [] | |
| 63 | + | |
| 64 | + # Recommended on 5m timeframe | |
| 65 | + minimal_roi = { | |
| 66 | + "0": 0.01, | |
| 67 | + "360": 0.005, | |
| 68 | + "720": 0 | |
| 69 | + } | |
| 70 | + | |
| 71 | + dynamic_roi = { | |
| 72 | + 'enabled': True, # enable dynamic roi which uses trennds and indicators to dynamically manipulate the roi table | |
| 73 | + 'profit-factor': 400, # factor for forumla of how far below peak profit to trigger sell | |
| 74 | + 'rmi-start': 30, # starting value for rmi-slow to be considered a positive trend | |
| 75 | + 'rmi-end': 70, # ending value | |
| 76 | + 'grow-delay': 0, # delay on growth | |
| 77 | + 'grow-time': 720, # finish time of growth | |
| 78 | + 'fallback': 'table', # if no trend, do what? (table, roc, atr, roc-table, atr-table) | |
| 79 | + 'min-roc-atr': 0.0075 # minimum roi value to return in roc or atr mode | |
| 80 | + } | |
| 81 | + | |
| 82 | + use_custom_stoploss = True | |
| 83 | + custom_stop = { | |
| 84 | + # Linear Decay Parameters | |
| 85 | + 'decay-time': 1080, # minutes to reach end, I find it works well to match this to the final ROI value | |
| 86 | + 'decay-delay': 0, # minutes to wait before decay starts | |
| 87 | + 'decay-start': -0.30, # starting value: should be the same or smaller than initial stoploss | |
| 88 | + 'decay-end': -0.03, # ending value | |
| 89 | + # Profit and TA | |
| 90 | + 'cur-min-diff': 0.03, # diff between current and minimum profit to move stoploss up to min profit point | |
| 91 | + 'cur-threshold': -0.02, # how far negative should current profit be before we consider moving it up based on cur/min or roc | |
| 92 | + 'roc-bail': -0.03, # value for roc to use for dynamic bailout | |
| 93 | + 'rmi-trend': 50, # rmi-slow value to pause stoploss decay | |
| 94 | + 'bail-how': 'immediate', # set the stoploss to the atr offset below current price, or immediate | |
| 95 | + # Positive Trailing | |
| 96 | + 'pos-trail': False, # enable trailing once positive | |
| 97 | + 'pos-threshold': 0.005, # trail after how far positive | |
| 98 | + 'pos-trail-dist': 0.015 # how far behind to place the trail | |
| 99 | + } | |
| 100 | + | |
| 101 | + stoploss = custom_stop['decay-start'] | |
| 102 | + | |
| 103 | + # Recommended | |
| 104 | + use_sell_signal = False | |
| 105 | + sell_profit_only = False | |
| 106 | + ignore_roi_if_buy_signal = False | |
| 107 | + | |
| 108 | + # Required | |
| 109 | + startup_candle_count: int = 72 | |
| 110 | + process_only_new_candles = False | |
| 111 | + | |
| 112 | + # Strategy Specific Variable Storage | |
| 113 | + custom_trade_info = {} | |
| 114 | + custom_fiat = "USD" # Only relevant if stake is BTC or ETH | |
| 115 | + custom_current_price_cache: TTLCache = TTLCache(maxsize=100, ttl=300) # 5 minutes | |
| 116 | + | |
| 117 | + """ | |
| 118 | + Informative Pair Definitions | |
| 119 | + """ | |
| 120 | + def informative_pairs(self): | |
| 121 | + # add all whitelisted pairs on informative timeframe | |
| 122 | + pairs = self.dp.current_whitelist() | |
| 123 | + informative_pairs = [(pair, self.inf_timeframe) for pair in pairs] | |
| 124 | + | |
| 125 | + # add extra informative pairs if the stake is BTC or ETH | |
| 126 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 127 | + for pair in pairs: | |
| 128 | + coin, stake = pair.split('/') | |
| 129 | + coin_fiat = f"{coin}/{self.custom_fiat}" | |
| 130 | + informative_pairs += [(coin_fiat, self.timeframe)] | |
| 131 | + | |
| 132 | + stake_fiat = f"{self.config['stake_currency']}/{self.custom_fiat}" | |
| 133 | + informative_pairs += [(stake_fiat, self.timeframe)] | |
| 134 | + informative_pairs += [(stake_fiat, self.inf_timeframe)] | |
| 135 | + # if BTC/STAKE is not in whitelist, add it as an informative pair on both timeframes | |
| 136 | + else: | |
| 137 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 138 | + if not btc_stake in pairs: | |
| 139 | + informative_pairs += [(btc_stake, self.timeframe)] | |
| 140 | + informative_pairs += [(btc_stake, self.inf_timeframe)] | |
| 141 | + | |
| 142 | + return informative_pairs | |
| 143 | + | |
| 144 | + """ | |
| 145 | + Indicator Definitions | |
| 146 | + """ | |
| 147 | + def populate_indicators(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 148 | + # Populate/update the trade data if there is any, set trades to false if not live/dry | |
| 149 | + self.custom_trade_info[metadata['pair']] = self.populate_trades(metadata['pair']) | |
| 150 | + | |
| 151 | + # Base timeframe indicators | |
| 152 | + dataframe['rmi-slow'] = cta.RMI(dataframe, length=21, mom=5) | |
| 153 | + dataframe['rmi-fast'] = cta.RMI(dataframe, length=8, mom=4) | |
| 154 | + | |
| 155 | + # Indicators for ROI and Custom Stoploss | |
| 156 | + dataframe['atr'] = ta.ATR(dataframe, timeperiod=24) | |
| 157 | + dataframe['roc'] = ta.ROC(dataframe, timeperiod=9) | |
| 158 | + | |
| 159 | + # Momentum Pinball: https://www.tradingview.com/script/fBpVB1ez-Momentum-Pinball-Indicator/ | |
| 160 | + dataframe['roc-mp'] = ta.ROC(dataframe, timeperiod=6) | |
| 161 | + dataframe['mp'] = ta.RSI(dataframe['roc-mp'], timeperiod=6) | |
| 162 | + | |
| 163 | + # Trends, Peaks and Crosses | |
| 164 | + dataframe['rmi-up'] = np.where(dataframe['rmi-slow'] >= dataframe['rmi-slow'].shift(),1,0) | |
| 165 | + dataframe['rmi-dn'] = np.where(dataframe['rmi-slow'] <= dataframe['rmi-slow'].shift(),1,0) | |
| 166 | + dataframe['rmi-up-trend'] = np.where(dataframe['rmi-up'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 167 | + dataframe['rmi-dn-trend'] = np.where(dataframe['rmi-dn'].rolling(3, min_periods=1).sum() >= 2,1,0) | |
| 168 | + | |
| 169 | + # Base pair informative timeframe indicators | |
| 170 | + informative = self.dp.get_pair_dataframe(pair=metadata['pair'], timeframe=self.inf_timeframe) | |
| 171 | + | |
| 172 | + # Get the "average day range" between the 1d high and 3d low to set up guards | |
| 173 | + informative['1d_high'] = informative['close'].rolling(24).max() | |
| 174 | + informative['3d_low'] = informative['close'].rolling(72).min() | |
| 175 | + informative['adr'] = informative['1d_high'] - informative['3d_low'] | |
| 176 | + | |
| 177 | + dataframe = merge_informative_pair(dataframe, informative, self.timeframe, self.inf_timeframe, ffill=True) | |
| 178 | + | |
| 179 | + # Other stake specific informative indicators | |
| 180 | + # e.g if stake is BTC and current coin is XLM (pair: XLM/BTC) | |
| 181 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 182 | + coin, stake = metadata['pair'].split('/') | |
| 183 | + fiat = self.custom_fiat | |
| 184 | + coin_fiat = f"{coin}/{fiat}" | |
| 185 | + stake_fiat = f"{stake}/{fiat}" | |
| 186 | + | |
| 187 | + # Informative COIN/FIAT e.g. XLM/USD - Base Timeframe | |
| 188 | + coin_fiat_tf = self.dp.get_pair_dataframe(pair=coin_fiat, timeframe=self.timeframe) | |
| 189 | + dataframe[f"{fiat}_rmi"] = cta.RMI(coin_fiat_tf, length=21, mom=5) | |
| 190 | + | |
| 191 | + # Informative STAKE/FIAT e.g. BTC/USD - Base Timeframe | |
| 192 | + stake_fiat_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.timeframe) | |
| 193 | + dataframe[f"{stake}_rmi"] = cta.RMI(stake_fiat_tf, length=21, mom=5) | |
| 194 | + | |
| 195 | + # Informative STAKE/FIAT e.g. BTC/USD - Informative Timeframe | |
| 196 | + stake_fiat_inf_tf = self.dp.get_pair_dataframe(pair=stake_fiat, timeframe=self.inf_timeframe) | |
| 197 | + stake_fiat_inf_tf[f"{stake}_rmi"] = cta.RMI(stake_fiat_inf_tf, length=48, mom=5) | |
| 198 | + dataframe = merge_informative_pair(dataframe, stake_fiat_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 199 | + | |
| 200 | + # Informatives for BTC/STAKE if not in whitelist | |
| 201 | + else: | |
| 202 | + pairs = self.dp.current_whitelist() | |
| 203 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 204 | + if not btc_stake in pairs: | |
| 205 | + # BTC/STAKE - Base Timeframe | |
| 206 | + btc_stake_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.timeframe) | |
| 207 | + dataframe['BTC_rmi'] = cta.RMI(btc_stake_tf, length=14, mom=3) | |
| 208 | + | |
| 209 | + # BTC/STAKE - Informative Timeframe | |
| 210 | + btc_stake_inf_tf = self.dp.get_pair_dataframe(pair=btc_stake, timeframe=self.inf_timeframe) | |
| 211 | + btc_stake_inf_tf['BTC_rmi'] = cta.RMI(btc_stake_inf_tf, length=48, mom=5) | |
| 212 | + dataframe = merge_informative_pair(dataframe, btc_stake_inf_tf, self.timeframe, self.inf_timeframe, ffill=True) | |
| 213 | + | |
| 214 | + # Slam some indicators into the trade_info dict so we can dynamic roi and custom stoploss in backtest | |
| 215 | + if self.dp.runmode.value in ('backtest', 'hyperopt'): | |
| 216 | + self.custom_trade_info[metadata['pair']]['roc'] = dataframe[['date', 'roc']].copy().set_index('date') | |
| 217 | + self.custom_trade_info[metadata['pair']]['atr'] = dataframe[['date', 'atr']].copy().set_index('date') | |
| 218 | + self.custom_trade_info[metadata['pair']]['rmi-slow'] = dataframe[['date', 'rmi-slow']].copy().set_index('date') | |
| 219 | + self.custom_trade_info[metadata['pair']]['rmi-up-trend'] = dataframe[['date', 'rmi-up-trend']].copy().set_index('date') | |
| 220 | + | |
| 221 | + return dataframe | |
| 222 | + | |
| 223 | + """ | |
| 224 | + Buy Signal | |
| 225 | + """ | |
| 226 | + def populate_buy_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 227 | + params = self.get_pair_params(metadata['pair'], 'buy') | |
| 228 | + conditions = [] | |
| 229 | + | |
| 230 | + # Primary guards on informative timeframe to make sure we don't trade when market is peaked or bottomed out | |
| 231 | + if params['inf-guard'] == 'upper' or params['inf-guard'] == 'both': | |
| 232 | + conditions.append( | |
| 233 | + (dataframe['close'] <= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 234 | + (params['inf-pct-adr-top'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 235 | + ) | |
| 236 | + | |
| 237 | + if params['inf-guard'] == 'lower' or params['inf-guard'] == 'both': | |
| 238 | + conditions.append( | |
| 239 | + (dataframe['close'] >= dataframe[f"3d_low_{self.inf_timeframe}"] + | |
| 240 | + (params['inf-pct-adr-bot'] * dataframe[f"adr_{self.inf_timeframe}"])) | |
| 241 | + ) | |
| 242 | + | |
| 243 | + # Base Timeframe | |
| 244 | + conditions.append( | |
| 245 | + (dataframe['rmi-dn-trend'] == 1) & | |
| 246 | + (dataframe['rmi-slow'] >= params['base-rmi-slow']) & | |
| 247 | + (dataframe['rmi-fast'] <= params['base-rmi-fast']) & | |
| 248 | + (dataframe['mp'] <= params['base-mp']) | |
| 249 | + ) | |
| 250 | + | |
| 251 | + # Extra conditions for */BTC and */ETH stakes on additional informative pairs | |
| 252 | + if self.config['stake_currency'] in ('BTC', 'ETH'): | |
| 253 | + conditions.append( | |
| 254 | + (dataframe[f"{self.config['stake_currency']}_rmi"] < params['xtra-base-stake-rmi']) | | |
| 255 | + (dataframe[f"{self.custom_fiat}_rmi"] > params['xtra-base-fiat-rmi']) | |
| 256 | + ) | |
| 257 | + conditions.append(dataframe[f"{self.config['stake_currency']}_rmi_{self.inf_timeframe}"] < params['xtra-inf-stake-rmi']) | |
| 258 | + # Extra conditions for BTC/STAKE if not in whitelist | |
| 259 | + else: | |
| 260 | + pairs = self.dp.current_whitelist() | |
| 261 | + btc_stake = f"BTC/{self.config['stake_currency']}" | |
| 262 | + if not btc_stake in pairs: | |
| 263 | + conditions.append( | |
| 264 | + (dataframe['BTC_rmi'] < params['xbtc-base-rmi']) & | |
| 265 | + (dataframe[f"BTC_rmi_{self.inf_timeframe}"] > params['xbtc-inf-rmi']) | |
| 266 | + ) | |
| 267 | + | |
| 268 | + conditions.append(dataframe['volume'].gt(0)) | |
| 269 | + | |
| 270 | + if conditions: | |
| 271 | + dataframe.loc[ | |
| 272 | + reduce(lambda x, y: x & y, conditions), | |
| 273 | + 'buy'] = 1 | |
| 274 | + | |
| 275 | + return dataframe | |
| 276 | + | |
| 277 | + """ | |
| 278 | + Sell Signal | |
| 279 | + """ | |
| 280 | + def populate_sell_trend(self, dataframe: DataFrame, metadata: dict) -> DataFrame: | |
| 281 | + # params = self.get_pair_params(metadata['pair'], 'sell') | |
| 282 | + | |
| 283 | + dataframe['sell'] = 0 | |
| 284 | + | |
| 285 | + return dataframe | |
| 286 | + | |
| 287 | + """ | |
| 288 | + Custom Stoploss | |
| 289 | + """ | |
| 290 | + def custom_stoploss(self, pair: str, trade: 'Trade', current_time: datetime, current_rate: float, current_profit: float, **kwargs) -> float: | |
| 291 | + params = self.custom_stop | |
| 292 | + | |
| 293 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 294 | + min_profit = trade.calc_profit_ratio(trade.min_rate) | |
| 295 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 296 | + profit_diff = current_profit - min_profit | |
| 297 | + current_stoploss = trade.stop_loss | |
| 298 | + | |
| 299 | + decay_stoploss = cta.linear_growth(params['decay-start'], params['decay-end'], params['decay-delay'], params['decay-time'], trade_dur) | |
| 300 | + | |
| 301 | + # enable stoploss in positive profits after threshold to trail as specifed distance | |
| 302 | + if params['pos-trail'] == True: | |
| 303 | + if current_profit > params['pos-threshold']: | |
| 304 | + return current_profit - params['pos-trail-dist'] | |
| 305 | + | |
| 306 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 307 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=pair, timeframe=self.timeframe) | |
| 308 | + roc = dataframe['roc'].iat[-1] | |
| 309 | + atr = dataframe['atr'].iat[-1] | |
| 310 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 311 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 312 | + else: | |
| 313 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 314 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 315 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 316 | + | |
| 317 | + if current_profit < params['cur-threshold']: | |
| 318 | + # Dynamic bailout based on rate of change | |
| 319 | + if (roc/100) <= params['roc-bail']: | |
| 320 | + if params['bail-how'] == 'atr': | |
| 321 | + return ((current_rate - atr)/current_rate) - 1 | |
| 322 | + elif params['bail-how'] == 'immediate': | |
| 323 | + return 0.001 | |
| 324 | + else: | |
| 325 | + return min(max(stoploss_from_open(decay_stoploss, current_profit), 0.001), current_stoploss) | |
| 326 | + | |
| 327 | + # if we might be on a rebound, move the stoploss to the low point or keep it where it was | |
| 328 | + if (current_profit > min_profit) or roc > 0 or rmi_slow >= params['rmi-trend']: | |
| 329 | + if profit_diff > params['cur-min-diff'] and current_profit < 0: | |
| 330 | + return stoploss_from_open(min_profit, current_profit) | |
| 331 | + return 1 | |
| 332 | + | |
| 333 | + if current_profit < 0: | |
| 334 | + return min(max(stoploss_from_open(decay_stoploss, current_profit), 0.001), current_stoploss) | |
| 335 | + | |
| 336 | + return 1 | |
| 337 | + | |
| 338 | + """ | |
| 339 | + Freqtrade ROI Overload for dynamic ROI functionality | |
| 340 | + """ | |
| 341 | + def min_roi_reached_dynamic(self, trade: Trade, current_profit: float, current_time: datetime, trade_dur: int) -> Tuple[Optional[int], Optional[float]]: | |
| 342 | + | |
| 343 | + dynamic_roi = self.get_pair_params(trade.pair, 'dynamic_roi') | |
| 344 | + minimal_roi = self.get_pair_params(trade.pair, 'minimal_roi') | |
| 345 | + | |
| 346 | + if not dynamic_roi or not minimal_roi: | |
| 347 | + return None, None | |
| 348 | + | |
| 349 | + _, table_roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 350 | + | |
| 351 | + # see if we have the data we need to do this, otherwise fall back to the standard table | |
| 352 | + if self.custom_trade_info and trade and trade.pair in self.custom_trade_info: | |
| 353 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 354 | + dataframe, last_updated = self.dp.get_analyzed_dataframe(pair=trade.pair, timeframe=self.timeframe) | |
| 355 | + roc = dataframe['roc'].iat[-1] | |
| 356 | + atr = dataframe['atr'].iat[-1] | |
| 357 | + rmi_slow = dataframe['rmi-slow'].iat[-1] | |
| 358 | + rmi_trend = dataframe['rmi-up-trend'].iat[-1] | |
| 359 | + # If in backtest or hyperopt, get the indicator values out of the trades dict (Thanks @JoeSchr!) | |
| 360 | + else: | |
| 361 | + roc = self.custom_trade_info[trade.pair]['roc'].loc[current_time]['roc'] | |
| 362 | + atr = self.custom_trade_info[trade.pair]['atr'].loc[current_time]['atr'] | |
| 363 | + rmi_slow = self.custom_trade_info[trade.pair]['rmi-slow'].loc[current_time]['rmi-slow'] | |
| 364 | + rmi_trend = self.custom_trade_info[trade.pair]['rmi-up-trend'].loc[current_time]['rmi-up-trend'] | |
| 365 | + | |
| 366 | + d = dynamic_roi | |
| 367 | + open_rate = trade.open_rate | |
| 368 | + max_profit = trade.calc_profit_ratio(trade.max_rate) | |
| 369 | + | |
| 370 | + atr_roi = max(d['min-roc-atr'], ((open_rate + atr) / open_rate) - 1) | |
| 371 | + roc_roi = max(d['min-roc-atr'], (roc/100)) | |
| 372 | + | |
| 373 | + # atr as the fallback (if > min-roc-atr) | |
| 374 | + if d['fallback'] == 'atr': | |
| 375 | + min_roi = atr_roi | |
| 376 | + # roc as the fallback (if > min-roc-atr) | |
| 377 | + elif d['fallback'] == 'roc': | |
| 378 | + min_roi = roc_roi | |
| 379 | + # atr or table as the fallback (whichever is larger) | |
| 380 | + elif d['fallback'] == 'atr-table': | |
| 381 | + min_roi = max(table_roi, atr_roi) | |
| 382 | + # roc or table as the fallback (whichever is larger) | |
| 383 | + elif d['fallback'] == 'roc-table': | |
| 384 | + min_roi = max(table_roi, roc_roi) | |
| 385 | + # default to table | |
| 386 | + else: | |
| 387 | + min_roi = table_roi | |
| 388 | + | |
| 389 | + rmi_grow = cta.linear_growth(d['rmi-start'], d['rmi-end'], d['grow-delay'], d['grow-time'], trade_dur) | |
| 390 | + profit_factor = (1 - (rmi_slow / d['profit-factor'])) | |
| 391 | + pullback_buffer = (max_profit * profit_factor) | |
| 392 | + | |
| 393 | + # If we observe a strong upward trend and our current profit has not retreated from the peak by much, hold | |
| 394 | + if (rmi_trend == 1) and (rmi_slow > rmi_grow): | |
| 395 | + if (current_profit < pullback_buffer) and max_profit > min_roi: | |
| 396 | + # allow immediate bailout if we were above the ROI point and retreated below it | |
| 397 | + min_roi = current_profit / 2 | |
| 398 | + else: | |
| 399 | + min_roi = 100 | |
| 400 | + | |
| 401 | + else: | |
| 402 | + min_roi = table_roi | |
| 403 | + | |
| 404 | + return trade_dur, min_roi | |
| 405 | + | |
| 406 | + # Minor change to the usual method here to allow feeding the pair for per-pair settings | |
| 407 | + def min_roi_reached_entry(self, trade_dur: int, pair: str = 'backtest') -> Tuple[Optional[int], Optional[float]]: | |
| 408 | + minimal_roi = self.get_pair_params(pair, 'minimal_roi') | |
| 409 | + | |
| 410 | + roi_list = list(filter(lambda x: x <= trade_dur, minimal_roi.keys())) | |
| 411 | + if not roi_list: | |
| 412 | + return None, None | |
| 413 | + roi_entry = max(roi_list) | |
| 414 | + min_roi = minimal_roi[roi_entry] | |
| 415 | + | |
| 416 | + return roi_entry, min_roi | |
| 417 | + | |
| 418 | + # Change here to allow loading of the dynamic_roi settings | |
| 419 | + def min_roi_reached(self, trade: Trade, current_profit: float, current_time: datetime) -> bool: | |
| 420 | + trade_dur = int((current_time.timestamp() - trade.open_date_utc.timestamp()) // 60) | |
| 421 | + | |
| 422 | + if self.dynamic_roi and 'enabled' in self.dynamic_roi and self.dynamic_roi['enabled']: | |
| 423 | + _, roi = self.min_roi_reached_dynamic(trade, current_profit, current_time, trade_dur) | |
| 424 | + else: | |
| 425 | + _, roi = self.min_roi_reached_entry(trade_dur, trade.pair) | |
| 426 | + if roi is None: | |
| 427 | + return False | |
| 428 | + else: | |
| 429 | + return current_profit > roi | |
| 430 | + | |
| 431 | + """ | |
| 432 | + Trade Timeout Overloads | |
| 433 | + """ | |
| 434 | + def check_buy_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 435 | + bid_strategy = self.config.get('bid_strategy', {}) | |
| 436 | + ob = self.dp.orderbook(pair, 1) | |
| 437 | + current_price = ob[f"{bid_strategy['price_side']}s"][0][0] | |
| 438 | + if current_price > order['price'] * 1.01: | |
| 439 | + return True | |
| 440 | + return False | |
| 441 | + | |
| 442 | + def check_sell_timeout(self, pair: str, trade: Trade, order: dict, **kwargs) -> bool: | |
| 443 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 444 | + ob = self.dp.orderbook(pair, 1) | |
| 445 | + current_price = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 446 | + if current_price < order['price'] * 0.99: | |
| 447 | + return True | |
| 448 | + return False | |
| 449 | + | |
| 450 | + """ | |
| 451 | + Custom Methods | |
| 452 | + """ | |
| 453 | + # Get parameters for various settings on a per pair or group of pairs basis | |
| 454 | + # This function can probably be simplified dramatically | |
| 455 | + def get_pair_params(self, pair: str, params: str) -> Dict: | |
| 456 | + buy_params, sell_params = self.buy_params, self.sell_params | |
| 457 | + minimal_roi, dynamic_roi = self.minimal_roi, self.dynamic_roi | |
| 458 | + custom_stop = self.custom_stop | |
| 459 | + | |
| 460 | + if self.custom_pair_params: | |
| 461 | + # custom_params = next(item for item in self.custom_pair_params if pair in item['pairs']) | |
| 462 | + for item in self.custom_pair_params: | |
| 463 | + if 'pairs' in item and pair in item['pairs']: | |
| 464 | + custom_params = item | |
| 465 | + if 'buy_params' in custom_params: | |
| 466 | + buy_params = custom_params['buy_params'] | |
| 467 | + if 'sell_params' in custom_params: | |
| 468 | + sell_params = custom_params['sell_params'] | |
| 469 | + if 'minimal_roi' in custom_params: | |
| 470 | + minimal_roi = custom_params['minimal_roi'] | |
| 471 | + if 'custom_stop' in custom_params: | |
| 472 | + custom_stop = custom_params['custom_stop'] | |
| 473 | + if 'dynamic_roi' in custom_params: | |
| 474 | + dynamic_roi = custom_params['dynamic_roi'] | |
| 475 | + break | |
| 476 | + | |
| 477 | + if params == 'buy': | |
| 478 | + return buy_params | |
| 479 | + if params == 'sell': | |
| 480 | + return sell_params | |
| 481 | + if params == 'minimal_roi': | |
| 482 | + return minimal_roi | |
| 483 | + if params == 'custom_stop': | |
| 484 | + return custom_stop | |
| 485 | + if params == 'dynamic_roi': | |
| 486 | + return dynamic_roi | |
| 487 | + | |
| 488 | + return False | |
| 489 | + | |
| 490 | + # Get the current price from the exchange (or local cache) | |
| 491 | + def get_current_price(self, pair: str, refresh: bool) -> float: | |
| 492 | + if not refresh: | |
| 493 | + rate = self.custom_current_price_cache.get(pair) | |
| 494 | + # Check if cache has been invalidated | |
| 495 | + if rate: | |
| 496 | + return rate | |
| 497 | + | |
| 498 | + ask_strategy = self.config.get('ask_strategy', {}) | |
| 499 | + if ask_strategy.get('use_order_book', False): | |
| 500 | + ob = self.dp.orderbook(pair, 1) | |
| 501 | + rate = ob[f"{ask_strategy['price_side']}s"][0][0] | |
| 502 | + else: | |
| 503 | + ticker = self.dp.ticker(pair) | |
| 504 | + rate = ticker['last'] | |
| 505 | + | |
| 506 | + self.custom_current_price_cache[pair] = rate | |
| 507 | + return rate | |
| 508 | + | |
| 509 | + """ | |
| 510 | + Stripped down version from Schism, meant only to update the price data a bit | |
| 511 | + more frequently than the default instead of getting all sorts of trade information | |
| 512 | + """ | |
| 513 | + def populate_trades(self, pair: str) -> dict: | |
| 514 | + # Initialize the trades dict if it doesn't exist, persist it otherwise | |
| 515 | + if not pair in self.custom_trade_info: | |
| 516 | + self.custom_trade_info[pair] = {} | |
| 517 | + | |
| 518 | + # init the temp dicts and set the trade stuff to false | |
| 519 | + trade_data = {} | |
| 520 | + trade_data['active_trade'] = False | |
| 521 | + | |
| 522 | + # active trade stuff only works in live and dry, not backtest | |
| 523 | + if self.config['runmode'].value in ('live', 'dry_run'): | |
| 524 | + | |
| 525 | + # find out if we have an open trade for this pair | |
| 526 | + active_trade = Trade.get_trades([Trade.pair == pair, Trade.is_open.is_(True),]).all() | |
| 527 | + | |
| 528 | + # if so, get some information | |
| 529 | + if active_trade: | |
| 530 | + # get current price and update the min/max rate | |
| 531 | + current_rate = self.get_current_price(pair, True) | |
| 532 | + active_trade[0].adjust_min_max_rates(current_rate) | |
| 533 | + | |
| 534 | + return trade_data | |
| 535 | + | |
| 536 | +# Sub-strategy with parameters specific to BTC stake | |
| 537 | +class Solipsis3_BTC(Solipsis3): | |
| 538 | + | |
| 539 | + timeframe = '15m' | |
| 540 | + inf_timeframe = '1h' | |
| 541 | + | |
| 542 | + minimal_roi = { | |
| 543 | + "0": 0.01, | |
| 544 | + "720": 0.005, | |
| 545 | + "1440": 0 | |
| 546 | + } | |
| 547 | + | |
| 548 | +# Sub-strategy with parameters specific to ETH stake | |
| 549 | +class Solipsis3_ETH(Solipsis3): | |
| 550 | + | |
| 551 | + timeframe = '15m' | |
| 552 | + inf_timeframe = '1h' | |
| 553 | + | |
| 554 | + minimal_roi = { | |
| 555 | + "0": 0.01, | |
| 556 | + "720": 0.005, | |
| 557 | + "1440": 0 | |
| 558 | + } | |
| No newline at the end of the file |